diff --git a/.gitignore b/.gitignore index b38a3f1e3..ca18feb5b 100644 --- a/.gitignore +++ b/.gitignore @@ -29,7 +29,9 @@ build_xc *.user.* *~ +# build system build.*/ +extdep/install *.pyc diff --git a/CMakeLists.txt b/CMakeLists.txt index d8c517fef..02e3a1a05 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,8 @@ # cmake global -cmake_minimum_required(VERSION 2.8.9) +cmake_minimum_required(VERSION 2.8.12) +# let cmake autolink dependencies on windows +# it's specified globally, cause qt libraries requires that on windows and they are also found globally +cmake_policy(SET CMP0020 NEW) project(ethereum) @@ -12,18 +15,14 @@ list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake") # Normally, set(...CACHE...) creates cache variables, but does not modify them. function(createDefaultCacheConfig) set(HEADLESS OFF CACHE BOOL "Do not compile GUI (AlethZero)") - set(LANGUAGES OFF CACHE BOOL "Limit build to Serpent/LLL tools") set(VMTRACE OFF CACHE BOOL "VM tracing and run-time checks (useful for cross-implementation VM debugging)") set(PARANOIA OFF CACHE BOOL "Additional run-time checks") + set(JSONRPC ON CACHE BOOL "Build with jsonprc. default on") endfunction() # propagates CMake configuration options to the compiler function(configureProject) - if (LANGUAGES) - add_definitions(-DETH_LANGUAGES) - endif () - if (PARANOIA) if ("${CMAKE_BUILD_TYPE}" STREQUAL "Debug") add_definitions(-DETH_PARANOIA) @@ -42,6 +41,7 @@ function(configureProject) endfunction() + function(createBuildInfo) # Set build platform; to be written to BuildInfo.h if (CMAKE_COMPILER_IS_MINGW) @@ -50,7 +50,7 @@ function(createBuildInfo) set(ETH_BUILD_PLATFORM "${ETH_BUILD_PLATFORM}/msys") elseif (CMAKE_COMPILER_IS_GNUCXX) set(ETH_BUILD_PLATFORM "${ETH_BUILD_PLATFORM}/g++") - elseif (CMAKE_COMPILER_IS_MSVC) + elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC") set(ETH_BUILD_PLATFORM "${ETH_BUILD_PLATFORM}/msvc") elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang") set(ETH_BUILD_PLATFORM "${ETH_BUILD_PLATFORM}/clang") @@ -58,14 +58,23 @@ function(createBuildInfo) set(ETH_BUILD_PLATFORM "${ETH_BUILD_PLATFORM}/unknown") endif () + #cmake build type may be not specified when using msvc + if (${CMAKE_BUILD_TYPE}) + set(_cmake_build_type ${CMAKE_BUILD_TYPE}) + else() + set(_cmake_build_type "undefined") + endif() + # Generate header file containing useful build information - add_custom_target(BuildInfo.h ALL COMMAND bash ${CMAKE_CURRENT_SOURCE_DIR}/BuildInfo.sh ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_BUILD_TYPE} ${ETH_BUILD_PLATFORM}) + add_custom_target(BuildInfo.h ALL COMMAND bash ${CMAKE_CURRENT_SOURCE_DIR}/BuildInfo.sh ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR} ${_cmake_build_type} ${ETH_BUILD_PLATFORM}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) set(CMAKE_INCLUDE_CURRENT_DIR ON) set(SRC_LIST BuildInfo.h) endfunction() + + ###################################################################################################### @@ -75,7 +84,7 @@ cmake_policy(SET CMP0015 NEW) createDefaultCacheConfig() configureProject() -message("-- LANGUAGES: ${LANGUAGES}; VMTRACE: ${VMTRACE}; PARANOIA: ${PARANOIA}; HEADLESS: ${HEADLESS}") +message("-- VMTRACE: ${VMTRACE}; PARANOIA: ${PARANOIA}; HEADLESS: ${HEADLESS}; JSONRPC: ${JSONRPC}") # Default TARGET_PLATFORM to "linux". @@ -88,20 +97,13 @@ if ("${TARGET_PLATFORM}" STREQUAL "linux") set(CMAKE_THREAD_LIBS_INIT pthread) endif () -# Set default build type to Release w/debug info -# if(NOT CMAKE_CONFIGURATION_TYPES AND NOT CMAKE_BUILD_TYPE) -# set(CMAKE_BUILD_TYPE RelWithDebInfo) -# endif() - - include(EthCompilerSettings) message("-- CXXFLAGS: ${CMAKE_CXX_FLAGS}") -#add_definitions("-DETH_BUILD_TYPE=${ETH_BUILD_TYPE}") -#add_definitions("-DETH_BUILD_PLATFORM=${ETH_BUILD_PLATFORM}") - -include(EthDependenciesDeprecated) +# this must be an include, as a function it would messs up with variable scope! +include(EthDependencies) +include(EthExecutableHelper) createBuildInfo() @@ -110,64 +112,48 @@ add_subdirectory(libevmcore) add_subdirectory(liblll) add_subdirectory(libserpent) add_subdirectory(libsolidity) -if(NOT APPLE) - if(PYTHON_LS) - add_subdirectory(libpyserpent) - endif() -endif() - add_subdirectory(lllc) add_subdirectory(solc) add_subdirectory(sc) -if (JSONRPC_LS) + +if (JSONRPC) add_subdirectory(libweb3jsonrpc) endif() -if (NOT LANGUAGES) - add_subdirectory(secp256k1) - add_subdirectory(libp2p) - add_subdirectory(libdevcrypto) - add_subdirectory(libwhisper) - - add_subdirectory(libethcore) - add_subdirectory(libevm) - add_subdirectory(libethereum) -# add_subdirectory(libethereumx) # TODO remove - - add_subdirectory(libwebthree) - add_subdirectory(test) - add_subdirectory(eth) - if("x${CMAKE_BUILD_TYPE}" STREQUAL "xDebug") - add_subdirectory(exp) - endif () - if(NOT ("${TARGET_PLATFORM}" STREQUAL "w64")) - add_subdirectory(neth) - endif () - if(QTQML) - add_definitions(-DETH_QTQML) - endif() - if(NOT HEADLESS) - if ("${TARGET_PLATFORM}" STREQUAL "w64") - cmake_policy(SET CMP0020 NEW) - endif () - if (NOT JSONRPC_LS) - message(FATAL_ERROR "Alethzero requires jsonrpc.") - endif() - - add_subdirectory(libjsqrc) - add_subdirectory(libqethereum) - add_subdirectory(alethzero) - add_subdirectory(third) - if(QTQML) - #add_subdirectory(iethxi) - #add_subdirectory(walleth) // resurect once we want to submit ourselves to QML. - endif() - endif() -endif() +add_subdirectory(secp256k1) +add_subdirectory(libp2p) +add_subdirectory(libdevcrypto) +add_subdirectory(libwhisper) +add_subdirectory(libethcore) +add_subdirectory(libevm) +add_subdirectory(libethereum) + +add_subdirectory(libwebthree) +add_subdirectory(test) +add_subdirectory(eth) +if("x${CMAKE_BUILD_TYPE}" STREQUAL "xDebug") + add_subdirectory(exp) +endif () + +# TODO check msvc +if(NOT ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC")) + add_subdirectory(neth) +endif () + +if (NOT HEADLESS) + + add_subdirectory(libjsqrc) + add_subdirectory(libqethereum) + add_subdirectory(alethzero) + add_subdirectory(third) + add_subdirectory(mix) + +endif() enable_testing() add_test(NAME alltests WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/test COMMAND testeth) #unset(TARGET_PLATFORM CACHE) + diff --git a/alethzero/EthereumMacOSXBundleInfo.plist.in b/EthereumMacOSXBundleInfo.plist.in similarity index 100% rename from alethzero/EthereumMacOSXBundleInfo.plist.in rename to EthereumMacOSXBundleInfo.plist.in diff --git a/README.md b/README.md index 23a202510..8b5ff903d 100644 --- a/README.md +++ b/README.md @@ -36,5 +36,5 @@ Please read [CodingStandards.txt](CodingStandards.txt) thoroughly before making libweb3jsonrpc/abstractwebthreestubserver.h is autogenerated from the jsonrpcstub executable that comes with the libjsonrpc library (json-rpc-cpp project). It shouldn't be maually altered. ```bash -jsonrpcstub -s -c spec.json WebThreeStub +jsonrpcstub spec.json --cpp-server=AbstractWebThreeStubServer ``` diff --git a/alethzero/CMakeLists.txt b/alethzero/CMakeLists.txt index 01dfb88dc..c4237eaee 100644 --- a/alethzero/CMakeLists.txt +++ b/alethzero/CMakeLists.txt @@ -1,101 +1,53 @@ +cmake_policy(SET CMP0015 NEW) +# let cmake autolink dependencies on windows +cmake_policy(SET CMP0020 NEW) +# this policy was introduced in cmake 3.0 +# remove if, once 3.0 will be used on unix +if (${CMAKE_MAJOR_VERSION} GREATER 2) + cmake_policy(SET CMP0043 OLD) +endif() + set(CMAKE_INCLUDE_CURRENT_DIR ON) aux_source_directory(. SRC_LIST) -include_directories(..) -if (APPLE) - # Add homebrew path for qt5 - set(CMAKE_PREFIX_PATH /usr/local/opt/qt5) - include_directories(/usr/local/opt/qt5/include /usr/local/include) -elseif ("${TARGET_PLATFORM}" STREQUAL "w64") - set(SRC_LIST ${SRC_LIST} ../windows/qt_plugin_import.cpp) - include_directories(/usr/x86_64-w64-mingw32/include /usr/x86_64-w64-mingw32/include/QtCore /usr/x86_64-w64-mingw32/include/QtGui /usr/x86_64-w64-mingw32/include/QtQuick /usr/x86_64-w64-mingw32/include/QtQml /usr/x86_64-w64-mingw32/include/QtNetwork /usr/x86_64-w64-mingw32/include/QtWidgets /usr/x86_64-w64-mingw32/include/QtWebKit /usr/x86_64-w64-mingw32/include/QtWebKitWidgets) -elseif (UNIX) - set(CMAKE_PREFIX_PATH ${CMAKE_PREFIX_PATH} ";$ENV{QTDIR}/lib/cmake") -endif () - -find_package(Qt5Core REQUIRED) -find_package(Qt5Gui REQUIRED) -find_package(Qt5Quick REQUIRED) -find_package(Qt5Qml REQUIRED) -find_package(Qt5Network REQUIRED) -find_package(Qt5Widgets REQUIRED) -find_package(Qt5WebKit REQUIRED) -find_package(Qt5WebKitWidgets REQUIRED) +include_directories(${JSON_RPC_CPP_INCLUDE_DIRS}) +include_directories(..) qt5_wrap_ui(ui_Main.h Main.ui) -# Set name of binary and add_executable() file(GLOB HEADERS "*.h") -if (APPLE) - set(EXECUTEABLE AlethZero) - set(BIN_INSTALL_DIR ".") - set(DOC_INSTALL_DIR ".") - - set(PROJECT_VERSION "${ETH_VERSION}") - set(MACOSX_BUNDLE_INFO_STRING "${PROJECT_NAME} ${PROJECT_VERSION}") - set(MACOSX_BUNDLE_BUNDLE_VERSION "${PROJECT_NAME} ${PROJECT_VERSION}") - set(MACOSX_BUNDLE_LONG_VERSION_STRING "${PROJECT_NAME} ${PROJECT_VERSION}") - set(MACOSX_BUNDLE_SHORT_VERSION_STRING "${PROJECT_VERSION}") - set(MACOSX_BUNDLE_COPYRIGHT "${PROJECT_COPYRIGHT_YEAR} ${PROJECT_VENDOR}") - set(MACOSX_BUNDLE_GUI_IDENTIFIER "${PROJECT_DOMAIN_SECOND}.${PROJECT_DOMAIN_FIRST}") - set(MACOSX_BUNDLE_BUNDLE_NAME ${EXECUTEABLE}) - set(MACOSX_BUNDLE_ICON_FILE alethzero) - include(BundleUtilities) - - add_executable(${EXECUTEABLE} MACOSX_BUNDLE alethzero.icns Main.ui ${SRC_LIST} ${HEADERS}) - set_target_properties(${EXECUTEABLE} PROPERTIES MACOSX_BUNDLE_INFO_PLIST "${CMAKE_CURRENT_SOURCE_DIR}/EthereumMacOSXBundleInfo.plist.in") - SET_SOURCE_FILES_PROPERTIES(${EXECUTEABLE} PROPERTIES MACOSX_PACKAGE_LOCATION MacOS) - SET_SOURCE_FILES_PROPERTIES(${MACOSX_BUNDLE_ICON_FILE}.icns PROPERTIES MACOSX_PACKAGE_LOCATION "Resources") - -else () - set(EXECUTEABLE alethzero) - add_executable(${EXECUTEABLE} Main.ui ${SRC_LIST} ${HEADERS}) -endif () - -qt5_use_modules(${EXECUTEABLE} Core)# Gui Widgets Network WebKit WebKitWidgets) -target_link_libraries(${EXECUTEABLE} webthree qethereum ethereum evm ethcore devcrypto secp256k1 gmp ${CRYPTOPP_LS} serpent lll solidity evmcore devcore web3jsonrpc jsqrc) if (APPLE) - # First have qt5 install plugins and frameworks - add_custom_command(TARGET ${EXECUTEABLE} POST_BUILD - COMMAND /usr/local/opt/qt5/bin/macdeployqt ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_CFG_INTDIR}/${EXECUTEABLE}.app - WORKING_DIRECTORY ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}) - - # This tool and next will inspect linked libraries in order to determine which dependencies are required - if (${CMAKE_CFG_INTDIR} STREQUAL ".") - set(APP_BUNDLE_PATH "${CMAKE_CURRENT_BINARY_DIR}/${EXECUTEABLE}.app") - else () - set(APP_BUNDLE_PATH "${CMAKE_CURRENT_BINARY_DIR}/\$ENV{CONFIGURATION}/${EXECUTEABLE}.app") - endif () - install(CODE " - include(BundleUtilities) - set(BU_CHMOD_BUNDLE_ITEMS 1) - fixup_bundle(\"${APP_BUNDLE_PATH}\" \"${BUNDLELIBS}\" \"../libqethereum ../libethereum ../secp256k1\") - " COMPONENT RUNTIME ) - # Cleanup duplicate libs from macdeployqt - install(CODE " - file(GLOB LINGER_RM \"${APP_BUNDLE_PATH}/Contents/Frameworks/*.dylib\") - if (LINGER_RM) - file(REMOVE \${LINGER_RM}) - endif () - ") -elseif ("${TARGET_PLATFORM}" STREQUAL "w64") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fno-keep-inline-dllexport -static-libgcc -static-libstdc++ -static") - set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,-s -Wl,-subsystem,windows -mthreads -L/usr/x86_64-w64-mingw32/plugins/platforms") - target_link_libraries(${EXECUTEABLE} gcc) - target_link_libraries(${EXECUTEABLE} mingw32 qtmain mswsock iphlpapi qwindows shlwapi Qt5PlatformSupport opengl32 gdi32 comdlg32 oleaut32 imm32 winmm ole32 uuid ws2_32) - target_link_libraries(${EXECUTEABLE} boost_system-mt-s) - target_link_libraries(${EXECUTEABLE} boost_filesystem-mt-s) - target_link_libraries(${EXECUTEABLE} boost_thread_win32-mt-s) - target_link_libraries(${EXECUTEABLE} crypt32) - target_link_libraries(${EXECUTEABLE} Qt5PlatformSupport) - set(CMAKE_SHARED_LIBRARY_LINK_CXX_FLAGS) -elseif (UNIX) + set(EXECUTABLE AlethZero) else () - target_link_libraries(${EXECUTEABLE} boost_system) - target_link_libraries(${EXECUTEABLE} boost_filesystem) - find_package(Threads REQUIRED) - target_link_libraries(${EXECUTEABLE} ${CMAKE_THREAD_LIBS_INIT}) - install( TARGETS ${EXECUTEABLE} RUNTIME DESTINATION bin ) + set(EXECUTABLE alethzero) endif () + +# eth_add_executable is defined in cmake/EthExecutableHelper.cmake +eth_add_executable(${EXECUTABLE} + ICON alethzero + UI_RESOURCES alethzero.icns Main.ui +) + +add_dependencies(${EXECUTABLE} BuildInfo.h) + +target_link_libraries(${EXECUTABLE} Qt5::Core) +target_link_libraries(${EXECUTABLE} ${JSONCPP_LIBRARIES}) +target_link_libraries(${EXECUTABLE} webthree) +target_link_libraries(${EXECUTABLE} qethereum) +target_link_libraries(${EXECUTABLE} ethereum) +target_link_libraries(${EXECUTABLE} evm) +target_link_libraries(${EXECUTABLE} ethcore) +target_link_libraries(${EXECUTABLE} devcrypto) +target_link_libraries(${EXECUTABLE} secp256k1) +target_link_libraries(${EXECUTABLE} serpent) +target_link_libraries(${EXECUTABLE} lll) +target_link_libraries(${EXECUTABLE} solidity) +target_link_libraries(${EXECUTABLE} evmcore) +target_link_libraries(${EXECUTABLE} devcore) +target_link_libraries(${EXECUTABLE} web3jsonrpc) +target_link_libraries(${EXECUTABLE} jsqrc) + +# eth_install_executable is defined in cmake/EthExecutableHelper.cmake +eth_install_executable(${EXECUTABLE}) diff --git a/alethzero/MainWin.cpp b/alethzero/MainWin.cpp index 8fe76e24b..122085225 100644 --- a/alethzero/MainWin.cpp +++ b/alethzero/MainWin.cpp @@ -43,6 +43,7 @@ #include #include #include +#include #include #include #include @@ -153,9 +154,8 @@ Main::Main(QWidget *parent) : m_webThree.reset(new WebThreeDirect(string("AlethZero/v") + dev::Version + "/" DEV_QUOTED(ETH_BUILD_TYPE) "/" DEV_QUOTED(ETH_BUILD_PLATFORM), getDataDir() + "/AlethZero", false, {"eth", "shh"})); - // w3stubserver, on dealloc, deletes m_qwebConnector - m_qwebConnector = new QWebThreeConnector(); // owned by WebThreeStubServer - m_server.reset(new OurWebThreeStubServer(m_qwebConnector, *web3(), keysAsVector(m_myKeys))); + m_qwebConnector.reset(new QWebThreeConnector()); + m_server.reset(new OurWebThreeStubServer(*m_qwebConnector, *web3(), keysAsVector(m_myKeys))); connect(&*m_server, SIGNAL(onNewId(QString)), SLOT(addNewId(QString))); m_server->setIdentities(keysAsVector(owned())); m_server->StartListening(); @@ -241,7 +241,7 @@ void Main::onKeysChanged() installBalancesWatch(); } -unsigned Main::installWatch(dev::eth::MessageFilter const& _tf, std::function const& _f) +unsigned Main::installWatch(dev::eth::LogFilter const& _tf, std::function const& _f) { auto ret = ethereum()->installWatch(_tf); m_handlers[ret] = _f; @@ -263,8 +263,8 @@ void Main::uninstallWatch(unsigned _w) void Main::installWatches() { - installWatch(dev::eth::MessageFilter().altered(c_config, 0), [=](){ installNameRegWatch(); }); - installWatch(dev::eth::MessageFilter().altered(c_config, 1), [=](){ installCurrenciesWatch(); }); + installWatch(dev::eth::LogFilter().address(c_config), [=]() { installNameRegWatch(); }); + installWatch(dev::eth::LogFilter().address(c_config), [=]() { installCurrenciesWatch(); }); installWatch(dev::eth::PendingChangedFilter, [=](){ onNewPending(); }); installWatch(dev::eth::ChainChangedFilter, [=](){ onNewBlock(); }); } @@ -272,29 +272,26 @@ void Main::installWatches() void Main::installNameRegWatch() { uninstallWatch(m_nameRegFilter); - m_nameRegFilter = installWatch(dev::eth::MessageFilter().altered((u160)ethereum()->stateAt(c_config, 0)), [=](){ onNameRegChange(); }); + m_nameRegFilter = installWatch(dev::eth::LogFilter().address((u160)ethereum()->stateAt(c_config, 0)), [=](){ onNameRegChange(); }); } void Main::installCurrenciesWatch() { uninstallWatch(m_currenciesFilter); - m_currenciesFilter = installWatch(dev::eth::MessageFilter().altered((u160)ethereum()->stateAt(c_config, 1)), [=](){ onCurrenciesChange(); }); + m_currenciesFilter = installWatch(dev::eth::LogFilter().address((u160)ethereum()->stateAt(c_config, 1)), [=](){ onCurrenciesChange(); }); } void Main::installBalancesWatch() { - dev::eth::MessageFilter tf; + dev::eth::LogFilter tf; vector
altCoins; Address coinsAddr = right160(ethereum()->stateAt(c_config, 1)); for (unsigned i = 0; i < ethereum()->stateAt(coinsAddr, 0); ++i) altCoins.push_back(right160(ethereum()->stateAt(coinsAddr, i + 1))); for (auto i: m_myKeys) - { - tf.altered(i.address()); for (auto c: altCoins) - tf.altered(c, (u160)i.address()); - } + tf.address(c).topic(h256(i.address(), h256::AlignRight)); uninstallWatch(m_balancesFilter); m_balancesFilter = installWatch(tf, [=](){ onBalancesChange(); }); @@ -353,8 +350,16 @@ void Main::on_enableOptimizer_triggered() on_data_textChanged(); } +QString Main::contents(QString _s) +{ + return QString::fromStdString(dev::asString(dev::contents(_s.toStdString()))); +} + void Main::load(QString _s) { + QString contents = QString::fromStdString(dev::asString(dev::contents(_s.toStdString()))); + ui->webView->page()->currentFrame()->evaluateJavaScript(contents); + /* QFile fin(_s); if (!fin.open(QFile::ReadOnly)) return; @@ -375,7 +380,7 @@ void Main::load(QString _s) //eval(line); line.clear(); } - } + }*/ } void Main::on_loadJS_triggered() @@ -526,7 +531,7 @@ QString Main::lookup(QString const& _a) const void Main::on_about_triggered() { - QMessageBox::about(this, "About AlethZero PoC-" + QString(dev::Version).section('.', 1, 1), QString("AlethZero/v") + dev::Version + "/" DEV_QUOTED(ETH_BUILD_TYPE) "/" DEV_QUOTED(ETH_BUILD_PLATFORM) "\n" DEV_QUOTED(ETH_COMMIT_HASH) + (ETH_CLEAN_REPO ? "\nCLEAN" : "\n+ LOCAL CHANGES") + "\n\nBy Gav Wood, 2014.\nBased on a design by Vitalik Buterin.\n\nThanks to the various contributors including: Alex Leverington, Tim Hughes, caktux, Eric Lombrozo, Marko Simovic."); + QMessageBox::about(this, "About AlethZero PoC-" + QString(dev::Version).section('.', 1, 1), QString("AlethZero/v") + dev::Version + "/" DEV_QUOTED(ETH_BUILD_TYPE) "/" DEV_QUOTED(ETH_BUILD_PLATFORM) "\n" DEV_QUOTED(ETH_COMMIT_HASH) + (ETH_CLEAN_REPO ? "\nCLEAN" : "\n+ LOCAL CHANGES") + "\n\nBerlin ÐΞV team, 2014.\nOriginally by Gav Wood. Based on a design by Vitalik Buterin.\n\nThanks to the various contributors including: Tim Hughes, caktux, Eric Lombrozo, Marko Simovic."); } void Main::on_paranoia_triggered() @@ -679,7 +684,7 @@ void Main::on_importKeyFile_triggered() try { js::mValue val; - json_spirit::read_string(asString(contents(s.toStdString())), val); + json_spirit::read_string(asString(dev::contents(s.toStdString())), val); auto obj = val.get_obj(); if (obj["encseed"].type() == js::str_type) { @@ -948,7 +953,7 @@ void Main::refreshBlockCount() cwatch << "refreshBlockCount()"; auto d = ethereum()->blockChain().details(); auto diff = BlockInfo(ethereum()->blockChain().block()).difficulty; - ui->blockCount->setText(QString("%6 #%1 @%3 T%2 N%4 D%5").arg(d.number).arg(toLog2(d.totalDifficulty)).arg(toLog2(diff)).arg(dev::eth::c_protocolVersion).arg(dev::eth::c_databaseVersion).arg(m_privateChain.size() ? "[" + m_privateChain + "] " : "testnet")); + ui->blockCount->setText(QString("%6 #%1 @%3 T%2 PV%4 D%5").arg(d.number).arg(toLog2(d.totalDifficulty)).arg(toLog2(diff)).arg(dev::eth::c_protocolVersion).arg(dev::eth::c_databaseVersion).arg(m_privateChain.size() ? "[" + m_privateChain + "] " : "testnet")); } static bool blockMatch(string const& _f, dev::eth::BlockDetails const& _b, h256 _h, BlockChain const& _bc) @@ -1254,13 +1259,19 @@ void Main::on_blocks_currentItemChanged() s << "
D/TD: 2^" << log2((double)info.difficulty) << "/2^" << log2((double)details.totalDifficulty) << ""; s << "   Children: " << details.children.size() << ""; s << "
Gas used/limit: " << info.gasUsed << "/" << info.gasLimit << ""; - s << "   Minimum gas price: " << formatBalance(info.minGasPrice) << ""; s << "
Coinbase: " << pretty(info.coinbaseAddress).toHtmlEscaped().toStdString() << " " << info.coinbaseAddress; s << "
Nonce: " << info.nonce << ""; + s << "
Hash w/o nonce: " << info.headerHash(WithoutNonce) << ""; + s << "
Difficulty: " << info.difficulty << ""; + if (info.number) + s << "
Proof-of-Work: " << ProofOfWork::eval(info.headerHash(WithoutNonce), info.nonce) << " <= " << (h256)u256((bigint(1) << 256) / info.difficulty) << ""; + else + s << "
Proof-of-Work: Phil has nothing to prove"; s << "
Parent: " << info.parentHash << ""; - s << "
Bloom: " << details.bloom << ""; +// s << "
Bloom: " << details.bloom << ""; s << "
Log Bloom: " << info.logBloom << ""; s << "
Transactions: " << block[1].itemCount() << " @" << info.transactionsRoot << ""; + s << "
Receipts: @" << info.receiptsRoot << ":"; s << "
Uncles: " << block[2].itemCount() << " @" << info.sha3Uncles << ""; for (auto u: block[2]) { @@ -1272,10 +1283,12 @@ void Main::on_blocks_currentItemChanged() if (info.parentHash) s << "
Pre: " << BlockInfo(ethereum()->blockChain().block(info.parentHash)).stateRoot << ""; else - s << "
Pre: Nothing is before the Gensesis"; + s << "
Pre: Nothing is before Phil"; for (auto const& i: block[1]) s << "
" << sha3(i.data()).abridged();// << ": " << i[1].toHash() << " [" << i[2].toInt() << " used]"; s << "
Post: " << info.stateRoot << ""; + s << "
Dump: " << toHex(block[0].data()) << ""; + s << "
Receipts-Hex: " << toHex(ethereum()->blockChain().receipts(h).rlp()) << "
"; } else { @@ -1283,6 +1296,7 @@ void Main::on_blocks_currentItemChanged() Transaction tx(block[1][txi].data()); auto ss = tx.safeSender(); h256 th = sha3(rlpList(ss, tx.nonce())); + TransactionReceipt receipt = ethereum()->blockChain().receipts(h).receipts[txi]; s << "

" << th << "

"; s << "

" << h << "[" << txi << "]

"; s << "
From: " << pretty(ss).toHtmlEscaped().toStdString() << " " << ss; @@ -1298,6 +1312,11 @@ void Main::on_blocks_currentItemChanged() s << "
R: " << hex << nouppercase << tx.signature().r << ""; s << "
S: " << hex << nouppercase << tx.signature().s << ""; s << "
Msg: " << tx.sha3(eth::WithoutSignature) << ""; + s << "
Log Bloom: " << receipt.bloom() << "
"; + s << "
Hex: " << toHex(block[1][txi].data()) << "
"; + auto r = receipt.rlp(); + s << "
Receipt: " << toString(RLP(r)) << "
"; + s << "
Receipt-Hex: " << toHex(receipt.rlp()) << "
"; if (tx.isCreation()) { if (tx.data().size()) @@ -1331,7 +1350,7 @@ void Main::on_debugCurrent_triggered() { unsigned txi = item->data(Qt::UserRole + 1).toInt(); m_executiveState = ethereum()->state(txi + 1, h); - m_currentExecution = unique_ptr(new Executive(m_executiveState)); + m_currentExecution = unique_ptr(new Executive(m_executiveState, 0)); Transaction t = m_executiveState.pending()[txi]; m_executiveState = m_executiveState.fromPending(txi); auto r = t.rlp(); @@ -1379,10 +1398,10 @@ void Main::populateDebugger(dev::bytesConstRef _r) bytesConstRef lastData; h256 lastHash; h256 lastDataHash; - auto onOp = [&](uint64_t steps, Instruction inst, dev::bigint newMemSize, dev::bigint gasCost, void* voidVM, void const* voidExt) + auto onOp = [&](uint64_t steps, Instruction inst, dev::bigint newMemSize, dev::bigint gasCost, dev::eth::VM* voidVM, dev::eth::ExtVMFace const* voidExt) { - dev::eth::VM& vm = *(dev::eth::VM*)voidVM; - dev::eth::ExtVM const& ext = *(dev::eth::ExtVM const*)voidExt; + dev::eth::VM& vm = *voidVM; + dev::eth::ExtVM const& ext = *static_cast(voidExt); if (ext.code != lastExtCode) { lastExtCode = ext.code; @@ -1481,58 +1500,6 @@ void Main::on_destination_currentTextChanged() // updateFee(); } -static bytes dataFromText(QString _s) -{ - bytes ret; - while (_s.size()) - { - QRegExp r("(@|\\$)?\"([^\"]*)\"(\\s.*)?"); - QRegExp d("(@|\\$)?([0-9]+)(\\s*(ether)|(finney)|(szabo))?(\\s.*)?"); - QRegExp h("(@|\\$)?(0x)?(([a-fA-F0-9])+)(\\s.*)?"); - if (r.exactMatch(_s)) - { - for (auto i: r.cap(2)) - ret.push_back((byte)i.toLatin1()); - if (r.cap(1) != "$") - for (int i = r.cap(2).size(); i < 32; ++i) - ret.push_back(0); - else - ret.push_back(0); - _s = r.cap(3); - } - else if (d.exactMatch(_s)) - { - u256 v(d.cap(2).toStdString()); - if (d.cap(6) == "szabo") - v *= dev::eth::szabo; - else if (d.cap(5) == "finney") - v *= dev::eth::finney; - else if (d.cap(4) == "ether") - v *= dev::eth::ether; - bytes bs = dev::toCompactBigEndian(v); - if (d.cap(1) != "$") - for (auto i = bs.size(); i < 32; ++i) - ret.push_back(0); - for (auto b: bs) - ret.push_back(b); - _s = d.cap(7); - } - else if (h.exactMatch(_s)) - { - bytes bs = fromHex((((h.cap(3).size() & 1) ? "0" : "") + h.cap(3)).toStdString()); - if (h.cap(1) != "$") - for (auto i = bs.size(); i < 32; ++i) - ret.push_back(0); - for (auto b: bs) - ret.push_back(b); - _s = h.cap(5); - } - else - _s = _s.mid(1); - } - return ret; -} - static shh::Topic topicFromText(QString _s) { shh::BuildTopic ret; @@ -1602,15 +1569,15 @@ void Main::on_data_textChanged() } else if (src.substr(0, 8) == "contract") // improve this heuristic { - shared_ptr scanner = make_shared(); + dev::solidity::CompilerStack compiler; try { - m_data = dev::solidity::CompilerStack::compile(src, scanner, m_enableOptimizer); + m_data = compiler.compile(src, m_enableOptimizer); } catch (dev::Exception const& exception) { ostringstream error; - solidity::SourceReferenceFormatter::printExceptionInformation(error, exception, "Error", *scanner); + solidity::SourceReferenceFormatter::printExceptionInformation(error, exception, "Error", compiler); solidity = "

Solidity

" + QString::fromStdString(error.str()).toHtmlEscaped() + "
"; } catch (...) @@ -1653,18 +1620,18 @@ void Main::on_data_textChanged() errs.append("
" + QString::fromStdString(i).toHtmlEscaped() + "
"); } ui->code->setHtml(errs + lll + solidity + "

Code

" + QString::fromStdString(disassemble(m_data)).toHtmlEscaped()); - ui->gas->setMinimum((qint64)Client::txGas(m_data.size(), 0)); + ui->gas->setMinimum((qint64)Client::txGas(m_data, 0)); if (!ui->gas->isEnabled()) ui->gas->setValue(m_backupGas); ui->gas->setEnabled(true); } else { - m_data = dataFromText(ui->data->toPlainText()); + m_data = parseData(ui->data->toPlainText().toStdString()); ui->code->setHtml(QString::fromStdString(dev::memDump(m_data, 8, true))); if (ethereum()->codeAt(fromString(ui->destination->currentText()), 0).size()) { - ui->gas->setMinimum((qint64)Client::txGas(m_data.size(), 1)); + ui->gas->setMinimum((qint64)Client::txGas(m_data, 1)); if (!ui->gas->isEnabled()) ui->gas->setValue(m_backupGas); ui->gas->setEnabled(true); @@ -1673,7 +1640,7 @@ void Main::on_data_textChanged() { if (ui->gas->isEnabled()) m_backupGas = ui->gas->value(); - ui->gas->setValue((qint64)Client::txGas(m_data.size())); + ui->gas->setValue((qint64)Client::txGas(m_data)); ui->gas->setEnabled(false); } } @@ -1836,7 +1803,7 @@ void Main::on_debug_clicked() { Secret s = i.secret(); m_executiveState = ethereum()->postState(); - m_currentExecution = unique_ptr(new Executive(m_executiveState)); + m_currentExecution = unique_ptr(new Executive(m_executiveState, 0)); Transaction t = isCreation() ? Transaction(value(), gasPrice(), ui->gas->value(), m_data, m_executiveState.transactionsFrom(dev::toAddress(s)), s) : Transaction(value(), gasPrice(), ui->gas->value(), fromString(ui->destination->currentText()), m_data, m_executiveState.transactionsFrom(dev::toAddress(s)), s); @@ -2188,7 +2155,7 @@ void Main::on_post_clicked() { shh::Message m; m.setTo(stringToPublic(ui->shhTo->currentText())); - m.setPayload(dataFromText(ui->shhData->toPlainText())); + m.setPayload(parseData(ui->shhData->toPlainText().toStdString())); Public f = stringToPublic(ui->shhFrom->currentText()); Secret from; if (m_server->ids().count(f)) @@ -2224,18 +2191,3 @@ void Main::refreshWhispers() ui->whispers->addItem(item); } } - -// extra bits needed to link on VS -#ifdef _MSC_VER - -// include moc file, ofuscated to hide from automoc -#include\ -"moc_MainWin.cpp" - -#include\ -"moc_MiningView.cpp" - -#include\ -"moc_DownloadView.cpp" - -#endif diff --git a/alethzero/MainWin.h b/alethzero/MainWin.h index 57f9c5ebd..b39b65106 100644 --- a/alethzero/MainWin.h +++ b/alethzero/MainWin.h @@ -33,6 +33,7 @@ #include #include #include +#include #include #include @@ -43,7 +44,6 @@ class Main; namespace dev { namespace eth { class Client; class State; -class MessageFilter; }} class QQuickView; @@ -85,6 +85,7 @@ public slots: void note(QString _entry); void debug(QString _entry); void warn(QString _entry); + QString contents(QString _file); void onKeysChanged(); @@ -154,6 +155,7 @@ private slots: void on_newIdentity_triggered(); void refreshWhisper(); + void refreshBlockChain(); void addNewId(QString _ids); signals: @@ -187,7 +189,7 @@ private: dev::u256 value() const; dev::u256 gasPrice() const; - unsigned installWatch(dev::eth::MessageFilter const& _tf, std::function const& _f); + unsigned installWatch(dev::eth::LogFilter const& _tf, std::function const& _f); unsigned installWatch(dev::h256 _tf, std::function const& _f); void uninstallWatch(unsigned _w); @@ -214,7 +216,6 @@ private: void refreshPending(); void refreshAccounts(); void refreshDestination(); - void refreshBlockChain(); void refreshBlockCount(); void refreshBalances(); @@ -255,7 +256,7 @@ private: QString m_logHistory; bool m_logChanged = true; - QWebThreeConnector* m_qwebConnector; + std::unique_ptr m_qwebConnector; std::unique_ptr m_server; QWebThree* m_qweb = nullptr; }; diff --git a/alethzero/OurWebThreeStubServer.cpp b/alethzero/OurWebThreeStubServer.cpp index a40727e1e..fec0f9e8d 100644 --- a/alethzero/OurWebThreeStubServer.cpp +++ b/alethzero/OurWebThreeStubServer.cpp @@ -24,7 +24,7 @@ using namespace std; using namespace dev; using namespace dev::eth; -OurWebThreeStubServer::OurWebThreeStubServer(jsonrpc::AbstractServerConnector* _conn, dev::WebThreeDirect& _web3, std::vector const& _accounts): +OurWebThreeStubServer::OurWebThreeStubServer(jsonrpc::AbstractServerConnector& _conn, dev::WebThreeDirect& _web3, std::vector const& _accounts): WebThreeStubServer(_conn, _web3, _accounts) {} diff --git a/alethzero/OurWebThreeStubServer.h b/alethzero/OurWebThreeStubServer.h index b3492df5e..ef13964b9 100644 --- a/alethzero/OurWebThreeStubServer.h +++ b/alethzero/OurWebThreeStubServer.h @@ -29,7 +29,7 @@ class OurWebThreeStubServer: public QObject, public WebThreeStubServer Q_OBJECT public: - OurWebThreeStubServer(jsonrpc::AbstractServerConnector* _conn, dev::WebThreeDirect& _web3, std::vector const& _accounts); + OurWebThreeStubServer(jsonrpc::AbstractServerConnector& _conn, dev::WebThreeDirect& _web3, std::vector const& _accounts); virtual std::string shh_newIdentity() override; diff --git a/build.py b/build.py new file mode 100755 index 000000000..099a8721d --- /dev/null +++ b/build.py @@ -0,0 +1,27 @@ +#!/usr/bin/python +# cpp-ethereum build script +# to be used from CI server, or to build locally +# uses python instead of bash script for better cross-platform support + +# TODO Initial version. Needs much more improvements + +import argparse +import os +import subprocess + +def build_dependencies(): + if os.path.exists("extdep"): + os.chdir("extdep") + if not os.path.exists("build"): + os.makedirs("build") + os.chdir("build") + subprocess.check_call(["cmake", ".."]) + subprocess.check_call("make") + +parser = argparse.ArgumentParser() +parser.add_argument("cmd", help="what to build") + +args = parser.parse_args() +if args.cmd == "dep": + build_dependencies() + diff --git a/cmake/EthCompilerSettings.cmake b/cmake/EthCompilerSettings.cmake index 6103970c4..24252cc0b 100644 --- a/cmake/EthCompilerSettings.cmake +++ b/cmake/EthCompilerSettings.cmake @@ -1,59 +1,39 @@ # Set necessary compile and link flags - # C++11 check and activation if ("${CMAKE_CXX_COMPILER_ID}" MATCHES "GNU") + + set(CMAKE_CXX_FLAGS "-std=c++11 -Wall -Wno-unknown-pragmas -Wextra -DSHAREDLIB -fPIC") + set(CMAKE_CXX_FLAGS_DEBUG "-O0 -g -DETH_DEBUG") + set(CMAKE_CXX_FLAGS_MINSIZEREL "-Os -DNDEBUG -DETH_RELEASE") + set(CMAKE_CXX_FLAGS_RELEASE "-O3 -DNDEBUG -DETH_RELEASE") + set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "-O2 -g -DETH_DEBUG") + set(ETH_SHARED 1) + execute_process( COMMAND ${CMAKE_CXX_COMPILER} -dumpversion OUTPUT_VARIABLE GCC_VERSION) if (NOT (GCC_VERSION VERSION_GREATER 4.7 OR GCC_VERSION VERSION_EQUAL 4.7)) message(FATAL_ERROR "${PROJECT_NAME} requires g++ 4.7 or greater.") endif () -elseif ("${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -stdlib=libc++") -else () - message(FATAL_ERROR "Your C++ compiler does not support C++11.") -endif () - - - -# Initialize CXXFLAGS -set(CMAKE_CXX_FLAGS "-std=c++11 -Wall -Wno-unknown-pragmas -Wextra -DSHAREDLIB") -set(CMAKE_CXX_FLAGS_DEBUG "-O0 -g -DETH_DEBUG") -set(CMAKE_CXX_FLAGS_MINSIZEREL "-Os -DNDEBUG -DETH_RELEASE") -set(CMAKE_CXX_FLAGS_RELEASE "-O4 -DNDEBUG -DETH_RELEASE") -set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "-O2 -g -DETH_DEBUG") -# Windows -if ("${TARGET_PLATFORM}" STREQUAL "w64") - set(CMAKE_SYSTEM_NAME Windows) - - set(CMAKE_CXX_LIBRARY_ARCHITECTURE x86_64-w64-mingw32) - set(CMAKE_C_COMPILER x86_64-w64-mingw32-gcc) - set(CMAKE_CXX_COMPILER x86_64-w64-mingw32-g++) - set(CMAKE_RC_COMPILER x86_64-w64-mingw32-windres) - set(CMAKE_AR x86_64-w64-mingw32-ar) - set(CMAKE_RANLIB x86_64-w64-mingw32-ranlib) - - set(CMAKE_EXECUTABLE_SUFFIX .exe) - - set(CMAKE_FIND_ROOT_PATH - /usr/x86_64-w64-mingw32 - ) +elseif ("${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang") - include_directories(/usr/x86_64-w64-mingw32/include/cryptopp) + set(CMAKE_CXX_FLAGS "-std=c++11 -Wall -Wno-unknown-pragmas -Wextra -DSHAREDLIB -fPIC") + set(CMAKE_CXX_FLAGS_DEBUG "-O0 -g -DETH_DEBUG") + set(CMAKE_CXX_FLAGS_MINSIZEREL "-Os -DNDEBUG -DETH_RELEASE") + set(CMAKE_CXX_FLAGS_RELEASE "-O3 -DNDEBUG -DETH_RELEASE") + set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "-O2 -g -DETH_DEBUG") + set(ETH_SHARED 1) - set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) - set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) - set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) +elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC") - set(CMAKE_INSTALL_PREFIX /usr/x86_64-w64-mingw32) - set(ETH_BUILD_PLATFORM "windows") + # specify Exception Handling Model in msvc + set(CMAKE_C_FLAGS "/EHsc") + set(CMAKE_CXX_FLAGS "/EHsc") + # windows likes static set(ETH_STATIC 1) -else () - set(ETH_BUILD_PLATFORM ${CMAKE_SYSTEM_NAME}) - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC") - set(ETH_SHARED 1) -endif() - +else () + message(WARNING "Your compiler is not tested, if you run into any issues, we'd welcome any patches.") +endif () diff --git a/cmake/EthDependencies.cmake b/cmake/EthDependencies.cmake new file mode 100644 index 000000000..24e5bd07d --- /dev/null +++ b/cmake/EthDependencies.cmake @@ -0,0 +1,137 @@ +# all dependencies that are not directly included in the cpp-ethereum distribution are defined here +# for this to work, download the dependency via the cmake script in extdep or install them manually! + +# by defining this variable, cmake will look for dependencies first in our own repository before looking in system paths like /usr/local/ ... +# this must be set to point to the same directory as $ETH_DEPENDENCY_INSTALL_DIR in /extdep directory +string(TOLOWER ${CMAKE_SYSTEM_NAME} _system_name) +set (ETH_DEPENDENCY_INSTALL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/extdep/install/${_system_name}") +set (CMAKE_PREFIX_PATH ${ETH_DEPENDENCY_INSTALL_DIR}) + +# Qt5 requires opengl +# TODO use proper version of windows SDK (32 vs 64) +# TODO make it possible to use older versions of windows SDK (7.0+ should also work) +# TODO it windows SDK is NOT FOUND, throw ERROR +if (WIN32) + set (CMAKE_PREFIX_PATH ${CMAKE_PREFIX_PATH} "C:/Program Files/Windows Kits/8.1/Lib/winv6.3/um/x86") + message(" - Found windows 8.1 SDK") + #set (CMAKE_PREFIX_PATH "C:/Program Files/Windows Kits/8.1/Lib/winv6.3/um/x64") +endif() + +# Dependencies must have a version number, to ensure reproducible build. The version provided here is the one that is in the extdep repository. If you use system libraries, version numbers may be different. + +find_package (CryptoPP 5.6.2 EXACT REQUIRED) +message(" - CryptoPP header: ${CRYPTOPP_INCLUDE_DIRS}") +message(" - CryptoPP lib : ${CRYPTOPP_LIBRARIES}") + +find_package (LevelDB REQUIRED) +message(" - LevelDB header: ${LEVELDB_INCLUDE_DIRS}") +message(" - LevelDB lib: ${LEVELDB_LIBRARIES}") + +# TODO the Jsoncpp package does not yet check for correct version number +find_package (Jsoncpp 0.60 REQUIRED) +message(" - Jsoncpp header: ${JSONCPP_INCLUDE_DIRS}") +message(" - Jsoncpp lib : ${JSONCPP_LIBRARIES}") + +# TODO the JsonRpcCpp package does not yet check for correct version number +# json-rpc-cpp support is currently not mandatory +# TODO make headless client optional +# TODO get rid of -DETH_JSONRPC +if (JSONRPC) + + find_package (JsonRpcCpp 0.3.2) + if (NOT JSON_RPC_CPP_FOUND) + message (FATAL_ERROR "JSONRPC 0.3.2. not found") + endif() + message (" - json-rpc-cpp header: ${JSON_RPC_CPP_INCLUDE_DIRS}") + message (" - json-rpc-cpp lib : ${JSON_RPC_CPP_LIBRARIES}") + add_definitions(-DETH_JSONRPC) + +endif() #JSONRPC + +# TODO readline package does not yet check for correct version number +# TODO make readline package dependent on cmake options +# TODO get rid of -DETH_READLINE +find_package (Readline 6.3.8) +if (READLINE_FOUND) + message (" - readline header: ${READLINE_INCLUDE_DIRS}") + message (" - readline lib : ${READLINE_LIBRARIES}") + add_definitions(-DETH_READLINE) +endif () + +# TODO miniupnpc package does not yet check for correct version number +# TODO make miniupnpc package dependent on cmake options +# TODO get rid of -DMINIUPNPC +find_package (Miniupnpc 1.8.2013) +if (MINIUPNPC_FOUND) + message (" - miniupnpc header: ${MINIUPNPC_INCLUDE_DIRS}") + message (" - miniupnpc lib : ${MINIUPNPC_LIBRARIES}") + add_definitions(-DETH_MINIUPNPC) +endif() + +# TODO gmp package does not yet check for correct version number +# TODO it is also not required in msvc build +find_package (Gmp 6.0.0) +if (GMP_FOUND) + message(" - gmp Header: ${GMP_INCLUDE_DIRS}") + message(" - gmp lib : ${GMP_LIBRARIES}") +endif() + +# curl is only requried for tests +# TODO specify min curl version, on windows we are currenly using 7.29 +find_package (CURL) +message(" - curl header: ${CURL_INCLUDE_DIRS}") +message(" - curl lib : ${CURL_LIBRARIES}") + +# do not compile GUI +if (NOT HEADLESS) + +# we need json rpc to build alethzero + if (NOT JSON_RPC_CPP_FOUND) + message (FATAL_ERROR "JSONRPC is required for GUI client") + endif() + +# find all of the Qt packages +# remember to use 'Qt' instead of 'QT', cause unix is case sensitive +# TODO make headless client optional + find_package (Qt5Core REQUIRED) + find_package (Qt5Gui REQUIRED) + find_package (Qt5Quick REQUIRED) + find_package (Qt5Qml REQUIRED) + find_package (Qt5Network REQUIRED) + find_package (Qt5Widgets REQUIRED) + find_package (Qt5WebKit REQUIRED) + find_package (Qt5WebKitWidgets REQUIRED) + +endif() #HEADLESS + +# use multithreaded boost libraries, with -mt suffix +set(Boost_USE_MULTITHREADED ON) + +if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC") + +# TODO hanlde other msvc versions or it will fail find them + set(Boost_COMPILER -vc120) +# use static boost libraries *.lib + set(Boost_USE_STATIC_LIBS ON) + +elseif (APPLE) + +# use static boost libraries *.a + set(Boost_USE_STATIC_LIBS ON) + +elseif (UNIX) +# use dynamic boost libraries .dll + set(Boost_USE_STATIC_LIBS OFF) + +endif() + +find_package(Boost 1.54.0 REQUIRED COMPONENTS thread date_time system regex chrono filesystem unit_test_framework program_options) + +message(" - boost header: ${Boost_INCLUDE_DIRS}") +message(" - boost lib : ${Boost_LIBRARIES}") + +if (APPLE) + link_directories(/usr/local/lib) + include_directories(/usr/local/include) +endif() + diff --git a/cmake/EthDependenciesDeprecated.cmake b/cmake/EthDependenciesDeprecated.cmake deleted file mode 100644 index 17b937c5c..000000000 --- a/cmake/EthDependenciesDeprecated.cmake +++ /dev/null @@ -1,210 +0,0 @@ -# search for and configure dependencies - -# deprecated. TODO will rewrite to proper CMake packages - - - -if("${TARGET_PLATFORM}" STREQUAL "w64") -# set(MINIUPNPC_LS /usr/x86_64-w64-mingw32/lib/libminiupnpc.a) - set(LEVELDB_LS leveldb) - set(CRYPTOPP_LS cryptopp) - set(CRYPTOPP_ID /usr/x86_64-w64-mingw32/include/cryptopp) -else() - # Look for available Crypto++ version and if it is >= 5.6.2 - find_path(ID cryptlib.h - ../cryptopp/src - ../../cryptopp/src - /usr/include/cryptopp - /usr/include/crypto++ - /usr/local/include/cryptopp - /usr/local/include/crypto++ - /opt/local/include/cryptopp - /opt/local/include/crypto++ - ) - find_library(LS NAMES cryptoppeth cryptopp - ../cryptopp/src/../target/build/release - ../../cryptopp/src/../target/build/release - PATHS - /usr/lib - /usr/local/lib - /opt/local/lib - ) - - if (ID AND LS) - message(STATUS "Found Crypto++: ${ID}, ${LS}") - set(_CRYPTOPP_VERSION_HEADER ${ID}/config.h) - if(EXISTS ${_CRYPTOPP_VERSION_HEADER}) - file(STRINGS ${_CRYPTOPP_VERSION_HEADER} _CRYPTOPP_VERSION REGEX "^#define CRYPTOPP_VERSION[ \t]+[0-9]+$") - string(REGEX REPLACE "^#define CRYPTOPP_VERSION[ \t]+([0-9]+)" "\\1" _CRYPTOPP_VERSION ${_CRYPTOPP_VERSION}) - if(${_CRYPTOPP_VERSION} LESS 562) - message(FATAL_ERROR "Crypto++ version found is smaller than 5.6.2.") - else() - set(CRYPTOPP_ID ${ID} CACHE FILEPATH "") - set(CRYPTOPP_LS ${LS} CACHE FILEPATH "") - message(STATUS "Crypto++ found and version greater or equal to 5.6.2") - endif() - endif() - else() - message(STATUS "Crypto++ Not Found: ${CRYPTOPP_ID}, ${CRYPTOPP_LS}") - endif() - - find_path( LEVELDB_ID leveldb/db.h - /usr/include - /usr/local/include - ) - if ( LEVELDB_ID STREQUAL "LEVELDB_ID-NOTFOUND" ) - message(FATAL_ERROR "Failed to find the LevelDB headers") - else () - message(STATUS "Found LevelDB Headers") - - # Check for accessory dev libraries leveldb and miniupnpc - find_library( LEVELDB_LS NAMES leveldb - PATHS - /usr/lib - /usr/local/lib - /opt/local/lib - /usr/lib/*/ - ) - if ( LEVELDB_LS STREQUAL "LEVELDB_LS-NOTFOUND" ) - message(FATAL_ERROR "Failed to find the LevelDB Library!") - else () - message(STATUS "Found LevelDB Library: ${LEVELDB_LS}") - add_definitions(-DETH_LEVELDB) - endif () - endif () - - find_path( PYTHON_ID pyconfig.h - ${PYTHON_INCLUDE_DIR} - /usr/include/python2.7 - /usr/local/include/python2.7 - ) - if ( PYTHON_ID STREQUAL "PYTHON_ID-NOTFOUND" ) - message(STATUS "Failed to find the Python-2.7 headers") - else () - message(STATUS "Found Python-2.7 Headers: ${PYTHON_ID}") - - # Check for accessory dev libraries leveldb and miniupnpc - find_library( PYTHON_LS NAMES python2.7 - PATHS - /usr/lib - /usr/local/lib - /opt/local/lib - /usr/lib/*/ - ) - if ( PYTHON_LS STREQUAL "PYTHON_LS-NOTFOUND" ) - message(STATUS "Failed to find the Python-2.7 Library!") - set(PYTHON_ID) - set(PYTHON_LS) - else () - message(STATUS "Found Python-2.7 Library: ${PYTHON_LS}") - add_definitions(-DETH_PYTHON) - endif () - endif () - - find_path( MINIUPNPC_ID miniupnpc/miniwget.h - /usr/include - /usr/local/include - ) - if ( MINIUPNPC_ID ) - message(STATUS "Found miniupnpc headers") - - find_library( MINIUPNPC_LS NAMES miniupnpc - PATHS - /usr/lib - /usr/local/lib - /opt/local/lib - /usr/lib/*/ - ) - if ( MINIUPNPC_LS ) - message(STATUS "Found miniupnpc library: ${MINIUPNPC_LS}") - add_definitions(-DETH_MINIUPNPC) - else () - message(STATUS "Failed to find the miniupnpc library!") - endif () - else () - message(STATUS "Failed to find the miniupnpc headers!") - endif () - - find_path( JSONRPC_ID jsonrpc/rpc.h - /usr/include - /usr/local/include - ../libjson-rpc-cpp/src - ) - if ( JSONRPC_ID ) - message(STATUS "Found jsonrpc headers") - find_library( JSONRPC_LS NAMES jsonrpc - PATHS - /usr/lib - /usr/local/lib - /opt/local/lib - /usr/lib/*/ - ../libjson-rpc-cpp/build/out - ) - if ( JSONRPC_LS ) - message(STATUS "Found jsonrpc library: ${JSONRPC_LS}") - add_definitions(-DETH_JSONRPC) - else () - message(STATUS "Failed to find the jsonrpc library!") - endif () - else () - message(STATUS "Failed to find the jsonrpc headers!") - endif () - - find_path( READLINE_ID readline/readline.h - /usr/include - /usr/local/include - ) - if ( READLINE_ID ) - message(STATUS "Found readline headers") - find_library( READLINE_LS NAMES readline - PATHS - /usr/lib - /usr/local/lib - /opt/local/lib - /usr/lib/*/ - ) - if ( READLINE_LS ) - message(STATUS "Found readline library: ${READLINE_LS}") - add_definitions(-DETH_READLINE) - else () - message(STATUS "Failed to find the readline library!") - endif () - else () - message(STATUS "Failed to find the readline headers!") - endif () - - if (LANGUAGES) - find_package(Boost 1.53 REQUIRED COMPONENTS thread date_time) - else() - find_package(Boost 1.53 REQUIRED COMPONENTS thread date_time system regex) - endif() - - set(QTQML 1) -endif() - -if(CRYPTOPP_ID) - include_directories(${CRYPTOPP_ID}) -endif() -if(PYTHON_ID) - include_directories(${PYTHON_ID}) -endif() -if(MINIUPNPC_ID) - include_directories(${MINIUPNPC_ID}) -endif() -if(LEVELDB_ID) - include_directories(${LEVELDB_ID}) -endif() -if(READLINE_ID) - include_directories(${READLINE_ID}) -endif() -if(JSONRPC_ID) - include_directories(${JSONRPC_ID}) -endif() - - - - -if(${CMAKE_SYSTEM_NAME} MATCHES "Darwin") - link_directories(/usr/local/lib) - include_directories(/usr/local/include) -endif() diff --git a/cmake/EthExecutableHelper.cmake b/cmake/EthExecutableHelper.cmake new file mode 100644 index 000000000..adda57692 --- /dev/null +++ b/cmake/EthExecutableHelper.cmake @@ -0,0 +1,118 @@ +# +# this function requires the following variables to be specified: +# ETH_VERSION +# PROJECT_NAME +# PROJECT_VERSION +# PROJECT_COPYRIGHT_YEAR +# PROJECT_VENDOR +# PROJECT_DOMAIN_SECOND +# PROJECT_DOMAIN_FIRST +# SRC_LIST +# HEADERS +# +# params: +# ICON +# + +macro(eth_add_executable EXECUTABLE) + set (extra_macro_args ${ARGN}) + set (options) + set (one_value_args ICON) + set (multi_value_args UI_RESOURCES) + cmake_parse_arguments (ETH_ADD_EXECUTABLE "${options}" "${one_value_args}" "${multi_value_args}" "${extra_macro_args}") + + if (APPLE) + + add_executable(${EXECUTABLE} MACOSX_BUNDLE ${SRC_LIST} ${HEADERS} ${ETH_ADD_EXECUTABLE_UI_RESOURCES}) + set(PROJECT_VERSION "${ETH_VERSION}") + set(MACOSX_BUNDLE_INFO_STRING "${PROJECT_NAME} ${PROJECT_VERSION}") + set(MACOSX_BUNDLE_BUNDLE_VERSION "${PROJECT_NAME} ${PROJECT_VERSION}") + set(MACOSX_BUNDLE_LONG_VERSION_STRING "${PROJECT_NAME} ${PROJECT_VERSION}") + set(MACOSX_BUNDLE_SHORT_VERSION_STRING "${PROJECT_VERSION}") + set(MACOSX_BUNDLE_COPYRIGHT "${PROJECT_COPYRIGHT_YEAR} ${PROJECT_VENDOR}") + set(MACOSX_BUNDLE_GUI_IDENTIFIER "${PROJECT_DOMAIN_SECOND}.${PROJECT_DOMAIN_FIRST}") + set(MACOSX_BUNDLE_BUNDLE_NAME ${EXECUTABLE}) + set(MACOSX_BUNDLE_ICON_FILE ${ETH_ADD_EXECUTABLE_ICON}) + set_target_properties(${EXECUTABLE} PROPERTIES MACOSX_BUNDLE_INFO_PLIST "${CMAKE_SOURCE_DIR}/EthereumMacOSXBundleInfo.plist.in") + set_source_files_properties(${EXECUTABLE} PROPERTIES MACOSX_PACKAGE_LOCATION MacOS) + set_source_files_properties(${MACOSX_BUNDLE_ICON_FILE}.icns PROPERTIES MACOSX_PACKAGE_LOCATION Resources) + + else () + add_executable(${EXECUTABLE} ${ETH_ADD_EXECUTABLE_UI_RESOURCES} ${SRC_LIST} ${HEADERS}) + endif() + +endmacro() + +# +# this function requires the following variables to be specified: +# ETH_DEPENDENCY_INSTALL_DIR +# +# params: +# QMLDIR +# + +macro(eth_install_executable EXECUTABLE) + + set (extra_macro_args ${ARGN}) + set (options) + set (one_value_args QMLDIR) + set (multi_value_args) + cmake_parse_arguments (ETH_INSTALL_EXECUTABLE "${options}" "${one_value_args}" "${multi_value_args}" "${extra_macro_args}") + + if (ETH_INSTALL_EXECUTABLE_QMLDIR) + set(eth_qml_dir "-qmldir=${ETH_INSTALL_EXECUTABLE_QMLDIR}") + endif() + + if (APPLE) + # First have qt5 install plugins and frameworks + add_custom_command(TARGET ${EXECUTABLE} POST_BUILD + COMMAND ${ETH_DEPENDENCY_INSTALL_DIR}/bin/macdeployqt ${eth_qml_dir} ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_CFG_INTDIR}/${EXECUTABLE}.app + WORKING_DIRECTORY ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}) + + # This tool and next will inspect linked libraries in order to determine which dependencies are required + if (${CMAKE_CFG_INTDIR} STREQUAL ".") + set(APP_BUNDLE_PATH "${CMAKE_CURRENT_BINARY_DIR}/${EXECUTABLE}.app") + else () + set(APP_BUNDLE_PATH "${CMAKE_CURRENT_BINARY_DIR}/\$ENV{CONFIGURATION}/${EXECUTABLE}.app") + endif () + + # TODO check, how fixup_bundle works and if it is required + install(CODE " + include(BundleUtilities) + set(BU_CHMOD_BUNDLE_ITEMS 1) + fixup_bundle(\"${APP_BUNDLE_PATH}\" \"${BUNDLELIBS}\" \"../libqethereum ../libethereum ../secp256k1\") + " COMPONENT RUNTIME ) + # Cleanup duplicate libs from macdeployqt + install(CODE " + file(GLOB LINGER_RM \"${APP_BUNDLE_PATH}/Contents/Frameworks/*.dylib\") + if (LINGER_RM) + file(REMOVE \${LINGER_RM}) + endif () + ") + elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC") + + # copy all dlls to executable directory + # TODO improve that by copying only required dlls + file (GLOB DLLS ${ETH_DEPENDENCY_INSTALL_DIR}/bin/*.dll) + + foreach(DLL ${DLLS}) + add_custom_command(TARGET ${EXECUTABLE} POST_BUILD + COMMAND cmake -E copy "${DLL}" "$" + ) + endforeach() + + add_custom_command(TARGET ${EXECUTABLE} POST_BUILD + COMMAND cmake -E copy_directory + "${ETH_DEPENDENCY_INSTALL_DIR}/plugins/platforms" + $/platforms + ) + + install( TARGETS ${EXECUTABLE} RUNTIME DESTINATION bin) + + else() + install( TARGETS ${EXECUTABLE} RUNTIME DESTINATION bin) + endif () + +endmacro() + + diff --git a/cmake/FindCryptoPP.cmake b/cmake/FindCryptoPP.cmake new file mode 100644 index 000000000..a9e7183c0 --- /dev/null +++ b/cmake/FindCryptoPP.cmake @@ -0,0 +1,108 @@ +# Module for locating the Crypto++ encryption library. +# +# Customizable variables: +# CRYPTOPP_ROOT_DIR +# This variable points to the CryptoPP root directory. On Windows the +# library location typically will have to be provided explicitly using the +# -D command-line option. The directory should include the include/cryptopp, +# lib and/or bin sub-directories. +# +# Read-only variables: +# CRYPTOPP_FOUND +# Indicates whether the library has been found. +# +# CRYPTOPP_INCLUDE_DIRS +# Points to the CryptoPP include directory. +# +# CRYPTOPP_LIBRARIES +# Points to the CryptoPP libraries that should be passed to +# target_link_libararies. +# +# +# Copyright (c) 2012 Sergiu Dotenco +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +INCLUDE (FindPackageHandleStandardArgs) + +FIND_PATH (CRYPTOPP_ROOT_DIR + NAMES cryptopp/cryptlib.h include/cryptopp/cryptlib.h + PATHS ENV CRYPTOPPROOT + DOC "CryptoPP root directory") + +# Re-use the previous path: +FIND_PATH (CRYPTOPP_INCLUDE_DIR + NAMES cryptopp/cryptlib.h + HINTS ${CRYPTOPP_ROOT_DIR} + PATH_SUFFIXES include + DOC "CryptoPP include directory") + +FIND_LIBRARY (CRYPTOPP_LIBRARY_DEBUG + NAMES cryptlibd cryptoppd + HINTS ${CRYPTOPP_ROOT_DIR} + PATH_SUFFIXES lib + DOC "CryptoPP debug library") + +FIND_LIBRARY (CRYPTOPP_LIBRARY_RELEASE + NAMES cryptlib cryptopp + HINTS ${CRYPTOPP_ROOT_DIR} + PATH_SUFFIXES lib + DOC "CryptoPP release library") + +IF (CRYPTOPP_LIBRARY_DEBUG AND CRYPTOPP_LIBRARY_RELEASE) + SET (CRYPTOPP_LIBRARY + optimized ${CRYPTOPP_LIBRARY_RELEASE} + debug ${CRYPTOPP_LIBRARY_DEBUG} CACHE DOC "CryptoPP library") +ELSEIF (CRYPTOPP_LIBRARY_RELEASE) + SET (CRYPTOPP_LIBRARY ${CRYPTOPP_LIBRARY_RELEASE} CACHE DOC + "CryptoPP library") +ENDIF (CRYPTOPP_LIBRARY_DEBUG AND CRYPTOPP_LIBRARY_RELEASE) + +IF (CRYPTOPP_INCLUDE_DIR) + SET (_CRYPTOPP_VERSION_HEADER ${CRYPTOPP_INCLUDE_DIR}/cryptopp/config.h) + + IF (EXISTS ${_CRYPTOPP_VERSION_HEADER}) + FILE (STRINGS ${_CRYPTOPP_VERSION_HEADER} _CRYPTOPP_VERSION_TMP REGEX + "^#define CRYPTOPP_VERSION[ \t]+[0-9]+$") + + STRING (REGEX REPLACE + "^#define CRYPTOPP_VERSION[ \t]+([0-9]+)" "\\1" _CRYPTOPP_VERSION_TMP + ${_CRYPTOPP_VERSION_TMP}) + + STRING (REGEX REPLACE "([0-9]+)[0-9][0-9]" "\\1" CRYPTOPP_VERSION_MAJOR + ${_CRYPTOPP_VERSION_TMP}) + STRING (REGEX REPLACE "[0-9]([0-9])[0-9]" "\\1" CRYPTOPP_VERSION_MINOR + ${_CRYPTOPP_VERSION_TMP}) + STRING (REGEX REPLACE "[0-9][0-9]([0-9])" "\\1" CRYPTOPP_VERSION_PATCH + ${_CRYPTOPP_VERSION_TMP}) + + SET (CRYPTOPP_VERSION_COUNT 3) + SET (CRYPTOPP_VERSION + ${CRYPTOPP_VERSION_MAJOR}.${CRYPTOPP_VERSION_MINOR}.${CRYPTOPP_VERSION_PATCH}) + ENDIF (EXISTS ${_CRYPTOPP_VERSION_HEADER}) +ENDIF (CRYPTOPP_INCLUDE_DIR) + +SET (CRYPTOPP_INCLUDE_DIRS ${CRYPTOPP_INCLUDE_DIR}) +SET (CRYPTOPP_LIBRARIES ${CRYPTOPP_LIBRARY}) + +MARK_AS_ADVANCED (CRYPTOPP_INCLUDE_DIR CRYPTOPP_LIBRARY CRYPTOPP_LIBRARY_DEBUG + CRYPTOPP_LIBRARY_RELEASE) + +FIND_PACKAGE_HANDLE_STANDARD_ARGS (CryptoPP REQUIRED_VARS + CRYPTOPP_INCLUDE_DIR CRYPTOPP_LIBRARY VERSION_VAR CRYPTOPP_VERSION) diff --git a/cmake/FindGmp.cmake b/cmake/FindGmp.cmake new file mode 100644 index 000000000..4dc8f48c4 --- /dev/null +++ b/cmake/FindGmp.cmake @@ -0,0 +1,34 @@ +# Find gmp +# +# Find the gmp includes and library +# +# if you nee to add a custom library search path, do it via via CMAKE_FIND_ROOT_PATH +# +# This module defines +# GMP_INCLUDE_DIRS, where to find header, etc. +# GMP_LIBRARIES, the libraries needed to use gmp. +# GMP_FOUND, If false, do not try to use gmp. + +# only look in default directories +find_path( + GMP_INCLUDE_DIR + NAMES gmp.h + DOC "gmp include dir" + ) + +find_library( + GMP_LIBRARY + NAMES gmp + DOC "gmp library" + ) + +set(GMP_INCLUDE_DIRS ${GMP_INCLUDE_DIR}) +set(GMP_LIBRARIES ${GMP_LIBRARY}) + +# handle the QUIETLY and REQUIRED arguments and set GMP_FOUND to TRUE +# if all listed variables are TRUE, hide their existence from configuration view +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(gmp DEFAULT_MSG + GMP_INCLUDE_DIR GMP_LIBRARY) +mark_as_advanced (GMP_INCLUDE_DIR GMP_LIBRARY) + diff --git a/cmake/FindJsonRpcCpp.cmake b/cmake/FindJsonRpcCpp.cmake new file mode 100644 index 000000000..eecf518f8 --- /dev/null +++ b/cmake/FindJsonRpcCpp.cmake @@ -0,0 +1,52 @@ +# Find json-rcp-cpp +# +# Find the json-rpc-cpp includes and library +# +# if you nee to add a custom library search path, do it via via CMAKE_FIND_ROOT_PATH +# +# This module defines +# JSON_RCP_CPP_INCLUDE_DIRS, where to find header, etc. +# JSON_RCP_CPP_LIBRARIES, the libraries needed to use json-rpc-cpp. +# JSON_RPC_CPP_SERVER_LIBRARIES, the libraries needed to use json-rpc-cpp-server +# JSON_RPC_CPP_CLIENT_LIBRARIES, the libraries needed to use json-rpc-cpp-client +# JSON_RCP_CPP_FOUND, If false, do not try to use json-rpc-cpp. + +# only look in default directories +find_path( + JSON_RPC_CPP_INCLUDE_DIR + NAMES jsonrpccpp/server.h + PATH_SUFFIXES jsonrpc + DOC "json-rpc-cpp include dir" +) + +find_library( + JSON_RPC_CPP_COMMON_LIBRARY + NAMES jsonrpccpp-common + DOC "json-rpc-cpp common library" +) + +find_library( + JSON_RPC_CPP_SERVER_LIBRARY + NAMES jsonrpccpp-server + DOC "json-rpc-cpp server library" +) + +find_library( + JSON_RPC_CPP_CLIENT_LIBRARY + NAMES jsonrpccpp-client + DOC "json-rpc-cpp client library" +) + +# these are the variables to be uses by the calling script +set (JSON_RPC_CPP_INCLUDE_DIRS ${JSON_RPC_CPP_INCLUDE_DIR}) +set (JSON_RPC_CPP_LIBRARIES ${JSON_RPC_CPP_COMMON_LIBRARY} ${JSON_RPC_CPP_SERVER_LIBRARY} ${JSON_RPC_CPP_CLIENT_LIBRARY}) +set (JSON_RPC_CPP_SERVER_LIBRARIES ${JSON_RPC_CPP_COMMON_LIBRARY} ${JSON_RPC_CPP_SERVER_LIBRARY}) +set (JSON_RPC_CPP_CLIENT_LIBRARIES ${JSON_RPC_CPP_COMMON_LIBRARY} ${JSON_RPC_CPP_CLIENT_LIBRARY}) + +# handle the QUIETLY and REQUIRED arguments and set JSON_RPC_CPP_FOUND to TRUE +# if all listed variables are TRUE, hide their existence from configuration view +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(json_rpc_cpp DEFAULT_MSG + JSON_RPC_CPP_COMMON_LIBRARY JSON_RPC_CPP_SERVER_LIBRARY JSON_RPC_CPP_CLIENT_LIBRARY JSON_RPC_CPP_INCLUDE_DIR) +mark_as_advanced (JSON_RPC_CPP_COMMON_LIBRARY JSON_RPC_CPP_SERVER_LIBRARY JSON_RPC_CPP_CLIENT_LIBRARY JSON_RPC_CPP_INCLUDE_DIR) + diff --git a/cmake/FindJsoncpp.cmake b/cmake/FindJsoncpp.cmake new file mode 100644 index 000000000..fe72a9042 --- /dev/null +++ b/cmake/FindJsoncpp.cmake @@ -0,0 +1,103 @@ +# - try to find JSONCPP library +# +# Cache Variables: (probably not for direct use in your scripts) +# JSONCPP_INCLUDE_DIR +# JSONCPP_LIBRARY +# +# Non-cache variables you might use in your CMakeLists.txt: +# JSONCPP_FOUND +# JSONCPP_INCLUDE_DIRS +# JSONCPP_LIBRARIES +# +# Requires these CMake modules: +# FindPackageHandleStandardArgs (known included with CMake >=2.6.2) +# +# Author: +# 2011 Philippe Crassous (ENSAM ParisTech / Institut Image) p.crassous _at_ free.fr +# +# Adapted from the Virtual Reality Peripheral Network library. +# https://github.com/rpavlik/vrpn/blob/master/README.Legal +# + +set(JSONCPP_ROOT_DIR + "${JSONCPP_ROOT_DIR}" + CACHE + PATH + "Directory to search for JSONCPP") +set(_jsoncppnames) +set(_pathsuffixes + suncc + vacpp + mingw + msvc6 + msvc7 + msvc71 + msvc80 + msvc90 + linux-gcc) +if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU" OR "${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang") + execute_process(COMMAND + ${CMAKE_CXX_COMPILER} + -dumpversion + OUTPUT_VARIABLE + _gnucxx_ver + OUTPUT_STRIP_TRAILING_WHITESPACE) + list(APPEND + _jsoncppnames + json_linux-gcc-${_gnucxx_ver}_libmt + json_linux-gcc_libmt) + list(APPEND _pathsuffixes linux-gcc-${_gnucxx_ver}) +elseif(MSVC) + if(MSVC_VERSION EQUAL 1200) + list(APPEND _jsoncppnames json_vc6_libmt) + elseif(MSVC_VERSION EQUAL 1300) + list(APPEND _jsoncppnames json_vc7_libmt) + elseif(MSVC_VERSION EQUAL 1310) + list(APPEND _jsoncppnames json_vc71_libmt) + elseif(MSVC_VERSION EQUAL 1400) + list(APPEND _jsoncppnames json_vc8_libmt) + elseif(MSVC_VERSION EQUAL 1500) + list(APPEND _jsoncppnames json_vc9_libmt) + elseif(MSVC_VERSION EQUAL 1600) + list(APPEND _jsoncppnames json_vc10_libmt) + endif() +else() + list(APPEND _jsoncppnames + json_suncc_libmt + json_vacpp_libmt) +endif() + +list(APPEND _jsoncppnames + json_mingw_libmt + jsoncpp) + +find_library(JSONCPP_LIBRARY + NAMES + ${_jsoncppnames} + PATHS + "${JSONCPP_ROOT_DIR}/libs" + PATH_SUFFIXES + ${_pathsuffixes}) + +find_path(JSONCPP_INCLUDE_DIR + NAMES + json/json.h + PATHS + "${JSONCPP_ROOT_DIR}" + PATH_SUFFIXES jsoncpp + include) + +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(JSONCPP + DEFAULT_MSG + JSONCPP_LIBRARY + JSONCPP_INCLUDE_DIR) + +if(JSONCPP_FOUND) + set(JSONCPP_LIBRARIES "${JSONCPP_LIBRARY}") + set(JSONCPP_INCLUDE_DIRS "${JSONCPP_INCLUDE_DIR}") + mark_as_advanced(JSONCPP_ROOT_DIR) +endif() + +mark_as_advanced(JSONCPP_INCLUDE_DIR JSONCPP_LIBRARY) + diff --git a/cmake/FindLevelDB.cmake b/cmake/FindLevelDB.cmake new file mode 100644 index 000000000..6bd373a9f --- /dev/null +++ b/cmake/FindLevelDB.cmake @@ -0,0 +1,34 @@ +# Find leveldb +# +# Find the leveldb includes and library +# +# if you nee to add a custom library search path, do it via via CMAKE_FIND_ROOT_PATH +# +# This module defines +# LEVELDB_INCLUDE_DIRS, where to find header, etc. +# LEVELDB_LIBRARIES, the libraries needed to use leveldb. +# LEVELDB_FOUND, If false, do not try to use leveldb. + +# only look in default directories +find_path( + LEVELDB_INCLUDE_DIR + NAMES leveldb/db.h + DOC "leveldb include dir" +) + +find_library( + LEVELDB_LIBRARY + NAMES leveldb + DOC "leveldb library" +) + +set(LEVELDB_INCLUDE_DIRS ${LEVELDB_INCLUDE_DIR}) +set(LEVELDB_LIBRARIES ${LEVELDB_LIBRARY}) + +# handle the QUIETLY and REQUIRED arguments and set LEVELDB_FOUND to TRUE +# if all listed variables are TRUE, hide their existence from configuration view +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(leveldb DEFAULT_MSG + LEVELDB_INCLUDE_DIR LEVELDB_LIBRARY) +mark_as_advanced (LEVELDB_INCLUDE_DIR LEVELDB_LIBRARY) + diff --git a/cmake/FindMiniupnpc.cmake b/cmake/FindMiniupnpc.cmake new file mode 100644 index 000000000..4ecbb0c4a --- /dev/null +++ b/cmake/FindMiniupnpc.cmake @@ -0,0 +1,34 @@ +# Find miniupnpc +# +# Find the miniupnpc includes and library +# +# if you nee to add a custom library search path, do it via via CMAKE_FIND_ROOT_PATH +# +# This module defines +# MINIUPNPC_INCLUDE_DIRS, where to find header, etc. +# MINIUPNPC_LIBRARIES, the libraries needed to use gmp. +# MINIUPNPC_FOUND, If false, do not try to use gmp. + +# only look in default directories +find_path( + MINIUPNPC_INCLUDE_DIR + NAMES miniupnpc/miniupnpc.h + DOC "miniupnpc include dir" + ) + +find_library( + MINIUPNPC_LIBRARY + NAMES miniupnpc + DOC "miniupnpc library" + ) + +set(MINIUPNPC_INCLUDE_DIRS ${MINIUPNPC_INCLUDE_DIR}) +set(MINIUPNPC_LIBRARIES ${MINIUPNPC_LIBRARY}) + +# handle the QUIETLY and REQUIRED arguments and set MINIUPNPC_FOUND to TRUE +# if all listed variables are TRUE, hide their existence from configuration view +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(miniupnpc DEFAULT_MSG + MINIUPNPC_INCLUDE_DIR MINIUPNPC_LIBRARY) +mark_as_advanced (MINIUPNPC_INCLUDE_DIR MINIUPNPC_LIBRARY) + diff --git a/cmake/FindReadline.cmake b/cmake/FindReadline.cmake new file mode 100644 index 000000000..1f47db4a7 --- /dev/null +++ b/cmake/FindReadline.cmake @@ -0,0 +1,34 @@ +# Find readline +# +# Find the readline includes and library +# +# if you nee to add a custom library search path, do it via via CMAKE_FIND_ROOT_PATH +# +# This module defines +# READLINE_INCLUDE_DIRS, where to find header, etc. +# READLINE_LIBRARIES, the libraries needed to use readline. +# READLINE_FOUND, If false, do not try to use readline. + +# only look in default directories +find_path( + READLINE_INCLUDE_DIR + NAMES readline/readline.h + DOC "readling include dir" + ) + +find_library( + READLINE_LIBRARY + NAMES readline + DOC "readline library" + ) + +set(READLINE_INCLUDE_DIRS ${READLINE_INCLUDE_DIR}) +set(READLINE_LIBRARIES ${READLINE_LIBRARY}) + +# handle the QUIETLY and REQUIRED arguments and set READLINE_FOUND to TRUE +# if all listed variables are TRUE, hide their existence from configuration view +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(readline DEFAULT_MSG + READLINE_INCLUDE_DIR READLINE_LIBRARY) +mark_as_advanced (READLINE_INCLUDE_DIR READLINE_LIBRARY) + diff --git a/eth/CMakeLists.txt b/eth/CMakeLists.txt index 7c997b256..739c2991c 100644 --- a/eth/CMakeLists.txt +++ b/eth/CMakeLists.txt @@ -1,48 +1,32 @@ cmake_policy(SET CMP0015 NEW) +set(CMAKE_AUTOMOC OFF) aux_source_directory(. SRC_LIST) +include_directories(${JSON_RPC_CPP_INCLUDE_DIRS}) include_directories(..) set(EXECUTABLE eth) file(GLOB HEADERS "*.h") + add_executable(${EXECUTABLE} ${SRC_LIST} ${HEADERS}) -target_link_libraries(${EXECUTABLE} webthree) -target_link_libraries(${EXECUTABLE} secp256k1) -target_link_libraries(${EXECUTABLE} gmp) -if(MINIUPNPC_LS) - target_link_libraries(${EXECUTABLE} ${MINIUPNPC_LS}) -endif() -target_link_libraries(${EXECUTABLE} ${LEVELDB_LS}) -target_link_libraries(${EXECUTABLE} ${CRYPTOPP_LS}) -if(JSONRPC_LS) -target_link_libraries(${EXECUTABLE} web3jsonrpc) +add_dependencies(${EXECUTABLE} BuildInfo.h) + +target_link_libraries(${EXECUTABLE} ${Boost_REGEX_LIBRARY_RELEASE}) +target_link_libraries(${EXECUTABLE} ${Boost_DATE_TIME_LIBRARY_RELEASE}) + +if (READLINE_FOUND) + target_link_libraries(${EXECUTABLE} ${READLINE_LIBRARIES}) endif() -if(READLINE_LS) -target_link_libraries(${EXECUTABLE} ${READLINE_LS}) + +if (JSONRPC) + target_link_libraries(${EXECUTABLE} web3jsonrpc) endif() -if ("${TARGET_PLATFORM}" STREQUAL "w64") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -static-libgcc -static-libstdc++") - target_link_libraries(${EXECUTABLE} boost_system-mt-s) - target_link_libraries(${EXECUTABLE} boost_filesystem-mt-s) - target_link_libraries(${EXECUTABLE} boost_thread_win32-mt-s) - target_link_libraries(${EXECUTABLE} gcc) - target_link_libraries(${EXECUTABLE} gdi32) - target_link_libraries(${EXECUTABLE} ws2_32) - target_link_libraries(${EXECUTABLE} mswsock) - target_link_libraries(${EXECUTABLE} shlwapi) - target_link_libraries(${EXECUTABLE} iphlpapi) - set(CMAKE_SHARED_LIBRARY_LINK_CXX_FLAGS) -elseif (UNIX) -else () - target_link_libraries(${EXECUTABLE} boost_system) - target_link_libraries(${EXECUTABLE} boost_filesystem) - find_package(Threads REQUIRED) - target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT}) -endif () +target_link_libraries(${EXECUTABLE} webthree) +target_link_libraries(${EXECUTABLE} secp256k1) install( TARGETS ${EXECUTABLE} DESTINATION bin ) diff --git a/eth/main.cpp b/eth/main.cpp index 408654018..49eac8876 100644 --- a/eth/main.cpp +++ b/eth/main.cpp @@ -27,10 +27,6 @@ #include #include #include -#if ETH_JSONRPC -#include -#include -#endif #include #include #include @@ -42,6 +38,7 @@ #endif #if ETH_JSONRPC #include +#include #endif #include "BuildInfo.h" using namespace std; @@ -337,10 +334,12 @@ int main(int argc, char** argv) web3.connect(remoteHost, remotePort); #if ETH_JSONRPC - auto_ptr jsonrpcServer; + shared_ptr jsonrpcServer; + unique_ptr jsonrpcConnector; if (jsonrpc > -1) { - jsonrpcServer = auto_ptr(new WebThreeStubServer(new jsonrpc::CorsHttpServer(jsonrpc), web3, {us})); + jsonrpcConnector = unique_ptr(new jsonrpc::HttpServer(jsonrpc)); + jsonrpcServer = shared_ptr(new WebThreeStubServer(*jsonrpcConnector.get(), web3, vector({us}))); jsonrpcServer->setIdentities({us}); jsonrpcServer->StartListening(); } @@ -428,7 +427,8 @@ int main(int argc, char** argv) { if (jsonrpc < 0) jsonrpc = 8080; - jsonrpcServer = auto_ptr(new WebThreeStubServer(new jsonrpc::CorsHttpServer(jsonrpc), web3, {us})); + jsonrpcConnector = unique_ptr(new jsonrpc::HttpServer(jsonrpc)); + jsonrpcServer = shared_ptr(new WebThreeStubServer(*jsonrpcConnector.get(), web3, vector({us}))); jsonrpcServer->setIdentities({us}); jsonrpcServer->StartListening(); } @@ -492,14 +492,12 @@ int main(int argc, char** argv) cnote << ssbd.str(); int ssize = sechex.length(); int size = hexAddr.length(); - u256 minGas = (u256)Client::txGas(data.size(), 0); + u256 minGas = (u256)Client::txGas(data, 0); if (size < 40) { if (size > 0) cwarn << "Invalid address length:" << size; } - else if (gasPrice < info.minGasPrice) - cwarn << "Minimum gas price is" << info.minGasPrice; else if (gas < minGas) cwarn << "Minimum gas amount is" << minGas; else if (ssize < 40) @@ -559,9 +557,9 @@ int main(int argc, char** argv) auto h = bc.currentHash(); auto blockData = bc.block(h); BlockInfo info(blockData); - u256 minGas = (u256)Client::txGas(0, 0); + u256 minGas = (u256)Client::txGas(bytes(), 0); Address dest = h160(fromHex(hexAddr)); - c->transact(us.secret(), amount, dest, bytes(), minGas, info.minGasPrice); + c->transact(us.secret(), amount, dest, bytes(), minGas); } } else @@ -598,11 +596,9 @@ int main(int argc, char** argv) cnote << "Init:"; cnote << ssc.str(); } - u256 minGas = (u256)Client::txGas(init.size(), 0); + u256 minGas = (u256)Client::txGas(init, 0); if (endowment < 0) cwarn << "Invalid endowment"; - else if (gasPrice < info.minGasPrice) - cwarn << "Minimum gas price is" << info.minGasPrice; else if (gas < minGas) cwarn << "Minimum gas amount is" << minGas; else @@ -624,7 +620,7 @@ int main(int argc, char** argv) dev::eth::State state =c->state(index + 1,c->blockChain().numberHash(block)); if (index < state.pending().size()) { - Executive e(state); + Executive e(state, 0); Transaction t = state.pending()[index]; state = state.fromPending(index); bytes r = t.rlp(); @@ -634,10 +630,10 @@ int main(int argc, char** argv) OnOpFunc oof; if (format == "pretty") - oof = [&](uint64_t steps, Instruction instr, bigint newMemSize, bigint gasCost, void* vvm, void const* vextVM) + oof = [&](uint64_t steps, Instruction instr, bigint newMemSize, bigint gasCost, dev::eth::VM* vvm, dev::eth::ExtVMFace const* vextVM) { - dev::eth::VM* vm = (VM*)vvm; - dev::eth::ExtVM const* ext = (ExtVM const*)vextVM; + dev::eth::VM* vm = vvm; + dev::eth::ExtVM const* ext = static_cast(vextVM); f << endl << " STACK" << endl; for (auto i: vm->stack()) f << (h256)i << endl; @@ -648,17 +644,17 @@ int main(int argc, char** argv) f << dec << ext->depth << " | " << ext->myAddress << " | #" << steps << " | " << hex << setw(4) << setfill('0') << vm->curPC() << " : " << dev::eth::instructionInfo(instr).name << " | " << dec << vm->gas() << " | -" << dec << gasCost << " | " << newMemSize << "x32"; }; else if (format == "standard") - oof = [&](uint64_t, Instruction instr, bigint, bigint, void* vvm, void const* vextVM) + oof = [&](uint64_t, Instruction instr, bigint, bigint, dev::eth::VM* vvm, dev::eth::ExtVMFace const* vextVM) { - dev::eth::VM* vm = (VM*)vvm; - dev::eth::ExtVM const* ext = (ExtVM const*)vextVM; + dev::eth::VM* vm = vvm; + dev::eth::ExtVM const* ext = static_cast(vextVM); f << ext->myAddress << " " << hex << toHex(dev::toCompactBigEndian(vm->curPC(), 1)) << " " << hex << toHex(dev::toCompactBigEndian((int)(byte)instr, 1)) << " " << hex << toHex(dev::toCompactBigEndian((uint64_t)vm->gas(), 1)) << endl; }; else if (format == "standard+") - oof = [&](uint64_t, Instruction instr, bigint, bigint, void* vvm, void const* vextVM) + oof = [&](uint64_t, Instruction instr, bigint, bigint, dev::eth::VM* vvm, dev::eth::ExtVMFace const* vextVM) { dev::eth::VM* vm = (VM*)vvm; - dev::eth::ExtVM const* ext = (ExtVM const*)vextVM; + dev::eth::ExtVM const* ext = static_cast(vextVM); if (instr == Instruction::STOP || instr == Instruction::RETURN || instr == Instruction::SUICIDE) for (auto const& i: ext->state().storage(ext->myAddress)) f << toHex(dev::toCompactBigEndian(i.first, 1)) << " " << toHex(dev::toCompactBigEndian(i.second, 1)) << endl; diff --git a/exp/CMakeLists.txt b/exp/CMakeLists.txt index da6775798..d0aadc8ae 100644 --- a/exp/CMakeLists.txt +++ b/exp/CMakeLists.txt @@ -1,7 +1,9 @@ cmake_policy(SET CMP0015 NEW) +set(CMAKE_AUTOMOC OFF) aux_source_directory(. SRC_LIST) +include_directories(${LEVELDB_INCLUDE_DIRS}) include_directories(..) set(EXECUTABLE exp) @@ -10,32 +12,6 @@ add_executable(${EXECUTABLE} ${SRC_LIST}) target_link_libraries(${EXECUTABLE} ethereum) target_link_libraries(${EXECUTABLE} p2p) -target_link_libraries(${EXECUTABLE} gmp) -target_link_libraries(${EXECUTABLE} ${CRYPTOPP_LS}) -if(MINIUPNPC_LS) -target_link_libraries(${EXECUTABLE} ${MINIUPNPC_LS}) -endif() -target_link_libraries(${EXECUTABLE} ${LEVELDB_LS}) -if ("${TARGET_PLATFORM}" STREQUAL "w64") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -static-libgcc -static-libstdc++") - target_link_libraries(${EXECUTABLE} gcc) - target_link_libraries(${EXECUTABLE} gdi32) - target_link_libraries(${EXECUTABLE} ws2_32) - target_link_libraries(${EXECUTABLE} mswsock) - target_link_libraries(${EXECUTABLE} shlwapi) - target_link_libraries(${EXECUTABLE} iphlpapi) - target_link_libraries(${EXECUTABLE} boost_system-mt-s) - target_link_libraries(${EXECUTABLE} boost_filesystem-mt-s) - target_link_libraries(${EXECUTABLE} boost_thread_win32-mt-s) - set(CMAKE_SHARED_LIBRARY_LINK_CXX_FLAGS) -elseif (UNIX) -else () - target_link_libraries(${EXECUTABLE} boost_system) - target_link_libraries(${EXECUTABLE} boost_filesystem) - find_package(Threads REQUIRED) - target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT}) -endif () - -install( TARGETS ${EXECUTABLE} DESTINATION bin ) +install( TARGETS ${EXECUTABLE} DESTINATION bin) diff --git a/extdep/CMakeLists.txt b/extdep/CMakeLists.txt new file mode 100644 index 000000000..19cd00f7b --- /dev/null +++ b/extdep/CMakeLists.txt @@ -0,0 +1,55 @@ +cmake_minimum_required(VERSION 2.8.12) + +include(ExternalProject) +include(CMakeParseArguments) +include(eth_download.cmake) + +# all dependencies will be installed into this directory, separated by platform +string(TOLOWER ${CMAKE_SYSTEM_NAME} _system_name) +set(ETH_DEPENDENCY_INSTALL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/install/${_system_name}") +set(ETH_DEPENDENCY_SERVER "http://poc-7.ethdev.com/precompiled/${_system_name}") +file(MAKE_DIRECTORY ${ETH_DEPENDENCY_INSTALL_DIR}/lib) +file(MAKE_DIRECTORY ${ETH_DEPENDENCY_INSTALL_DIR}/include) +file(MAKE_DIRECTORY ${ETH_DEPENDENCY_INSTALL_DIR}/bin) + +if (ETH_COMPILE) + # json-rpc-cpp and its dependencies + include(compile/jsoncpp.cmake) + include(compile/argtable2.cmake) + include(compile/curl.cmake) + include(compile/json-rpc-cpp.cmake) + + # qt and its dependencies + include(compile/icu.cmake) + include(compile/jom.cmake) + include(compile/qt.cmake) + + # leveldb and its dependencies + include(compile/snappy.cmake) + include(compile/leveldb.cmake) + + # cryptopp + include(compile/cryptopp.cmake) + + # boost + include(compile/boost.cmake) +else() + eth_download(jsoncpp) + eth_download(json-rpc-cpp OSX_SCRIPT ${CMAKE_CURRENT_SOURCE_DIR}/scripts/json-rpc-cpp_osx.sh) + + if (APPLE) + eth_download(snappy OSX_SCRIPT ${CMAKE_CURRENT_SOURCE_DIR}/scripts/snappy_osx.sh) + endif() + + eth_download(leveldb OSX_SCRIPT ${CMAKE_CURRENT_SOURCE_DIR}/scripts/leveldb_osx.sh) + eth_download(qt) + eth_download(cryptopp) + eth_download(boost) + eth_download(curl) + +endif() + +# will be re-eanbled later +# include(miniupnpc.cmake) +# if install phase of extep fails, even if libs are already created, the ethereum install will fail + diff --git a/extdep/Readme.md b/extdep/Readme.md new file mode 100644 index 000000000..1706f1fb9 --- /dev/null +++ b/extdep/Readme.md @@ -0,0 +1,16 @@ +# cpp-ethereum external dependencies + +**This is Work-in-Progress!** + +This directory hosts the external libraries that are needed to build cpp-ethereum. + +To automatically download, build, and link libraries, do +``` +cd extdep; mkdir build; cd build; cmake ..; make +``` +this will take some time. + + +To check which libraries are already included, check `CMakeLists.txt`. Other libraries still need to be fetched via the system's package manager. + +Libraries will be installed in `cpp-ethereum/extdep/install/` diff --git a/extdep/cmake/FindCURL.cmake b/extdep/cmake/FindCURL.cmake new file mode 100644 index 000000000..22d51591c --- /dev/null +++ b/extdep/cmake/FindCURL.cmake @@ -0,0 +1,9 @@ +# hacky way to resolve nested dependencies - needed for json-rpc-cpp +find_library(CURL_LIBRARY NAMES curl + PATHS + ${ETH_DEPENDENCY_INSTALL_DIR}/lib + ) + +set(CURL_LIBRARIES ${CURL_LIBRARY}) +set(CURL_INCLUDE_DIRS ${ETH_DEPENDENCY_INSTALL_DIR}/include) + diff --git a/extdep/compile/argtable2.cmake b/extdep/compile/argtable2.cmake new file mode 100644 index 000000000..778d6a299 --- /dev/null +++ b/extdep/compile/argtable2.cmake @@ -0,0 +1,13 @@ +if (APPLE) + +elseif (WIN32) +ExternalProject_Add(argtable2 + GIT_REPOSITORY https://github.com/debris/argtable.git + GIT_TAG master + BINARY_DIR argtable2-prefix/src/argtable2 + CONFIGURE_COMMAND cmake . + BUILD_COMMAND devenv argtable2.sln /build release + INSTALL_COMMAND cmd /c cp src/Release/argtable2.lib ${ETH_DEPENDENCY_INSTALL_DIR}/lib && cp src/argtable2.h ${ETH_DEPENDENCY_INSTALL_DIR}/include +) +else() +endif() diff --git a/extdep/compile/boost.cmake b/extdep/compile/boost.cmake new file mode 100644 index 000000000..7449cf47b --- /dev/null +++ b/extdep/compile/boost.cmake @@ -0,0 +1,19 @@ +if (APPLE) + +elseif (WIN32) +set(boost_address_model) +# on windows 64: +# set(boost_address_model address-model=64) + +set(boost_targets --with-filesystem --with-system --with-thread --with-date_time --with-regex --with-test --with-chrono --with-program_options) +ExternalProject_Add(boost + URL http://downloads.sourceforge.net/project/boost/boost/1.55.0/boost_1_55_0.tar.gz + BINARY_DIR boost-prefix/src/boost + CONFIGURE_COMMAND ./bootstrap.bat + BUILD_COMMAND ./b2.exe -j4 --build-type=complete link=static runtime-link=shared variant=debug,release threading=multi ${boost_addressModel} ${boost_targets} install --prefix=${ETH_DEPENDENCY_INSTALL_DIR} + INSTALL_COMMAND cmake -E rename ${ETH_DEPENDENCY_INSTALL_DIR}/include/boost-1_55/boost ${ETH_DEPENDENCY_INSTALL_DIR}/include/boost + ) +else() + +endif() + diff --git a/extdep/compile/cryptopp.cmake b/extdep/compile/cryptopp.cmake new file mode 100644 index 000000000..a7e65d6c6 --- /dev/null +++ b/extdep/compile/cryptopp.cmake @@ -0,0 +1,33 @@ +# CryptoPP does not have good cross-platform support, there exist several different other projects to make it work ... + +# TODO the OS X build throws a lot of warnings, but compiles fine +if (APPLE) + ExternalProject_Add(cryptopp + URL https://downloads.sourceforge.net/project/cryptopp/cryptopp/5.6.2/cryptopp562.zip + BINARY_DIR cryptopp-prefix/src/cryptopp + CONFIGURE_COMMAND "" + BUILD_COMMAND make CXX=clang++ CXXFLAGS=-DCRYPTOPP_DISABLE_ASM + INSTALL_COMMAND make install PREFIX=${ETH_DEPENDENCY_INSTALL_DIR} + ) +elseif (WIN32) + file(MAKE_DIRECTORY ${ETH_DEPENDENCY_INSTALL_DIR}/include/cryptopp) + + ExternalProject_Add(cryptopp + SVN_REPOSITORY http://svn.code.sf.net/p/cryptopp/code/trunk/c5 + SVN_REVISION -r "541" + BINARY_DIR cryptopp-prefix/src/cryptopp + CONFIGURE_COMMAND devenv cryptest.sln /upgrade + BUILD_COMMAND devenv cryptest.sln /build release + INSTALL_COMMAND cmd /c cp Win32/DLL_Output/Release/cryptopp.dll ${ETH_DEPENDENCY_INSTALL_DIR}/lib && cp Win32/DLL_Output/Release/cryptopp.lib ${ETH_DEPENDENCY_INSTALL_DIR}/lib && cp *.h ${ETH_DEPENDENCY_INSTALL_DIR}/include/cryptopp + ) +# on Linux, the default Makefile does not work. +else() + ExternalProject_Add(cryptopp + URL https://github.com/mmoss/cryptopp/archive/v5.6.2.zip + BINARY_DIR cryptopp-prefix/src/cryptopp + CONFIGURE_COMMAND "" + BUILD_COMMAND scons --shared --prefix=${ETH_DEPENDENCY_INSTALL_DIR} + INSTALL_COMMAND "" + ) +endif() + diff --git a/extdep/compile/curl.cmake b/extdep/compile/curl.cmake new file mode 100644 index 000000000..64f253d43 --- /dev/null +++ b/extdep/compile/curl.cmake @@ -0,0 +1,29 @@ +if (APPLE) + ExternalProject_Add(curl + URL http://curl.haxx.se/download/curl-7.38.0.tar.bz2 + BINARY_DIR curl-prefix/src/curl + CONFIGURE_COMMAND ./configure --with-darwinssl --prefix=${ETH_DEPENDENCY_INSTALL_DIR} --exec-prefix=${ETH_DEPENDENCY_INSTALL_DIR} + BUILD_COMMAND make -j 3 + INSTALL_COMMAND make install + ) +elseif (WIN32) + ExternalProject_Add(curl + GIT_REPOSITORY https://github.com/debris/libcurl-7.29 + GIT_TAG master + BINARY_DIR curl-prefix/src/curl + CONFIGURE_COMMAND "" + BUILD_COMMAND "" + INSTALL_COMMAND cmd /c cp lib/release/libcurl.lib ${ETH_DEPENDENCY_INSTALL_DIR}/lib && cp -R include/curl ${ETH_DEPENDENCY_INSTALL_DIR}/include + ) + +else() + ExternalProject_Add(curl + URL http://curl.haxx.se/download/curl-7.38.0.tar.bz2 + BINARY_DIR curl-prefix/src/curl + CONFIGURE_COMMAND CONFIG_CMD ./configure --prefix=${ETH_DEPENDENCY_INSTALL_DIR} --exec-prefix=${ETH_DEPENDENCY_INSTALL_DIR} + BUILD_COMMAND make -j 3 + INSTALL_COMMAND make install + ) + +endif() + diff --git a/extdep/compile/icu.cmake b/extdep/compile/icu.cmake new file mode 100644 index 000000000..ba3f3a9f0 --- /dev/null +++ b/extdep/compile/icu.cmake @@ -0,0 +1,17 @@ +if (APPLE) + +elseif (WIN32) + ExternalProject_Add(icu + GIT_REPOSITORY https://github.com/debris/icu-win32.git + GIT_TAG master + BINARY_DIR icu-prefix/src/icu + CONFIGURE_COMMAND "" + BUILD_COMMAND "" + INSTALL_COMMAND cmake -E copy_directory . ${ETH_DEPENDENCY_INSTALL_DIR} + ) + +else() + +endif() + + diff --git a/extdep/compile/jom.cmake b/extdep/compile/jom.cmake new file mode 100644 index 000000000..f300fb2ad --- /dev/null +++ b/extdep/compile/jom.cmake @@ -0,0 +1,16 @@ +if (APPLE) + + +elseif (WIN32) + ExternalProject_Add(jom + URL http://download.qt-project.org/official_releases/jom/jom.zip + BINARY_DIR jom-prefix/src/jom + CONFIGURE_COMMAND "" + BUILD_COMMAND "" + INSTALL_COMMAND cmake -E copy jom.exe ${ETH_DEPENDENCY_INSTALL_DIR}/bin + ) + +else() + +endif() + diff --git a/extdep/compile/json-rpc-cpp.cmake b/extdep/compile/json-rpc-cpp.cmake new file mode 100644 index 000000000..9d56b0dac --- /dev/null +++ b/extdep/compile/json-rpc-cpp.cmake @@ -0,0 +1,40 @@ +# json-rpc-cpp is under heavy development, not yet stable, and multiplatform builds are not yet available. +# DO NOT MESS WITH THESE SETTINGS! IF YOU HAVE TO MAKE CHANGES HERE, CONSULT sven@ethdev.com BEFOREHAND!! + +# DO NOT CHANGE ANYTHING HERE! +if(APPLE) + ExternalProject_Add(json-rpc-cpp + # DEPENDS argtable2 jsoncpp + # DEPENDS curl # re-enable later, when we build curl again + GIT_REPOSITORY https://github.com/cinemast/libjson-rpc-cpp.git + GIT_TAG v0.3.2 + BINARY_DIR json-rpc-cpp-prefix/src/json-rpc-cpp + CONFIGURE_COMMAND cmake -DCMAKE_INSTALL_PREFIX=${ETH_DEPENDENCY_INSTALL_DIR} -DCMAKE_MODULE_PATH:PATH=${CMAKE_CURRENT_SOURCE_DIR}/cmake -DETH_DEPENDENCY_INSTALL_DIR:PATH=${ETH_DEPENDENCY_INSTALL_DIR} -DCMAKE_BUILD_TYPE=None -DCMAKE_FIND_FRAMEWORK=LAST -Wno-dev . + BUILD_COMMAND make -j 3 + INSTALL_COMMAND make install && ${CMAKE_CURRENT_SOURCE_DIR}/scripts/json-rpc-cpp_osx.sh . ${ETH_DEPENDENCY_INSTALL_DIR} + ) + +elseif (WIN32) + ExternalProject_Add(json-rpc-cpp + DEPENDS argtable2 jsoncpp curl + GIT_REPOSITORY https://github.com/debris/libjson-rpc-cpp.git + GIT_TAG windows + BINARY_DIR json-rpc-cpp-prefix/src/json-rpc-cpp + CONFIGURE_COMMAND cmake -DCMAKE_PREFIX_PATH=${ETH_DEPENDENCY_INSTALL_DIR} -DCURL_LIBRARIES=${ETH_DEPENDENCY_INSTALL_DIR}/lib/libcurl.lib . + BUILD_COMMAND devenv libjson-rpc-cpp.sln /build release + INSTALL_COMMAND cmd /c cp lib/Release/* ${ETH_DEPENDENCY_INSTALL_DIR}/lib && cp -R src/jsonrpccpp ${ETH_DEPENDENCY_INSTALL_DIR}/include + ) +else() + ExternalProject_Add(json-rpc-cpp + # DEPENDS argtable2 jsoncpp + # DEPENDS curl # re-enable later, when we build curl again + GIT_REPOSITORY https://github.com/cinemast/libjson-rpc-cpp.git + GIT_TAG v0.3.2 + BINARY_DIR json-rpc-cpp-prefix/src/json-rpc-cpp + CONFIGURE_COMMAND cmake -DCMAKE_INSTALL_PREFIX=${ETH_DEPENDENCY_INSTALL_DIR} -DCMAKE_MODULE_PATH:PATH=${CMAKE_CURRENT_SOURCE_DIR}/cmake -DETH_DEPENDENCY_INSTALL_DIR:PATH=${ETH_DEPENDENCY_INSTALL_DIR} -DCMAKE_BUILD_TYPE=None -DCMAKE_FIND_FRAMEWORK=LAST . + BUILD_COMMAND make -j 3 + INSTALL_COMMAND make install + ) + +endif() + diff --git a/extdep/compile/jsoncpp.cmake b/extdep/compile/jsoncpp.cmake new file mode 100644 index 000000000..c0d6c97cd --- /dev/null +++ b/extdep/compile/jsoncpp.cmake @@ -0,0 +1,16 @@ +if (APPLE) + +elseif (WIN32) + + file(MAKE_DIRECTORY ${ETH_DEPENDENCY_INSTALL_DIR}/include/jsoncpp) + ExternalProject_Add(jsoncpp + GIT_REPOSITORY https://github.com/open-source-parsers/jsoncpp + GIT_TAG svn-import + BINARY_DIR jsoncpp-prefix/src/jsoncpp + CONFIGURE_COMMAND cmake . + BUILD_COMMAND devenv jsoncpp.sln /build release + INSTALL_COMMAND cmd /c cp lib/Release/jsoncpp.lib ${ETH_DEPENDENCY_INSTALL_DIR}/lib && cp -R include/json ${ETH_DEPENDENCY_INSTALL_DIR}/include/jsoncpp + ) + +else() +endif() diff --git a/extdep/compile/leveldb.cmake b/extdep/compile/leveldb.cmake new file mode 100644 index 000000000..2f5388c14 --- /dev/null +++ b/extdep/compile/leveldb.cmake @@ -0,0 +1,23 @@ +if (APPLE) + ExternalProject_Add(leveldb + #DEPENDS snappy + URL https://leveldb.googlecode.com/files/leveldb-1.15.0.tar.gz + BINARY_DIR leveldb-prefix/src/leveldb + #CONFIGURE_COMMAND patch < ${CMAKE_CURRENT_SOURCE_DIR}/compile/leveldb_osx.patch + CONFIGURE_COMMAND "" + BUILD_COMMAND export ETH_DEPENDENCY_INSTALL_DIR=${ETH_DEPENDENCY_INSTALL_DIR} && make -j 3 + INSTALL_COMMAND cp -rf include/leveldb ${ETH_DEPENDENCY_INSTALL_DIR}/include/ && cp libleveldb.a ${ETH_DEPENDENCY_INSTALL_DIR}/lib && cp libleveldb.dylib.1.15 ${ETH_DEPENDENCY_INSTALL_DIR}/lib/libleveldb.dylib + ) +elseif (WIN32) + ExternalProject_Add(leveldb + GIT_REPOSITORY https://github.com/debris/leveldb-win32.git + GIT_TAG master + BINARY_DIR leveldb-prefix/src/leveldb + CONFIGURE_COMMAND "" + BUILD_COMMAND "" + INSTALL_COMMAND cmd /c cp lib/LibLevelDB.lib ${ETH_DEPENDENCY_INSTALL_DIR}/lib/leveldb.lib && cp -R include/leveldb ${ETH_DEPENDENCY_INSTALL_DIR}/include + ) +else() + +endif() + diff --git a/extdep/compile/leveldb_osx.patch b/extdep/compile/leveldb_osx.patch new file mode 100644 index 000000000..ac9e8f528 --- /dev/null +++ b/extdep/compile/leveldb_osx.patch @@ -0,0 +1,18 @@ +--- Makefile 2014-11-07 00:54:05.000000000 +0100 ++++ MakefilePatch 2014-11-07 00:56:59.000000000 +0100 +@@ -17,11 +17,11 @@ + # this file is generated by the previous line to set build flags and sources + include build_config.mk + +-CFLAGS += -I. -I./include $(PLATFORM_CCFLAGS) $(OPT) +-CXXFLAGS += -I. -I./include $(PLATFORM_CXXFLAGS) $(OPT) ++CFLAGS += -I. -I./include $(PLATFORM_CCFLAGS) $(OPT) ++CXXFLAGS += -I. -I./include $(PLATFORM_CXXFLAGS) $(OPT) -DSNAPPY -I$(ETH_DEPENDENCY_INSTALL_DIR)/include + +-LDFLAGS += $(PLATFORM_LDFLAGS) +-LIBS += $(PLATFORM_LIBS) ++LDFLAGS += $(PLATFORM_LDFLAGS) -L$(ETH_DEPENDENCY_INSTALL_DIR)/lib ++LIBS += $(PLATFORM_LIBS) -lsnappy + + LIBOBJECTS = $(SOURCES:.cc=.o) + MEMENVOBJECTS = $(MEMENV_SOURCES:.cc=.o) diff --git a/extdep/compile/qt.cmake b/extdep/compile/qt.cmake new file mode 100644 index 000000000..5fb8a1440 --- /dev/null +++ b/extdep/compile/qt.cmake @@ -0,0 +1,32 @@ +if (APPLE) + ExternalProject_add(qt + URL http://qtmirror.ics.com/pub/qtproject/official_releases/qt/5.3/5.3.2/single/qt-everywhere-opensource-src-5.3.2.tar.gz + BINARY_DIR qt-prefix/src/qt + PATCH_COMMAND patch -d qtmultimedia/src/plugins/avfoundation/mediaplayer < ${CMAKE_CURRENT_SOURCE_DIR}/compile/qt_osx.patch + CONFIGURE_COMMAND ./configure -prefix ${ETH_DEPENDENCY_INSTALL_DIR} -system-zlib -qt-libpng -qt-libjpeg -confirm-license -opensource -nomake tests -release -nomake examples -no-xcb -arch x86_64 + BUILD_COMMAND make + INSTALL_COMMAND make install + ) +elseif(WIN32) + ExternalProject_Add(qt + DEPENDS icu jom + URL http://qtmirror.ics.com/pub/qtproject/official_releases/qt/5.3/5.3.2/single/qt-everywhere-opensource-src-5.3.2.tar.gz + BINARY_DIR qt-prefix/src/qt + UPDATE_COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/compile/qt_tools.bat + #PATCH_COMMAND cmake -E copy ${CMAKE_CURRENT_SOURCE_DIR}/compile/qt_configure.bat qtbase/configure.bat + CONFIGURE_COMMAND configure -prefix ${ETH_DEPENDENCY_INSTALL_DIR} -opensource -confirm-license -release -opengl desktop -platform win32-msvc2013 -icu -I ${ETH_DEPENDENCY_INSTALL_DIR}/include -L ${ETH_DEPENDENCY_INSTALL_DIR}/lib -nomake tests -nomake examples + BUILD_COMMAND nmake + INSTALL_COMMAND nmake install + ) + + ExternalProject_Add_Step(qt configure_paths + COMMAND set PATH=${ETH_DEPENDENCY_INSTALL_DIR}/bin;%cd%/gnuwin32/bin;%cd%/qtbase/bin;%PATH% + DEPENDEES patch + DEPENDERS configure + ) + +else() + +endif() + + diff --git a/extdep/compile/qt_configure.bat b/extdep/compile/qt_configure.bat new file mode 100644 index 000000000..bd810938a --- /dev/null +++ b/extdep/compile/qt_configure.bat @@ -0,0 +1,111 @@ +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:: +:: Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +:: Contact: http://www.qt-project.org/legal +:: +:: This file is part of the tools applications of the Qt Toolkit. +:: +:: $QT_BEGIN_LICENSE:LGPL$ +:: Commercial License Usage +:: Licensees holding valid commercial Qt licenses may use this file in +:: accordance with the commercial license agreement provided with the +:: Software or, alternatively, in accordance with the terms contained in +:: a written agreement between you and Digia. For licensing terms and +:: conditions see http://qt.digia.com/licensing. For further information +:: use the contact form at http://qt.digia.com/contact-us. +:: +:: GNU Lesser General Public License Usage +:: Alternatively, this file may be used under the terms of the GNU Lesser +:: General Public License version 2.1 as published by the Free Software +:: Foundation and appearing in the file LICENSE.LGPL included in the +:: packaging of this file. Please review the following information to +:: ensure the GNU Lesser General Public License version 2.1 requirements +:: will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +:: +:: In addition, as a special exception, Digia gives you certain additional +:: rights. These rights are described in the Digia Qt LGPL Exception +:: version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +:: +:: GNU General Public License Usage +:: Alternatively, this file may be used under the terms of the GNU +:: General Public License version 3.0 as published by the Free Software +:: Foundation and appearing in the file LICENSE.GPL included in the +:: packaging of this file. Please review the following information to +:: ensure the GNU General Public License version 3.0 requirements will be +:: met: http://www.gnu.org/copyleft/gpl.html. +:: +:: +:: $QT_END_LICENSE$ +:: +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: + +@echo off +set QTSRC=%~dp0 +set QTDIR=%CD% +::if not exist %QTSRC%\.gitignore goto sconf +echo Please wait while bootstrapping configure ... + +for %%C in (cl.exe icl.exe g++.exe perl.exe) do set %%C=%%~$PATH:C + +if "%perl.exe%" == "" ( + echo Perl not found in PATH. Aborting. >&2 + exit /b 1 +) +if not exist mkspecs ( + md mkspecs + if errorlevel 1 goto exit +) +perl %QTSRC%bin\syncqt.pl -minimal -module QtCore -outdir %QTDIR% %QTSRC% +if errorlevel 1 goto exit + +if not exist tools\configure ( + md tools\configure + if errorlevel 1 goto exit +) +cd tools\configure +if errorlevel 1 goto exit + +echo #### Generated by configure.bat - DO NOT EDIT! ####> Makefile +echo/>> Makefile +for /f "tokens=3 usebackq" %%V in (`findstr QT_VERSION_STR %QTSRC%\src\corelib\global\qglobal.h`) do @echo QTVERSION = %%~V>> Makefile +if not "%cl.exe%" == "" ( + echo CXX = cl>>Makefile + echo EXTRA_CXXFLAGS =>>Makefile + rem This must have a trailing space. + echo QTSRC = %QTSRC% >> Makefile + set tmpl=win32 + set make=nmake +) else if not "%icl.exe%" == "" ( + echo CXX = icl>>Makefile + echo EXTRA_CXXFLAGS = /Zc:forScope>>Makefile + rem This must have a trailing space. + echo QTSRC = %QTSRC% >> Makefile + set tmpl=win32 + set make=nmake +) else if not "%g++.exe%" == "" ( + echo CXX = g++>>Makefile + echo EXTRA_CXXFLAGS =>>Makefile + rem This must NOT have a trailing space. + echo QTSRC = %QTSRC:\=/%>> Makefile + set tmpl=mingw + set make=mingw32-make +) else ( + echo No suitable compiler found in PATH. Aborting. >&2 + cd ..\.. + exit /b 1 +) +echo/>> Makefile +type %QTSRC%tools\configure\Makefile.%tmpl% >> Makefile + +%make% +if errorlevel 1 (cd ..\.. & exit /b 1) + +cd ..\.. + +:conf +configure.exe -srcdir %QTSRC% %* +goto exit + +:sconf +%QTSRC%\configure.exe %* +:exit diff --git a/extdep/compile/qt_osx.patch b/extdep/compile/qt_osx.patch new file mode 100644 index 000000000..7900f6094 --- /dev/null +++ b/extdep/compile/qt_osx.patch @@ -0,0 +1,11 @@ +--- avfmediaplayersession.mm 2014-09-11 12:48:26.000000000 +0200 ++++ avfmediaplayersessionPatch.mm 2014-12-01 12:53:14.000000000 +0100 +@@ -295,7 +295,7 @@ + //AVPlayerItem "status" property value observer. + if (context == AVFMediaPlayerSessionObserverStatusObservationContext) + { +- AVPlayerStatus status = [[change objectForKey:NSKeyValueChangeNewKey] integerValue]; ++ AVPlayerStatus status = (AVPlayerStatus)[[change objectForKey:NSKeyValueChangeNewKey] integerValue]; + switch (status) + { + //Indicates that the status of the player is not yet known because diff --git a/extdep/compile/qt_tools.bat b/extdep/compile/qt_tools.bat new file mode 100644 index 000000000..bd588c480 --- /dev/null +++ b/extdep/compile/qt_tools.bat @@ -0,0 +1,2 @@ +rem : import VC environment vars +call "%VS120COMNTOOLS%\..\..\VC\vcvarsall.bat" x86 \ No newline at end of file diff --git a/extdep/compile/snappy.cmake b/extdep/compile/snappy.cmake new file mode 100644 index 000000000..0f7ba300e --- /dev/null +++ b/extdep/compile/snappy.cmake @@ -0,0 +1,14 @@ +if (APPLE) + ExternalProject_Add(snappy + URL https://snappy.googlecode.com/files/snappy-1.1.1.tar.gz + BINARY_DIR snappy-prefix/src/snappy + CONFIGURE_COMMAND ./configure --disable-dependency-tracking --prefix=${ETH_DEPENDENCY_INSTALL_DIR} + BUILD_COMMAND "" + INSTALL_COMMAND make install + ) +elseif(WIN32) + +else() + +endif() + diff --git a/extdep/eth_download.cmake b/extdep/eth_download.cmake new file mode 100644 index 000000000..96d6c5122 --- /dev/null +++ b/extdep/eth_download.cmake @@ -0,0 +1,74 @@ +# this macro requires the following variables to be specified: +# +# ETH_DEPENDENCY_SERVER - server from which dependencies should be downloaded +# ETH_DEPENDENCY_INSTALL_DIR - install location for all dependencies +# +# usage: +# +# eth_download("json-rpc-cpp") +# eth_download("json-rpc-cpp" VERSION "0.3.2") +# +# params: +# VERSION - exact version we want to use +# OSX_SCRIPT - script which will be executed on apple in install phase +# UNIX_SCRIPT - script which will be executed on unix in install phase +# WIN_SCRIPT - script which will be executed on win in install phase + +# OSX_SCRIPT, WIN_SCRIPT, UNIX_SCRIPT are taking 2 params: +# $1 is package_source, +# $2 is ETH_DEPENDENCY_INSTALL_DIR +# +# parsing arguments +# http://www.cmake.org/cmake/help/v3.0/module/CMakeParseArguments.html +# +# for macos you may need to specify OSX_SCRIPT with install_name_tool to fix dylib +# http://stackoverflow.com/questions/2985315/using-install-name-tool-whats-going-wrong +# +# TODO: +# check if install_command is handling symlinks correctly on linux and windows + +macro(eth_download eth_package_name) + + set (extra_macro_args ${ARGN}) + set (options) + set (one_value_args VERSION OSX_SCRIPT UNIX_SCRIPT WIN_SCRIPT) + set (multi_value_args) + cmake_parse_arguments (ETH_DOWNLOAD "${options}" "${one_value_args}" "${multi_value_args}" ${extra_macro_args}) + + if (ETH_DOWNLOAD_VERSION) + set(eth_tar_name "${eth_package_name}-${ETH_DOWNLOAD_VERSION}.tar.gz") + else() + set(eth_tar_name "${eth_package_name}.tar.gz") + endif() + + message(STATUS "download path for ${eth_package_name} is : ${ETH_DEPENDENCY_SERVER}/${eth_tar_name}") + + # we need that to copy symlinks + # see http://superuser.com/questions/138587/how-to-copy-symbolic-links + if (APPLE) + set (eth_package_copy cp -a . ${ETH_DEPENDENCY_INSTALL_DIR}) + set (eth_package_install ${ETH_DOWNLOAD_OSX_SCRIPT}) + elseif (UNIX) + set (eth_package_copy cp -a . ${ETH_DEPENDENCY_INSTALL_DIR}) + set (eth_package_install ${ETH_DOWNLOAD_UNIX_SCRIPT}) + else () + set (eth_package_copy cmake -E copy_directory . ${ETH_DEPENDENCY_INSTALL_DIR}) + set (eth_package_install ${ETH_DOWNLOAD_WIN_SCRIPT}) + endif() + + if (eth_package_install) + message(STATUS "install script: ${eth_package_install}") + set (eth_package_install ${eth_package_install} . ${ETH_DEPENDENCY_INSTALL_DIR}) + else () + set (eth_package_install echo 0) # cause empty string is not handled properly + endif() + + ExternalProject_Add(${eth_package_name} + URL ${ETH_DEPENDENCY_SERVER}/${eth_tar_name} + BINARY_DIR ${eth_package_name}-prefix/src/${eth_package_name} + CONFIGURE_COMMAND "" + BUILD_COMMAND ${eth_package_copy} + INSTALL_COMMAND ${eth_package_install} + ) +endmacro() + diff --git a/extdep/miniupnpc.cmake b/extdep/miniupnpc.cmake new file mode 100644 index 000000000..4fbed6807 --- /dev/null +++ b/extdep/miniupnpc.cmake @@ -0,0 +1,11 @@ +# TODO this file is not used yet, but will be in future +include(ExternalProject) + +ExternalProject_Add(miniupnpc + URL http://miniupnp.tuxfamily.org/files/download.php?file=miniupnpc-1.9.20141027.tar.gz + BINARY_DIR miniupnpc-prefix/src/miniupnpc + CONFIGURE_COMMAND "" + BUILD_COMMAND make -j 3 + INSTALL_COMMAND make install INSTALLPREFIX=${ETH_DEPENDENCY_INSTALL_DIR} +) + diff --git a/extdep/scripts/json-rpc-cpp_osx.sh b/extdep/scripts/json-rpc-cpp_osx.sh new file mode 100755 index 000000000..8a6b96c7b --- /dev/null +++ b/extdep/scripts/json-rpc-cpp_osx.sh @@ -0,0 +1,29 @@ +#!/bin/bash + +ETH_DEPENDENCY_SOURCE_DIR=$1 +ETH_DEPENDENCY_INSTALL_DIR=$2 + +OLD_COMMON_DYLIB="libjsonrpccpp-common.0.dylib" + +COMMON_DYLIB=${ETH_DEPENDENCY_INSTALL_DIR}/lib/libjsonrpccpp-common.0.dylib +SERVER_DYLIB=${ETH_DEPENDENCY_INSTALL_DIR}/lib/libjsonrpccpp-server.0.dylib +CLIENT_DYLIB=${ETH_DEPENDENCY_INSTALL_DIR}/lib/libjsonrpccpp-client.0.dylib + +# fix bin +STAB_EXEC=${ETH_DEPENDENCY_INSTALL_DIR}/bin/jsonrpcstub +install_name_tool -change ${OLD_COMMON_DYLIB} ${COMMON_DYLIB} ${STAB_EXEC} + +# fix common +install_name_tool -id ${COMMON_DYLIB} ${COMMON_DYLIB} + +# fix server +install_name_tool -id ${SERVER_DYLIB} ${SERVER_DYLIB} +install_name_tool -change ${OLD_COMMON_DYLIB} ${COMMON_DYLIB} ${SERVER_DYLIB} + +# fix client +install_name_tool -id ${CLIENT_DYLIB} ${CLIENT_DYLIB} +install_name_tool -change ${OLD_COMMON_DYLIB} ${COMMON_DYLIB} ${CLIENT_DYLIB} + +# TODO fix argtable and jsoncpp once they are downloaded as dependencies + + diff --git a/extdep/scripts/leveldb_osx.sh b/extdep/scripts/leveldb_osx.sh new file mode 100755 index 000000000..06b4a2dbd --- /dev/null +++ b/extdep/scripts/leveldb_osx.sh @@ -0,0 +1,12 @@ +#!/bin/bash + +ETH_DEPENDENCY_SOURCE_DIR=$1 +ETH_DEPENDENCY_INSTALL_DIR=$2 + +OLD_SNAPPY_DYLIB="/Users/marekkotewicz/ethereum/cpp-ethereum/extdep/install/darwin/lib/libsnappy.1.dylib" +SNAPPY_DYLIB=${ETH_DEPENDENCY_INSTALL_DIR}/lib/libsnappy.dylib +LEVELDB_DYLIB=${ETH_DEPENDENCY_INSTALL_DIR}/lib/libleveldb.dylib + +install_name_tool -id ${LEVELDB_DYLIB} ${LEVELDB_DYLIB} +install_name_tool -change ${OLD_SNAPPY_DYLIB} ${SNAPPY_DYLIB} ${LEVELDB_DYLIB} + diff --git a/extdep/scripts/snappy_osx.sh b/extdep/scripts/snappy_osx.sh new file mode 100755 index 000000000..01304fcf1 --- /dev/null +++ b/extdep/scripts/snappy_osx.sh @@ -0,0 +1,8 @@ +#!/bin/bash + +ETH_DEPENDENCY_SOURCE_DIR=$1 +ETH_DEPENDENCY_INSTALL_DIR=$2 + +SNAPPY_DYLIB=${ETH_DEPENDENCY_INSTALL_DIR}/lib/libsnappy.dylib +install_name_tool -id ${SNAPPY_DYLIB} ${SNAPPY_DYLIB} + diff --git a/iethxi/CMakeLists.txt b/iethxi/CMakeLists.txt deleted file mode 100644 index fc8edf1dc..000000000 --- a/iethxi/CMakeLists.txt +++ /dev/null @@ -1,117 +0,0 @@ -cmake_policy(SET CMP0015 NEW) - -if ("${TARGET_PLATFORM}" STREQUAL "w64") - cmake_policy(SET CMP0020 NEW) -endif () - - -set(CMAKE_INCLUDE_CURRENT_DIR ON) -aux_source_directory(. SRC_LIST) - -include_directories(..) -link_directories(../libethcore) -link_directories(../libethereum) -link_directories(../libqethereum) - -# Find Qt5 for Apple and update src_list for windows -if (APPLE) - # homebrew defaults to qt4 and installs qt5 as 'keg-only' - # which places it into /usr/local/opt insteadof /usr/local. - - set(CMAKE_PREFIX_PATH /usr/local/opt/qt5) - include_directories(/usr/local/opt/qt5/include /usr/local/include) -elseif ("${TARGET_PLATFORM}" STREQUAL "w64") - set(SRC_LIST ${SRC_LIST} ../windows/qt_plugin_import.cpp) -elseif (UNIX) - set(CMAKE_PREFIX_PATH ${CMAKE_PREFIX_PATH} ";$ENV{QTDIR}/lib/cmake") -endif () - - -find_package(Qt5Widgets REQUIRED) -find_package(Qt5Gui REQUIRED) -find_package(Qt5Quick REQUIRED) -find_package(Qt5Qml REQUIRED) -find_package(Qt5Network REQUIRED) -qt5_wrap_ui(ui_Main.h Main.ui) -qt5_add_resources(RESOURCE_ADDED Resources.qrc) - -# Set name of binary and add_executable() -if (APPLE) - set(EXECUTEABLE IEthXi) - set(CMAKE_INSTALL_PREFIX ./) - set(BIN_INSTALL_DIR ".") - set(DOC_INSTALL_DIR ".") - - set(PROJECT_VERSION "${ETH_VERSION}") - set(MACOSX_BUNDLE_INFO_STRING "${PROJECT_NAME} ${PROJECT_VERSION}") - set(MACOSX_BUNDLE_BUNDLE_VERSION "${PROJECT_NAME} ${PROJECT_VERSION}") - set(MACOSX_BUNDLE_LONG_VERSION_STRING "${PROJECT_NAME} ${PROJECT_VERSION}") - set(MACOSX_BUNDLE_SHORT_VERSION_STRING "${PROJECT_VERSION}") - set(MACOSX_BUNDLE_COPYRIGHT "${PROJECT_COPYRIGHT_YEAR} ${PROJECT_VENDOR}") - set(MACOSX_BUNDLE_GUI_IDENTIFIER "${PROJECT_DOMAIN_SECOND}.${PROJECT_DOMAIN_FIRST}") - set(MACOSX_BUNDLE_BUNDLE_NAME ${EXECUTEABLE}) - include(BundleUtilities) - - add_executable(${EXECUTEABLE} MACOSX_BUNDLE Main.ui ${RESOURCE_ADDED} ${SRC_LIST}) -else () - set(EXECUTEABLE iethxi) - add_executable(${EXECUTEABLE} Main.ui ${RESOURCE_ADDED} ${SRC_LIST}) -endif () - -qt5_use_modules(${EXECUTEABLE} Core Gui Widgets Network Quick Qml) -target_link_libraries(${EXECUTEABLE} qethereum ethereum secp256k1 ${CRYPTOPP_LS}) - -if (APPLE) - if (${ADDFRAMEWORKS}) - set_target_properties(${EXECUTEABLE} PROPERTIES MACOSX_BUNDLE_INFO_PLIST "${CMAKE_CURRENT_SOURCE_DIR}/EthereumMacOSXBundleInfo.plist.in") - endif () - - SET_SOURCE_FILES_PROPERTIES(${EXECUTEABLE} PROPERTIES MACOSX_PACKAGE_LOCATION MacOS) - - # This is a workaround for when the build-type defaults to Debug, and when a multi-config generator like xcode is used, where the type - # will not be set but defaults to release. - set(generator_lowercase "${CMAKE_GENERATOR}") - string(TOLOWER "${CMAKE_GENERATOR}" generator_lowercase) - if ("${generator_lowercase}" STREQUAL "xcode") - # TODO: Not sure how to resolve this. Possibly \${TARGET_BUILD_DIR} - set(binary_build_dir "${CMAKE_CURRENT_BINARY_DIR}/Debug") - else () - set(binary_build_dir "${CMAKE_CURRENT_BINARY_DIR}") - endif () - - set(APPS ${binary_build_dir}/${EXECUTEABLE}.app) - - # This tool and the next will automatically looked at the linked libraries in order to determine what dependencies are required. Thus, target_link_libaries only needs to add ethereum and secp256k1 (above) - install(CODE " - include(BundleUtilities) - set(BU_CHMOD_BUNDLE_ITEMS 1) - fixup_bundle(\"${APPS}\" \"${BUNDLELIBS}\" \"../libqethereum ../libethereum ../secp256k1\") - " COMPONENT RUNTIME ) - - if (${ADDFRAMEWORKS}) - add_custom_target(addframeworks ALL - COMMAND /usr/local/opt/qt5/bin/macdeployqt ${binary_build_dir}/${EXECUTEABLE}.app - WORKING_DIRECTORY ${CMAKE_RUNTIME_OUTPUT_DIRECTORY} - DEPENDS ${PROJECT_NAME} - ) - endif () - -elseif ("${TARGET_PLATFORM}" STREQUAL "w64") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fno-keep-inline-dllexport -static-libgcc -static-libstdc++ -static") - set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,-s -Wl,-subsystem,windows -mthreads -L/usr/x86_64-w64-mingw32/plugins/platforms") - target_link_libraries(${EXECUTEABLE} gcc) - target_link_libraries(${EXECUTEABLE} mingw32 qtmain mswsock iphlpapi qwindows shlwapi Qt5PlatformSupport gdi32 comdlg32 oleaut32 imm32 winmm ole32 uuid ws2_32) - target_link_libraries(${EXECUTEABLE} boost_system-mt-s) - target_link_libraries(${EXECUTEABLE} boost_filesystem-mt-s) - target_link_libraries(${EXECUTEABLE} boost_thread_win32-mt-s) - target_link_libraries(${EXECUTEABLE} Qt5PlatformSupport) - set(CMAKE_SHARED_LIBRARY_LINK_CXX_FLAGS) -elseif (UNIX) -else () - target_link_libraries(${EXECUTEABLE} boost_system) - target_link_libraries(${EXECUTEABLE} boost_filesystem) - find_package(Threads REQUIRED) - target_link_libraries(${EXECUTEABLE} ${CMAKE_THREAD_LIBS_INIT}) - install( TARGETS ${EXECUTEABLE} RUNTIME DESTINATION bin ) -endif () - diff --git a/iethxi/EthereumMacOSXBundleInfo.plist.in b/iethxi/EthereumMacOSXBundleInfo.plist.in deleted file mode 100644 index 684ad7908..000000000 --- a/iethxi/EthereumMacOSXBundleInfo.plist.in +++ /dev/null @@ -1,38 +0,0 @@ - - - - - CFBundleDevelopmentRegion - English - CFBundleExecutable - ${MACOSX_BUNDLE_EXECUTABLE_NAME} - CFBundleGetInfoString - ${MACOSX_BUNDLE_INFO_STRING} - CFBundleIconFile - ${MACOSX_BUNDLE_ICON_FILE} - CFBundleIdentifier - ${MACOSX_BUNDLE_GUI_IDENTIFIER} - CFBundleInfoDictionaryVersion - 6.0 - CFBundleLongVersionString - ${MACOSX_BUNDLE_LONG_VERSION_STRING} - CFBundleName - ${MACOSX_BUNDLE_BUNDLE_NAME} - CFBundlePackageType - APPL - CFBundleShortVersionString - ${MACOSX_BUNDLE_SHORT_VERSION_STRING} - CFBundleSignature - ???? - CFBundleVersion - ${MACOSX_BUNDLE_BUNDLE_VERSION} - CSResourcesFileMapped - - LSRequiresCarbon - - NSHumanReadableCopyright - ${MACOSX_BUNDLE_COPYRIGHT} - NSHighResolutionCapable - - - diff --git a/iethxi/Main.ui b/iethxi/Main.ui deleted file mode 100644 index fe289ba9f..000000000 --- a/iethxi/Main.ui +++ /dev/null @@ -1,168 +0,0 @@ - - - Main - - - - 0 - 0 - 562 - 488 - - - - Walleth - - - true - - - QMainWindow::AllowNestedDocks|QMainWindow::AllowTabbedDocks|QMainWindow::VerticalTabs - - - true - - - - - 0 - - - 0 - - - 0 - - - 0 - - - - - - - 0 wei - - - - - - - 0 peers - - - - - - - 1 block - - - - - - - - - - - 0 - 0 - 562 - 25 - - - - - &File - - - - - - &Network - - - - - - - - T&ools - - - - - - - - &Help - - - - - - - - - - - - &Quit - - - - - true - - - true - - - Use &UPnP - - - - - &Connect to Peer... - - - - - true - - - Enable &Network - - - - - true - - - &Mine - - - - - &New Address - - - - - &About... - - - - - true - - - &Preview - - - - - - - diff --git a/iethxi/MainWin.cpp b/iethxi/MainWin.cpp deleted file mode 100644 index 2d5b57094..000000000 --- a/iethxi/MainWin.cpp +++ /dev/null @@ -1,59 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "BuildInfo.h" -#include "MainWin.h" -#include "ui_Main.h" -using namespace std; -using namespace eth; - -Main::Main(QWidget *parent) : - QObject(parent) -{ -/* qRegisterMetaType("eth::u256"); - qRegisterMetaType("eth::KeyPair"); - qRegisterMetaType("eth::Secret"); - qRegisterMetaType("eth::Address"); - qRegisterMetaType("QmlAccount*"); - qRegisterMetaType("QmlEthereum*"); - - qmlRegisterType("org.ethereum", 1, 0, "Ethereum"); - qmlRegisterType("org.ethereum", 1, 0, "Account"); - qmlRegisterSingletonType("org.ethereum", 1, 0, "Balance", QmlEthereum::constructU256Helper); - qmlRegisterSingletonType("org.ethereum", 1, 0, "Key", QmlEthereum::constructKeyHelper); -*/ - /* - ui->librariesView->setModel(m_libraryMan); - ui->graphsView->setModel(m_graphMan); - */ - - - - -// QQmlContext* context = m_view->rootContext(); -// context->setContextProperty("u256", new U256Helper(this)); -} - -Main::~Main() -{ -} - -// extra bits needed to link on VS -#ifdef _MSC_VER - -// include moc file, ofuscated to hide from automoc -#include\ -"moc_MainWin.cpp" - -#endif diff --git a/iethxi/MainWin.h b/iethxi/MainWin.h deleted file mode 100644 index acbea8ca8..000000000 --- a/iethxi/MainWin.h +++ /dev/null @@ -1,18 +0,0 @@ -#ifndef MAIN_H -#define MAIN_H - -#include - -class Main: public QObject -{ - Q_OBJECT - -public: - explicit Main(QWidget *parent = 0); - ~Main(); - -private: - QQmlApplicationEngine* m_view; -}; - -#endif // MAIN_H diff --git a/iethxi/Resources.qrc b/iethxi/Resources.qrc deleted file mode 100644 index 1789216ed..000000000 --- a/iethxi/Resources.qrc +++ /dev/null @@ -1,5 +0,0 @@ - - - Simple.qml - - diff --git a/iethxi/Simple.qml b/iethxi/Simple.qml deleted file mode 100644 index ac9dc5e37..000000000 --- a/iethxi/Simple.qml +++ /dev/null @@ -1,9 +0,0 @@ -import QtQuick.Controls 1.1 - -ApplicationWindow { - title: "My App" - Button { - text: "Push Me" - anchors.centerIn: parent - } -} diff --git a/iethxi/main.cpp b/iethxi/main.cpp deleted file mode 100644 index 569b6d17c..000000000 --- a/iethxi/main.cpp +++ /dev/null @@ -1,9 +0,0 @@ -#include -#include - -int main(int argc, char *argv[]) -{ - QApplication a(argc, argv); - QQmlApplicationEngine app(QUrl("qrc:/Simple.qml")); - return a.exec(); -} diff --git a/libdevcore/All.h b/libdevcore/All.h deleted file mode 100644 index eac152d42..000000000 --- a/libdevcore/All.h +++ /dev/null @@ -1,8 +0,0 @@ -#pragma once - -#include "Common.h" -#include "CommonData.h" -#include "CommonIO.h" -#include "FixedHash.h" -#include "Log.h" -#include "RLP.h" diff --git a/libdevcore/CMakeLists.txt b/libdevcore/CMakeLists.txt index 7c54301c9..001c568b5 100644 --- a/libdevcore/CMakeLists.txt +++ b/libdevcore/CMakeLists.txt @@ -1,49 +1,42 @@ cmake_policy(SET CMP0015 NEW) - -if (CMAKE_MAJOR_VERSION GREATER 1 AND CMAKE_MINOR_VERSION GREATER 7 AND CMAKE_PATCH_VERSION GREATER 11) - cmake_policy(SET CMP0022 NEW) +# this policy was introduced in cmake 3.0 +# remove if, once 3.0 will be used on unix +if (${CMAKE_MAJOR_VERSION} GREATER 2) + # old policy do not use MACOSX_RPATH + cmake_policy(SET CMP0042 OLD) endif() +set(CMAKE_AUTOMOC OFF) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DSTATICLIB") aux_source_directory(. SRC_LIST) +include_directories(${Boost_INCLUDE_DIRS}) +include_directories(..) + set(EXECUTABLE devcore) file(GLOB HEADERS "*.h") + if(ETH_STATIC) add_library(${EXECUTABLE} STATIC ${SRC_LIST} ${HEADERS}) else() add_library(${EXECUTABLE} SHARED ${SRC_LIST} ${HEADERS}) endif() -include_directories(..) +target_link_libraries(${EXECUTABLE} ${Boost_THREAD_LIBRARY_RELEASE}) +target_link_libraries(${EXECUTABLE} ${Boost_DATE_TIME_LIBRARY_RELEASE}) +target_link_libraries(${EXECUTABLE} ${Boost_SYSTEM_LIBRARY_RELEASE}) +target_link_libraries(${EXECUTABLE} ${Boost_CHRONO_LIBRARY_RELEASE}) -if("${TARGET_PLATFORM}" STREQUAL "w64") - include_directories(/usr/x86_64-w64-mingw32/include/cryptopp) - target_link_libraries(${EXECUTABLE} boost_system-mt-s) - target_link_libraries(${EXECUTABLE} boost_thread_win32-mt-s) - target_link_libraries(${EXECUTABLE} iphlpapi) - target_link_libraries(${EXECUTABLE} ws2_32) - target_link_libraries(${EXECUTABLE} mswsock) - target_link_libraries(${EXECUTABLE} shlwapi) -elseif (APPLE) - # Latest mavericks boost libraries only come with -mt - target_link_libraries(${EXECUTABLE} boost_system-mt) - target_link_libraries(${EXECUTABLE} boost_filesystem-mt) - target_link_libraries(${EXECUTABLE} boost_thread-mt) +if (APPLE) find_package(Threads REQUIRED) target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT}) elseif (UNIX) - find_package(Boost 1.53 REQUIRED COMPONENTS thread system) - target_link_libraries(${EXECUTABLE} ${Boost_THREAD_LIBRARY} ${Boost_SYSTEM_LIBRARY}) - find_package(Threads REQUIRED) - target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT}) -else () - target_link_libraries(${EXECUTABLE} boost_thread) find_package(Threads REQUIRED) target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT}) -endif () +endif() install( TARGETS ${EXECUTABLE} ARCHIVE DESTINATION lib LIBRARY DESTINATION lib ) install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} ) diff --git a/libdevcore/Common.cpp b/libdevcore/Common.cpp index 78dbed65b..55250b418 100644 --- a/libdevcore/Common.cpp +++ b/libdevcore/Common.cpp @@ -27,7 +27,7 @@ using namespace dev; namespace dev { -char const* Version = "0.7.9"; +char const* Version = "0.7.12"; } diff --git a/libdevcore/Common.h b/libdevcore/Common.h index 87cc069b3..198119f24 100644 --- a/libdevcore/Common.h +++ b/libdevcore/Common.h @@ -59,6 +59,7 @@ using bytesConstRef = vector_ref; // Numeric types. using bigint = boost::multiprecision::number>; +using u128 = boost::multiprecision::number>; using u256 = boost::multiprecision::number>; using s256 = boost::multiprecision::number>; using u160 = boost::multiprecision::number>; diff --git a/libdevcore/CommonData.cpp b/libdevcore/CommonData.cpp index bfcbc5e2e..215f9c4b3 100644 --- a/libdevcore/CommonData.cpp +++ b/libdevcore/CommonData.cpp @@ -23,20 +23,27 @@ #include #include "Exceptions.h" -#include +#include "Log.h" + using namespace std; using namespace dev; std::string dev::escaped(std::string const& _s, bool _all) { + static const map prettyEscapes{{'\r', 'r'}, {'\n', 'n'}, {'\t', 't'}, {'\v', 'v'}}; std::string ret; - ret.reserve(_s.size()); + ret.reserve(_s.size() + 2); ret.push_back('"'); for (auto i: _s) if (i == '"' && !_all) ret += "\\\""; else if (i == '\\' && !_all) ret += "\\\\"; + else if (prettyEscapes.count(i)) + { + ret += '\\'; + ret += prettyEscapes.find(i)->second; + } else if (i < ' ' || _all) { ret += "\\x"; @@ -82,13 +89,25 @@ bytes dev::fromHex(std::string const& _s) { ret.push_back(fromHex(_s[s++])); } - catch (...){ ret.push_back(0); cwarn << boost::current_exception_diagnostic_information(); } + catch (...) + { + ret.push_back(0); + // msvc does not support it +#ifndef BOOST_NO_EXCEPTIONS + cwarn << boost::current_exception_diagnostic_information(); +#endif + } for (unsigned i = s; i < _s.size(); i += 2) try { ret.push_back((byte)(fromHex(_s[i]) * 16 + fromHex(_s[i + 1]))); } - catch (...){ ret.push_back(0); cwarn << boost::current_exception_diagnostic_information(); } + catch (...){ + ret.push_back(0); +#ifndef BOOST_NO_EXCEPTIONS + cwarn << boost::current_exception_diagnostic_information(); +#endif + } return ret; } diff --git a/libdevcore/CommonIO.cpp b/libdevcore/CommonIO.cpp index 3d2eccf13..8fc4fedb3 100644 --- a/libdevcore/CommonIO.cpp +++ b/libdevcore/CommonIO.cpp @@ -30,7 +30,7 @@ string dev::memDump(bytes const& _b, unsigned _w, bool _html) { stringstream ret; if (_html) - ret << "
";
+		ret << "
";
 	for (unsigned i = 0; i < _b.size(); i += _w)
 	{
 		ret << hex << setw(4) << setfill('0') << i << " ";
diff --git a/libdevcore/CommonJS.cpp b/libdevcore/CommonJS.cpp
index 96f4b1896..c09a5b565 100644
--- a/libdevcore/CommonJS.cpp
+++ b/libdevcore/CommonJS.cpp
@@ -38,31 +38,20 @@ bytes jsToBytes(std::string const& _s)
 		return bytes();
 }
 
-std::string jsPadded(std::string const& _s, unsigned _l, unsigned _r)
+bytes padded(bytes _b, unsigned _l)
 {
-	bytes b = jsToBytes(_s);
-	while (b.size() < _l)
-		b.insert(b.begin(), 0);
-	while (b.size() < _r)
-		b.push_back(0);
-	return asString(b).substr(b.size() - std::max(_l, _r));
+	while (_b.size() < _l)
+		_b.insert(_b.begin(), 0);
+	while (_b.size() < _l)
+		_b.push_back(0);
+	return asBytes(asString(_b).substr(_b.size() - std::max(_l, _l)));
 }
 
-std::string jsPadded(std::string const& _s, unsigned _l)
+bytes unpadded(bytes _b)
 {
-	if (_s.substr(0, 2) == "0x" || _s.find_first_not_of("0123456789") == std::string::npos)
-		// Numeric: pad to right
-		return jsPadded(_s, _l, _l);
-	else
-		// Text: pad to the left
-		return jsPadded(_s, 0, _l);
-}
-
-std::string jsUnpadded(std::string _s)
-{
-	auto p = _s.find_last_not_of((char)0);
-	_s.resize(p == std::string::npos ? 0 : (p + 1));
-	return _s;
+	auto p = asString(_b).find_last_not_of((char)0);
+	_b.resize(p == std::string::npos ? 0 : (p + 1));
+	return _b;
 }
 
 }
diff --git a/libdevcore/CommonJS.h b/libdevcore/CommonJS.h
index be98c2372..80e1a9ca1 100644
--- a/libdevcore/CommonJS.h
+++ b/libdevcore/CommonJS.h
@@ -47,9 +47,8 @@ inline std::string toJS(dev::bytes const& _n)
 }
 
 bytes jsToBytes(std::string const& _s);
-std::string jsPadded(std::string const& _s, unsigned _l, unsigned _r);
-std::string jsPadded(std::string const& _s, unsigned _l);
-std::string jsUnpadded(std::string _s);
+bytes padded(bytes _b, unsigned _l);
+bytes unpadded(bytes _s);
 
 template  FixedHash jsToFixed(std::string const& _s)
 {
@@ -61,7 +60,7 @@ template  FixedHash jsToFixed(std::string const& _s)
 		return (typename FixedHash::Arith)(_s);
 	else
 		// Binary
-		return FixedHash(asBytes(jsPadded(_s, N)));
+		return FixedHash();	// FAIL
 }
 
 inline std::string jsToFixed(double _s)
@@ -79,7 +78,7 @@ template  boost::multiprecision::number>(_s);
 	else
 		// Binary
-		return fromBigEndian>>(asBytes(jsPadded(_s, N)));
+		return 0;			// FAIL
 }
 
 inline Address jsToAddress(std::string const& _s) { return jsToFixed(_s); }
@@ -89,7 +88,7 @@ inline u256 jsToU256(std::string const& _s) { return jsToInt<32>(_s); }
 
 inline std::string jsToBinary(std::string const& _s)
 {
-	return jsUnpadded(dev::toString(jsToBytes(_s)));
+	return dev::toString(unpadded(jsToBytes(_s)));
 }
 
 inline std::string jsToDecimal(std::string const& _s)
diff --git a/libdevcore/Exceptions.h b/libdevcore/Exceptions.h
index bbc928da4..5d03c195f 100644
--- a/libdevcore/Exceptions.h
+++ b/libdevcore/Exceptions.h
@@ -45,7 +45,7 @@ struct FileError: virtual Exception {};
 typedef boost::error_info errinfo_invalidSymbol;
 typedef boost::error_info errinfo_wrongAddress;
 typedef boost::error_info errinfo_comment;
-typedef boost::error_info errinfo_required;
-typedef boost::error_info errinfo_got;
+typedef boost::error_info errinfo_required;
+typedef boost::error_info errinfo_got;
 typedef boost::tuple RequirementError;
 }
diff --git a/libdevcore/FixedHash.h b/libdevcore/FixedHash.h
index 2353a100c..6c42aa501 100644
--- a/libdevcore/FixedHash.h
+++ b/libdevcore/FixedHash.h
@@ -83,6 +83,7 @@ public:
 	bool operator==(FixedHash const& _c) const { return m_data == _c.m_data; }
 	bool operator!=(FixedHash const& _c) const { return m_data != _c.m_data; }
 	bool operator<(FixedHash const& _c) const { return m_data < _c.m_data; }
+	bool operator>=(FixedHash const& _c) const { return m_data >= _c.m_data; }
 
 	// The obvious binary operators.
 	FixedHash& operator^=(FixedHash const& _c) { for (unsigned i = 0; i < N; ++i) m_data[i] ^= _c.m_data[i]; return *this; }
@@ -240,6 +241,7 @@ using h520 = FixedHash<65>;
 using h512 = FixedHash<64>;
 using h256 = FixedHash<32>;
 using h160 = FixedHash<20>;
+using h128 = FixedHash<16>;
 using h512s = std::vector;
 using h256s = std::vector;
 using h160s = std::vector;
diff --git a/libdevcore/RLP.h b/libdevcore/RLP.h
index afedc68da..2eedbaba2 100644
--- a/libdevcore/RLP.h
+++ b/libdevcore/RLP.h
@@ -28,10 +28,10 @@
 #include 
 #include 
 #include 
-#include 
-#include 
-#include 
-#include 
+#include "vector_ref.h"
+#include "Common.h"
+#include "Exceptions.h"
+#include "FixedHash.h"
 
 namespace dev
 {
@@ -158,6 +158,7 @@ public:
 
 	/// Best-effort conversion operators.
 	explicit operator std::string() const { return toString(); }
+	explicit operator bytes() const { return toBytes(); }
 	explicit operator RLPs() const { return toList(); }
 	explicit operator uint8_t() const { return toInt(); }
 	explicit operator uint16_t() const { return toInt(); }
@@ -341,7 +342,7 @@ public:
 	RLPStream& append(char const* _s) { return append(std::string(_s)); }
 	template  RLPStream& append(FixedHash _s, bool _compact = false, bool _allOrNothing = false) { return _allOrNothing && !_s ? append(bytesConstRef()) : append(_s.ref(), _compact); }
 
-	/// Appends an arbitrary RLP fragment - this *must* be a single item.
+	/// Appends an arbitrary RLP fragment - this *must* be a single item unless @a _itemCount is given.
 	RLPStream& append(RLP const& _rlp, unsigned _itemCount = 1) { return appendRaw(_rlp.data(), _itemCount); }
 
 	/// Appends a sequence of data to the stream as a list.
diff --git a/libdevcore/Worker.cpp b/libdevcore/Worker.cpp
index b2660305a..014780a66 100644
--- a/libdevcore/Worker.cpp
+++ b/libdevcore/Worker.cpp
@@ -41,7 +41,8 @@ void Worker::startWorking()
 		startedWorking();
 		while (!m_stop)
 		{
-			this_thread::sleep_for(chrono::milliseconds(30));
+			if (m_idleWaitMs)
+				this_thread::sleep_for(chrono::milliseconds(m_idleWaitMs));
 			doWork();
 		}
 		cdebug << "Finishing up worker thread";
diff --git a/libdevcore/Worker.h b/libdevcore/Worker.h
index a4a998dd7..f73a0f4aa 100644
--- a/libdevcore/Worker.h
+++ b/libdevcore/Worker.h
@@ -31,7 +31,7 @@ namespace dev
 class Worker
 {
 protected:
-	Worker(std::string const& _name = "anon"): m_name(_name) {}
+	Worker(std::string const& _name = "anon", unsigned _idleWaitMs = 30): m_name(_name), m_idleWaitMs(_idleWaitMs) {}
 
 	/// Move-constructor.
 	Worker(Worker&& _m) { std::swap(m_name, _m.m_name); }
@@ -41,20 +41,34 @@ protected:
 
 	virtual ~Worker() { stopWorking(); }
 
+	/// Allows changing worker name if work is stopped.
 	void setName(std::string _n) { if (!isWorking()) m_name = _n; }
 
+	/// Starts worker thread; causes startedWorking() to be called.
 	void startWorking();
+	
+	/// Stop worker thread; causes call to stopWorking().
 	void stopWorking();
+	
+	/// Returns if worker thread is present.
 	bool isWorking() const { Guard l(x_work); return !!m_work; }
+	
+	/// Called after thread is started from startWorking().
 	virtual void startedWorking() {}
+	
+	/// Called continuously following sleep for m_idleWaitMs.
 	virtual void doWork() = 0;
+	
+	/// Called when is to be stopped, just prior to thread being joined.
 	virtual void doneWorking() {}
 
 private:
+	std::string m_name;
+	unsigned m_idleWaitMs;
+	
 	mutable Mutex x_work;						///< Lock for the network existance.
 	std::unique_ptr m_work;		///< The network thread.
 	bool m_stop = false;
-	std::string m_name;
 };
 
 }
diff --git a/libdevcore/_libdevcore.cpp b/libdevcore/_libdevcore.cpp
deleted file mode 100644
index 0605791de..000000000
--- a/libdevcore/_libdevcore.cpp
+++ /dev/null
@@ -1,13 +0,0 @@
-#ifdef _MSC_VER
-#include "All.h"
-#include "Common.cpp"
-#include "CommonData.cpp"
-#include "CommonIO.cpp"
-#include "CommonJS.h"
-#include "FixedHash.cpp"
-#include "Guards.cpp"
-#include "Log.cpp"
-#include "RangeMask.cpp"
-#include "RLP.cpp"
-#include "Worker.cpp"
-#endif
diff --git a/libdevcore/vector_ref.h b/libdevcore/vector_ref.h
index be2fea13c..db46d62f6 100644
--- a/libdevcore/vector_ref.h
+++ b/libdevcore/vector_ref.h
@@ -40,6 +40,7 @@ public:
 	vector_ref<_T> cropped(size_t _begin, size_t _count = ~size_t(0)) const { if (m_data && _begin + std::max(size_t(0), _count) <= m_count) return vector_ref<_T>(m_data + _begin, _count == ~size_t(0) ? m_count - _begin : _count); else return vector_ref<_T>(); }
 	void retarget(_T const* _d, size_t _s) { m_data = _d; m_count = _s; }
 	void retarget(std::vector<_T> const& _t) { m_data = _t.data(); m_count = _t.size(); }
+	void copyTo(vector_ref::type> _t) const { memcpy(_t.data(), m_data, std::min(_t.size(), m_count) * sizeof(_T)); }
 
 	_T* begin() { return m_data; }
 	_T* end() { return m_data + m_count; }
diff --git a/libdevcrypto/SHA3MAC.cpp b/libdevcrypto/AES.cpp
similarity index 64%
rename from libdevcrypto/SHA3MAC.cpp
rename to libdevcrypto/AES.cpp
index 9498ef87b..56885ae36 100644
--- a/libdevcrypto/SHA3MAC.cpp
+++ b/libdevcrypto/AES.cpp
@@ -1,40 +1,60 @@
 /*
  This file is part of cpp-ethereum.
-
+ 
  cpp-ethereum is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.
-
+ 
  cpp-ethereum is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.
-
+ 
  You should have received a copy of the GNU General Public License
  along with cpp-ethereum.  If not, see .
  */
-/** @file SHA3MAC.cpp
+/** @file AES.cpp
  * @author Alex Leverington 
  * @date 2014
- *
- * SHA3 MAC
  */
 
 #include "CryptoPP.h"
-#include "SHA3MAC.h"
+#include "AES.h"
 
+using namespace std;
 using namespace dev;
 using namespace dev::crypto;
+using namespace dev::crypto::aes;
 using namespace CryptoPP;
 
-void crypto::sha3mac(bytesConstRef _secret, bytesConstRef _plain, bytesRef _output)
+struct aes::Aes128Ctr
+{
+	Aes128Ctr(h128 _k)
+	{
+		mode.SetKeyWithIV(_k.data(), sizeof(h128), Nonce::get().data());
+	}
+	CTR_Mode::Encryption mode;
+};
+
+Stream::Stream(StreamType, h128 _ckey):
+	m_cSecret(_ckey)
+{
+	cryptor = new Aes128Ctr(_ckey);
+}
+
+Stream::~Stream()
+{
+	delete cryptor;
+}
+
+void Stream::update(bytesRef)
+{
+
+}
+
+size_t Stream::streamOut(bytes&)
 {
-	CryptoPP::SHA3_256 ctx;
-	assert(_secret.size() > 0);
-	ctx.Update((byte*)_secret.data(), _secret.size());
-	ctx.Update((byte*)_plain.data(), _plain.size());
-	assert(_output.size() >= 32);
-	ctx.Final(_output.data());
+	return 0;
 }
 
diff --git a/libdevcrypto/AES.h b/libdevcrypto/AES.h
new file mode 100644
index 000000000..f0646eb85
--- /dev/null
+++ b/libdevcrypto/AES.h
@@ -0,0 +1,89 @@
+/*
+ This file is part of cpp-ethereum.
+ 
+ cpp-ethereum is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+ 
+ cpp-ethereum is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ GNU General Public License for more details.
+ 
+ You should have received a copy of the GNU General Public License
+ along with cpp-ethereum.  If not, see .
+ */
+/** @file AES.h
+ * @author Alex Leverington 
+ * @date 2014
+ *
+ * AES
+ * todo: use openssl
+ */
+
+#pragma once
+
+#include 
+#include "Common.h"
+
+namespace dev
+{
+namespace crypto
+{
+namespace aes
+{
+
+struct Aes128Ctr;
+enum StreamType { Encrypt, Decrypt };
+	
+/**
+ * @brief Encrypted stream
+ */
+class Stream
+{
+public:
+	// streamtype maybe irrelevant w/ctr
+	Stream(StreamType _t, h128 _ckey);
+	~Stream();
+	
+	virtual void update(bytesRef io_bytes);
+	
+	/// Move ciphertext to _bytes.
+	virtual size_t streamOut(bytes& o_bytes);
+	
+private:
+	Stream(Stream const&) = delete;
+	Stream& operator=(Stream const&) = delete;
+	
+	h128 m_cSecret;
+	bytes m_text;
+
+	Aes128Ctr* cryptor;
+};
+	
+
+/**
+ * @brief Encrypted stream with inband SHA3 mac at specific interval.
+ */
+class AuthenticatedStream: public Stream
+{
+public:
+	AuthenticatedStream(StreamType _t, h128 _ckey, h128 _mackey, unsigned _interval): Stream(_t, _ckey), m_macSecret(_mackey) { m_macInterval = _interval; }
+	
+	AuthenticatedStream(StreamType _t, Secret const& _s, unsigned _interval): Stream(_t, h128(_s)), m_macSecret(FixedHash<16>((byte const*)_s.data()+16,h128::ConstructFromPointer)) { m_macInterval = _interval; }
+	
+	/// Adjust mac interval. Next mac will be xored with value.
+	void adjustInterval(unsigned _interval) { m_macInterval = _interval; }
+	
+private:
+	AuthenticatedStream(AuthenticatedStream const&) = delete;
+	AuthenticatedStream& operator=(AuthenticatedStream const&) = delete;
+	
+	std::atomic m_macInterval;
+	h128 m_macSecret;
+};
+
+}
+}
+}
\ No newline at end of file
diff --git a/libdevcrypto/All.h b/libdevcrypto/All.h
deleted file mode 100644
index db6d7c615..000000000
--- a/libdevcrypto/All.h
+++ /dev/null
@@ -1,12 +0,0 @@
-#pragma once
-
-#include "Common.h"
-#include "CryptoPP.h"
-#include "EC.h"
-#include "FileSystem.h"
-#include "MemoryDB.h"
-#include "OverlayDB.h"
-#include "SHA3.h"
-#include "SHA3MAC.h"
-#include "TrieCommon.h"
-#include "TrieDB.h"
diff --git a/libdevcrypto/CMakeLists.txt b/libdevcrypto/CMakeLists.txt
index cee7d130d..20eab916a 100644
--- a/libdevcrypto/CMakeLists.txt
+++ b/libdevcrypto/CMakeLists.txt
@@ -1,7 +1,19 @@
 cmake_policy(SET CMP0015 NEW)
+# this policy was introduced in cmake 3.0
+# remove if, once 3.0 will be used on unix
+if (${CMAKE_MAJOR_VERSION} GREATER 2)
+	# old policy do not use MACOSX_RPATH
+	cmake_policy(SET CMP0042 OLD)
+endif()
+set(CMAKE_AUTOMOC OFF)
 
 aux_source_directory(. SRC_LIST)
 
+include_directories(${Boost_INCLUDE_DIRS})
+include_directories(${CRYPTOPP_INCLUDE_DIRS})
+include_directories(${LEVELDB_INCLUDE_DIRS})
+include_directories(..) 
+
 set(EXECUTABLE devcrypto)
 
 file(GLOB HEADERS "*.h")
@@ -11,43 +23,10 @@ else()
 	add_library(${EXECUTABLE} SHARED ${SRC_LIST} ${HEADERS})
 endif()
 
-include_directories(..)
-
+target_link_libraries(${EXECUTABLE} ${Boost_FILESYSTEM_LIBRARY_RELEASE})
+target_link_libraries(${EXECUTABLE} ${LEVELDB_LIBRARIES})
+target_link_libraries(${EXECUTABLE} ${CRYPTOPP_LIBRARIES})
 target_link_libraries(${EXECUTABLE} devcore)
-target_link_libraries(${EXECUTABLE} secp256k1)
-target_link_libraries(${EXECUTABLE} gmp)
-target_link_libraries(${EXECUTABLE} ${LEVELDB_LS})
-target_link_libraries(${EXECUTABLE} ${CRYPTOPP_LS})
-
-if("${TARGET_PLATFORM}" STREQUAL "w64")
-	target_link_libraries(${EXECUTABLE} boost_system-mt-s)
-	target_link_libraries(${EXECUTABLE} boost_filesystem-mt-s)
-	target_link_libraries(${EXECUTABLE} boost_thread_win32-mt-s)
-	target_link_libraries(${EXECUTABLE} iphlpapi)
-	target_link_libraries(${EXECUTABLE} ws2_32)
-	target_link_libraries(${EXECUTABLE} mswsock)
-	target_link_libraries(${EXECUTABLE} shlwapi)
-elseif (APPLE)
-	# Latest mavericks boost libraries only come with -mt
-	target_link_libraries(${EXECUTABLE} boost_system-mt)
-	target_link_libraries(${EXECUTABLE} boost_filesystem-mt)
-	target_link_libraries(${EXECUTABLE} boost_thread-mt)
-	find_package(Threads REQUIRED)
-	target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT})
-elseif (UNIX)
-	find_package(Boost 1.53 REQUIRED COMPONENTS filesystem)
-	target_link_libraries(${EXECUTABLE} ${Boost_SYSTEM_LIBRARY})
-	target_link_libraries(${EXECUTABLE} ${Boost_FILESYSTEM_LIBRARY})
-	target_link_libraries(${EXECUTABLE} ${Boost_THREAD_LIBRARY})
-	target_link_libraries(${EXECUTABLE} ${Boost_DATE_TIME_LIBRARY})
-	target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT})
-else ()
-	target_link_libraries(${EXECUTABLE} boost_system)
-	target_link_libraries(${EXECUTABLE} boost_filesystem)
-	target_link_libraries(${EXECUTABLE} boost_thread)
-	find_package(Threads REQUIRED)
-	target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT})
-endif ()
 
 install( TARGETS ${EXECUTABLE} ARCHIVE DESTINATION lib LIBRARY DESTINATION lib )
 install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} )
diff --git a/libdevcrypto/Common.cpp b/libdevcrypto/Common.cpp
index 2db65aae3..f4803bd52 100644
--- a/libdevcrypto/Common.cpp
+++ b/libdevcrypto/Common.cpp
@@ -23,89 +23,113 @@
 #include 
 #include 
 #include 
-#include "EC.h"
 #include "SHA3.h"
 #include "FileSystem.h"
+#include "CryptoPP.h"
 #include "Common.h"
 using namespace std;
 using namespace dev;
-using namespace crypto;
+using namespace dev::crypto;
 
-//#define ETH_ADDRESS_DEBUG 1
+static Secp256k1 s_secp256k1;
 
-Address dev::toAddress(Secret _secret)
+bool dev::SignatureStruct::isValid()
 {
-	return KeyPair(_secret).address();
+	if (this->v > 1 ||
+			this->r >= h256("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141") ||
+			this->s >= h256("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"))
+		return false;
+	return true;
 }
 
-KeyPair KeyPair::create()
+Public dev::toPublic(Secret const& _secret)
 {
-	static mt19937_64 s_eng(time(0) + chrono::high_resolution_clock::now().time_since_epoch().count());
-	uniform_int_distribution d(0, 255);
-
-	for (int i = 0; i < 100; ++i)
-	{
-		h256 sec;
-		for (unsigned i = 0; i < 32; ++i)
-			sec[i] = (byte)d(s_eng);
-
-		KeyPair ret(sec);
-		if (ret.address())
-			return ret;
-	}
-	return KeyPair();
+	Public p;
+	s_secp256k1.toPublic(_secret, p);
+	return std::move(p);
 }
 
-KeyPair::KeyPair(h256 _sec):
-	m_secret(_sec)
+Address dev::toAddress(Public const& _public)
 {
-	toPublic(m_secret, m_public);
-	if (verifySecret(m_secret, m_public))
-		m_address = right160(dev::sha3(m_public.ref()));
-	
-#if ETH_ADDRESS_DEBUG
-	cout << "---- ADDRESS -------------------------------" << endl;
-	cout << "SEC: " << m_secret << endl;
-	cout << "PUB: " << m_public << endl;
-	cout << "ADR: " << m_address << endl;
-#endif
+	return s_secp256k1.toAddress(_public);
 }
 
-KeyPair KeyPair::fromEncryptedSeed(bytesConstRef _seed, std::string const& _password)
+Address dev::toAddress(Secret const& _secret)
 {
-	return KeyPair(sha3(aesDecrypt(_seed, _password)));
+	Public p;
+	s_secp256k1.toPublic(_secret, p);
+	return s_secp256k1.toAddress(p);
 }
 
-void dev::encrypt(Public _k, bytesConstRef _plain, bytes& o_cipher)
+void dev::encrypt(Public const& _k, bytesConstRef _plain, bytes& o_cipher)
 {
 	bytes io = _plain.toBytes();
-	crypto::encrypt(_k, io);
+	s_secp256k1.encrypt(_k, io);
 	o_cipher = std::move(io);
 }
 
-bool dev::decrypt(Secret _k, bytesConstRef _cipher, bytes& o_plaintext)
+bool dev::decrypt(Secret const& _k, bytesConstRef _cipher, bytes& o_plaintext)
 {
 	bytes io = _cipher.toBytes();
-	crypto::decrypt(_k, io);
+	s_secp256k1.decrypt(_k, io);
 	if (io.empty())
 		return false;
 	o_plaintext = std::move(io);
 	return true;
 }
 
-Public dev::recover(Signature _sig, h256 _message)
+Public dev::recover(Signature const& _sig, h256 const& _message)
 {
-	return crypto::recover(_sig, _message.ref());
+	return s_secp256k1.recover(_sig, _message.ref());
 }
 
-Signature dev::sign(Secret _k, h256 _hash)
+Signature dev::sign(Secret const& _k, h256 const& _hash)
 {
-	return crypto::sign(_k, _hash);
+	return s_secp256k1.sign(_k, _hash);
 }
 
-bool dev::verify(Public _p, Signature _s, h256 _hash)
+bool dev::verify(Public const& _p, Signature const& _s, h256 const& _hash)
 {
-	return crypto::verify(_p, _s, bytesConstRef(_hash.data(), 32), true);
+	return s_secp256k1.verify(_p, _s, _hash.ref(), true);
+}
+
+KeyPair KeyPair::create()
+{
+	static mt19937_64 s_eng(time(0) + chrono::high_resolution_clock::now().time_since_epoch().count());
+	uniform_int_distribution d(0, 255);
+
+	for (int i = 0; i < 100; ++i)
+	{
+		KeyPair ret(FixedHash<32>::random(s_eng));
+		if (ret.address())
+			return ret;
+	}
+	return KeyPair();
+}
+
+KeyPair::KeyPair(h256 _sec):
+	m_secret(_sec)
+{
+	if (s_secp256k1.verifySecret(m_secret, m_public))
+		m_address = s_secp256k1.toAddress(m_public);
+}
+
+KeyPair KeyPair::fromEncryptedSeed(bytesConstRef _seed, std::string const& _password)
+{
+	return KeyPair(sha3(aesDecrypt(_seed, _password)));
+}
+
+h256 crypto::kdf(Secret const& _priv, h256 const& _hash)
+{
+	// H(H(r||k)^h)
+	h256 s;
+	sha3mac(Nonce::get().ref(), _priv.ref(), s.ref());
+	s ^= _hash;
+	sha3(s.ref(), s.ref());
+	
+	if (!s || !_hash || !_priv)
+		BOOST_THROW_EXCEPTION(InvalidState());
+	return std::move(s);
 }
 
 h256 Nonce::get(bool _commit)
@@ -125,7 +149,7 @@ h256 Nonce::get(bool _commit)
 		else
 		{
 			// todo: replace w/entropy from user and system
-			std::mt19937_64 s_eng(time(0));
+			std::mt19937_64 s_eng(time(0) + chrono::high_resolution_clock::now().time_since_epoch().count());
 			std::uniform_int_distribution d(0, 255);
 			for (unsigned i = 0; i < 32; ++i)
 				s_seed[i] = (byte)d(s_eng);
diff --git a/libdevcrypto/Common.h b/libdevcrypto/Common.h
index e95eefa40..02d52f495 100644
--- a/libdevcrypto/Common.h
+++ b/libdevcrypto/Common.h
@@ -43,7 +43,20 @@ using Public = h512;
 /// @NOTE This is not endian-specific; it's just a bunch of bytes.
 using Signature = h520;
 
-struct SignatureStruct { h256 r; h256 s; byte v; };
+struct SignatureStruct
+{
+	SignatureStruct() {}
+	SignatureStruct(Signature const& _s) { *(h520*)this = _s; }
+	SignatureStruct(h256 _r, h256 _s, byte _v): r(_r), s(_s), v(_v) {}
+	operator Signature() const { return *(h520 const*)this; }
+
+	/// @returns true if r,s,v values are valid, otherwise false
+	bool isValid();
+
+	h256 r;
+	h256 s;
+	byte v;
+};
 
 /// An Ethereum address: 20 bytes.
 /// @NOTE This is not endian-specific; it's just a bunch of bytes.
@@ -52,30 +65,36 @@ using Address = h160;
 /// A vector of Ethereum addresses.
 using Addresses = h160s;
 
-/// A vector of Ethereum addresses.
+/// A set of Ethereum addresses.
 using AddressSet = std::set;
 
 /// A vector of secrets.
 using Secrets = h256s;
 
 /// Convert a secret key into the public key equivalent.
+Public toPublic(Secret const& _secret);
+
+/// Convert a public key to address.
+Address toAddress(Public const& _public);
+
+/// Convert a secret key into address of public key equivalent.
 /// @returns 0 if it's not a valid secret key.
-Address toAddress(Secret _secret);
+Address toAddress(Secret const& _secret);
 
 /// Encrypts plain text using Public key.
-void encrypt(Public _k, bytesConstRef _plain, bytes& o_cipher);
+void encrypt(Public const& _k, bytesConstRef _plain, bytes& o_cipher);
 
 /// Decrypts cipher using Secret key.
-bool decrypt(Secret _k, bytesConstRef _cipher, bytes& o_plaintext);
+bool decrypt(Secret const& _k, bytesConstRef _cipher, bytes& o_plaintext);
 	
 /// Recovers Public key from signed message hash.
-Public recover(Signature _sig, h256 _hash);
+Public recover(Signature const& _sig, h256 const& _hash);
 	
 /// Returns siganture of message hash.
-Signature sign(Secret _k, h256 _hash);
+Signature sign(Secret const& _k, h256 const& _hash);
 	
 /// Verify signature.
-bool verify(Public _k, Signature _s, h256 _hash);
+bool verify(Public const& _k, Signature const& _s, h256 const& _hash);
 
 /// Simple class that represents a "key pair".
 /// All of the data of the class can be regenerated from the secret key (m_secret) alone.
@@ -119,6 +138,9 @@ namespace crypto
 {
 struct InvalidState: public dev::Exception {};
 
+/// Key derivation
+h256 kdf(Secret const& _priv, h256 const& _hash);
+	
 /**
  * @brief Generator for nonce material
  */
diff --git a/libdevcrypto/CryptoPP.cpp b/libdevcrypto/CryptoPP.cpp
index 1b51d5bd5..766ca485d 100644
--- a/libdevcrypto/CryptoPP.cpp
+++ b/libdevcrypto/CryptoPP.cpp
@@ -21,25 +21,212 @@
 
 #include "CryptoPP.h"
 
+using namespace std;
 using namespace dev;
 using namespace dev::crypto;
 using namespace CryptoPP;
 
+static_assert(dev::Secret::size == 32, "Secret key must be 32 bytes.");
+static_assert(dev::Public::size == 64, "Public key must be 64 bytes.");
+static_assert(dev::Signature::size == 65, "Signature must be 65 bytes.");
 
-/// Integer and Point Conversion:
+void Secp256k1::encrypt(Public const& _k, bytes& io_cipher)
+{
+	ECIES::Encryptor e;
+	initializeDLScheme(_k, e);
+
+	size_t plen = io_cipher.size();
+	bytes ciphertext;
+	ciphertext.resize(e.CiphertextLength(plen));
+	
+	{
+		lock_guard l(x_rng);
+		e.Encrypt(m_rng, io_cipher.data(), plen, ciphertext.data());
+	}
+	
+	memset(io_cipher.data(), 0, io_cipher.size());
+	io_cipher = std::move(ciphertext);
+}
+
+void Secp256k1::decrypt(Secret const& _k, bytes& io_text)
+{
+	CryptoPP::ECIES::Decryptor d;
+	initializeDLScheme(_k, d);
+
+	if (!io_text.size())
+	{
+		io_text.resize(1);
+		io_text[0] = 0;
+	}
+	
+	size_t clen = io_text.size();
+	bytes plain;
+	plain.resize(d.MaxPlaintextLength(io_text.size()));
+	
+	DecodingResult r;
+	{
+		lock_guard l(x_rng);
+		r = d.Decrypt(m_rng, io_text.data(), clen, plain.data());
+	}
+	
+	if (!r.isValidCoding)
+	{
+		io_text.clear();
+		return;
+	}
+	
+	io_text.resize(r.messageLength);
+	io_text = std::move(plain);
+}
+
+Signature Secp256k1::sign(Secret const& _k, bytesConstRef _message)
+{
+	return sign(_k, sha3(_message));
+}
+
+Signature Secp256k1::sign(Secret const& _key, h256 const& _hash)
+{
+	// assumption made by signing alogrithm
+	asserts(m_q == m_qs);
+	
+	Signature sig;
+	
+	Integer k(kdf(_key, _hash).data(), 32);
+	if (k == 0)
+		BOOST_THROW_EXCEPTION(InvalidState());
+	k = 1 + (k % (m_qs - 1));
+	
+	ECP::Point rp;
+	Integer r;
+	{
+		lock_guard l(x_params);
+		rp = m_params.ExponentiateBase(k);
+		r = m_params.ConvertElementToInteger(rp);
+	}
+	sig[64] = 0;
+//	sig[64] = (r >= m_q) ? 2 : 0;
+	
+	Integer kInv = k.InverseMod(m_q);
+	Integer z(_hash.asBytes().data(), 32);
+	Integer s = (kInv * (Integer(_key.asBytes().data(), 32)*r + z)) % m_q;
+	if (r == 0 || s == 0)
+		BOOST_THROW_EXCEPTION(InvalidState());
+	
+//	if (s > m_qs)
+//	{
+//		s = m_q - s;
+//		if (sig[64])
+//			sig[64] ^= 1;
+//	}
+	
+	sig[64] |= rp.y.IsOdd() ? 1 : 0;
+	r.Encode(sig.data(), 32);
+	s.Encode(sig.data() + 32, 32);
+	return sig;
+}
+
+bool Secp256k1::verify(Signature const& _signature, bytesConstRef _message)
+{
+	return !!recover(_signature, _message);
+}
 
-void pp::exportPublicKey(CryptoPP::DL_PublicKey_EC const& _k, Public& _p)
+bool Secp256k1::verify(Public const& _p, Signature const& _sig, bytesConstRef _message, bool _hashed)
+{
+	// todo: verify w/o recovery (if faster)
+	return _p == _hashed ? recover(_sig, _message) : recover(_sig, sha3(_message).ref());
+}
+
+Public Secp256k1::recover(Signature _signature, bytesConstRef _message)
+{
+	Public recovered;
+	
+	Integer r(_signature.data(), 32);
+	Integer s(_signature.data()+32, 32);
+	// cryptopp encodes sign of y as 0x02/0x03 instead of 0/1 or 27/28
+	byte encodedpoint[33];
+	encodedpoint[0] = _signature[64]|2;
+	memcpy(&encodedpoint[1], _signature.data(), 32);
+	
+	ECP::Element x;
+	{
+		lock_guard l(x_curve);
+		m_curve.DecodePoint(x, encodedpoint, 33);
+		if (!m_curve.VerifyPoint(x))
+			return recovered;
+	}
+	
+//	if (_signature[64] & 2)
+//	{
+//		r += m_q;
+//		lock_guard l(x_params);
+//		if (r >= m_params.GetMaxExponent())
+//			return recovered;
+//	}
+	
+	Integer z(_message.data(), 32);
+	Integer rn = r.InverseMod(m_q);
+	Integer u1 = m_q - (rn.Times(z)).Modulo(m_q);
+	Integer u2 = (rn.Times(s)).Modulo(m_q);
+	
+	ECP::Point p;
+	byte recoveredbytes[65];
+	{
+		lock_guard l(x_curve);
+		// todo: make generator member
+		p = m_curve.CascadeMultiply(u2, x, u1, m_params.GetSubgroupGenerator());
+		m_curve.EncodePoint(recoveredbytes, p, false);
+	}
+	memcpy(recovered.data(), &recoveredbytes[1], 64);
+	return recovered;
+}
+
+bool Secp256k1::verifySecret(Secret const& _s, Public& _p)
+{
+	DL_PrivateKey_EC k;
+	k.Initialize(m_params, secretToExponent(_s));
+	if (!k.Validate(m_rng, 3))
+		return false;
+	
+	DL_PublicKey_EC pub;
+	k.MakePublicKey(pub);
+	if (!k.Validate(m_rng, 3))
+		return false;
+
+	exportPublicKey(pub, _p);
+	return true;
+}
+
+void Secp256k1::agree(Secret const& _s, Public const& _r, h256& o_s)
+{
+	ECDH::Domain d(m_oid);
+	assert(d.AgreedValueLength() == sizeof(o_s));
+	byte remote[65] = {0x04};
+	memcpy(&remote[1], _r.data(), 64);
+	assert(d.Agree(o_s.data(), _s.data(), remote));
+}
+
+void Secp256k1::exportPublicKey(CryptoPP::DL_PublicKey_EC const& _k, Public& o_p)
 {
 	bytes prefixedKey(_k.GetGroupParameters().GetEncodedElementSize(true));
-	secp256k1Params.GetCurve().EncodePoint(prefixedKey.data(), _k.GetPublicElement(), false);
+	
+	{
+		lock_guard l(x_params);
+		m_params.GetCurve().EncodePoint(prefixedKey.data(), _k.GetPublicElement(), false);
+		assert(Public::size + 1 == _k.GetGroupParameters().GetEncodedElementSize(true));
+	}
 
-	assert(Public::size + 1 == _k.GetGroupParameters().GetEncodedElementSize(true));
-	memcpy(_p.data(), &prefixedKey[1], Public::size);
+	memcpy(o_p.data(), &prefixedKey[1], Public::size);
 }
 
-void pp::exponentToPublic(Integer const& _e, Public& _p)
+void Secp256k1::exponentToPublic(Integer const& _e, Public& o_p)
 {
 	CryptoPP::DL_PublicKey_EC pk;
-	pk.Initialize(secp256k1Params, secp256k1Params.ExponentiateBase(_e));
-	pp::exportPublicKey(pk, _p);
-}
\ No newline at end of file
+	
+	{
+		lock_guard l(x_params);
+		pk.Initialize(m_params, m_params.ExponentiateBase(_e));
+	}
+	
+	exportPublicKey(pk, o_p);
+}
+
diff --git a/libdevcrypto/CryptoPP.h b/libdevcrypto/CryptoPP.h
index dc5d6a610..7ec95c552 100644
--- a/libdevcrypto/CryptoPP.h
+++ b/libdevcrypto/CryptoPP.h
@@ -23,6 +23,7 @@
 
 #pragma once
 
+#include 
 // need to leave this one disabled for link-time. blame cryptopp.
 #pragma GCC diagnostic ignored "-Wunused-function"
 #pragma warning(push)
@@ -33,57 +34,100 @@
 #pragma GCC diagnostic ignored "-Wunused-variable"
 #pragma GCC diagnostic ignored "-Wdelete-non-virtual-dtor"
 #pragma GCC diagnostic ignored "-Wextra"
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
 #pragma warning(pop)
 #pragma GCC diagnostic pop
+#include "SHA3.h"
 #include "Common.h"
 
 namespace dev
 {
 namespace crypto
 {
-namespace pp
-{
-	
+
 using namespace CryptoPP;
+
+inline ECP::Point publicToPoint(Public const& _p) { Integer x(_p.data(), 32); Integer y(_p.data() + 32, 32); return std::move(ECP::Point(x,y)); }
+
+inline Integer secretToExponent(Secret const& _s) { return std::move(Integer(_s.data(), Secret::size)); }
+	
+/**
+ * CryptoPP secp256k1 algorithms.
+ */
+class Secp256k1
+{	
+public:
+	Secp256k1(): m_oid(ASN1::secp256k1()), m_params(m_oid), m_curve(m_params.GetCurve()), m_q(m_params.GetGroupOrder()), m_qs(m_params.GetSubgroupOrder()) {}
 	
-/// CryptoPP random number pool
-static CryptoPP::AutoSeededRandomPool PRNG;
+	Address toAddress(Public const& _p) { return right160(sha3(_p.ref())); }
 	
-/// CryptoPP EC Cruve
-static const CryptoPP::OID secp256k1Curve = CryptoPP::ASN1::secp256k1();
+	void toPublic(Secret const& _s, Public& o_public) { exponentToPublic(Integer(_s.data(), sizeof(_s)), o_public); }
 	
-static const CryptoPP::DL_GroupParameters_EC secp256k1Params(secp256k1Curve);
+	/// Encrypts text (replace input).
+	void encrypt(Public const& _k, bytes& io_cipher);
 	
-static ECP::Point publicToPoint(Public const& _p) { Integer x(_p.data(), 32); Integer y(_p.data() + 32, 32); return std::move(ECP::Point(x,y)); }
+	/// Decrypts text (replace input).
+	void decrypt(Secret const& _k, bytes& io_text);
 	
-static Integer secretToExponent(Secret const& _s) { return std::move(Integer(_s.data(), Secret::size)); }
-
-void exportPublicKey(CryptoPP::DL_PublicKey_EC const& _k, Public& _p);
-
-static void exportPrivateKey(CryptoPP::DL_PrivateKey_EC const& _k, Secret& _s) { _k.GetPrivateExponent().Encode(_s.data(), Secret::size); }
+	/// @returns siganture of message.
+	Signature sign(Secret const& _k, bytesConstRef _message);
+	
+	/// @returns compact siganture of provided hash.
+	Signature sign(Secret const& _k, h256 const& _hash);
+	
+	/// Verify compact signature (public key is extracted from signature).
+	bool verify(Signature const& _signature, bytesConstRef _message);
+	
+	/// Verify signature.
+	bool verify(Public const& _p, Signature const& _sig, bytesConstRef _message, bool _hashed = false);
 	
-void exponentToPublic(Integer const& _e, Public& _p);
+	/// Recovers public key from compact signature. Uses libsecp256k1.
+	Public recover(Signature _signature, bytesConstRef _message);
 	
-template 
-void initializeDLScheme(Secret const& _s, T& io_operator) { io_operator.AccessKey().Initialize(pp::secp256k1Params, secretToExponent(_s)); }
+	/// Verifies _s is a valid secret key and returns corresponding public key in o_p.
+	bool verifySecret(Secret const& _s, Public& o_p);
 	
-template 
-void initializeDLScheme(Public const& _p, T& io_operator) { io_operator.AccessKey().Initialize(pp::secp256k1Params, publicToPoint(_p)); }
+	void agree(Secret const& _s, Public const& _r, h256& o_s);
+	
+protected:
+	void exportPrivateKey(DL_PrivateKey_EC const& _k, Secret& o_s) { _k.GetPrivateExponent().Encode(o_s.data(), Secret::size); }
+	
+	void exportPublicKey(DL_PublicKey_EC const& _k, Public& o_p);
+	
+	void exponentToPublic(Integer const& _e, Public& o_p);
+	
+	template  void initializeDLScheme(Secret const& _s, T& io_operator) { std::lock_guard l(x_params); io_operator.AccessKey().Initialize(m_params, secretToExponent(_s)); }
+	
+	template  void initializeDLScheme(Public const& _p, T& io_operator) { std::lock_guard l(x_params); io_operator.AccessKey().Initialize(m_params, publicToPoint(_p)); }
+	
+private:
+	OID m_oid;
+	
+	std::mutex x_rng;
+	AutoSeededRandomPool m_rng;
+	
+	std::mutex x_params;
+	DL_GroupParameters_EC m_params;
+	
+	std::mutex x_curve;
+	DL_GroupParameters_EC::EllipticCurve m_curve;
+	
+	Integer m_q;
+	Integer m_qs;
+};
 
 }
 }
-}
 
diff --git a/libdevcrypto/EC.cpp b/libdevcrypto/EC.cpp
deleted file mode 100644
index af6d0e65e..000000000
--- a/libdevcrypto/EC.cpp
+++ /dev/null
@@ -1,199 +0,0 @@
-/*
- This file is part of cpp-ethereum.
-
- cpp-ethereum is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- cpp-ethereum is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with cpp-ethereum.  If not, see .
- */
-/** @file EC.cpp
- * @author Alex Leverington 
- * @date 2014
- *
- * ECDSA, ECIES
- */
-
-#include 
-#include "CryptoPP.h"
-#include "SHA3.h"
-#include "SHA3MAC.h"
-#include "EC.h"
-
-static_assert(dev::Secret::size == 32, "Secret key must be 32 bytes.");
-static_assert(dev::Public::size == 64, "Public key must be 64 bytes.");
-static_assert(dev::Signature::size == 65, "Signature must be 65 bytes.");
-
-using namespace std;
-using namespace dev;
-using namespace dev::crypto;
-using namespace CryptoPP;
-using namespace pp;
-
-void crypto::toPublic(Secret const& _s, Public& o_public)
-{
-	exponentToPublic(Integer(_s.data(), sizeof(_s)), o_public);
-}
-
-h256 crypto::kdf(Secret const& _priv, h256 const& _hash)
-{
-	// H(H(r||k)^h)
-	h256 s;
-	sha3mac(Nonce::get().ref(), _priv.ref(), s.ref());
-	s ^= _hash;
-	sha3(s.ref(), s.ref());
-	
-	if (!s || !_hash || !_priv)
-		BOOST_THROW_EXCEPTION(InvalidState());
-	return std::move(s);
-}
-
-void crypto::encrypt(Public const& _k, bytes& io_cipher)
-{
-	ECIES::Encryptor e;
-	initializeDLScheme(_k, e);
-	size_t plen = io_cipher.size();
-	bytes c;
-	c.resize(e.CiphertextLength(plen));
-	// todo: use StringSource with io_cipher as input and output.
-	e.Encrypt(PRNG, io_cipher.data(), plen, c.data());
-	memset(io_cipher.data(), 0, io_cipher.size());
-	io_cipher = std::move(c);
-}
-
-void crypto::decrypt(Secret const& _k, bytes& io_text)
-{
-	CryptoPP::ECIES::Decryptor d;
-	initializeDLScheme(_k, d);
-	size_t clen = io_text.size();
-	bytes p;
-	p.resize(d.MaxPlaintextLength(io_text.size()));
-	// todo: use StringSource with io_text as input and output.
-	DecodingResult r = d.Decrypt(PRNG, io_text.data(), clen, p.data());
-	if (!r.isValidCoding)
-	{
-		io_text.clear();
-		return;
-	}
-	io_text.resize(r.messageLength);
-	io_text = std::move(p);
-}
-
-Signature crypto::sign(Secret const& _k, bytesConstRef _message)
-{
-	return crypto::sign(_k, sha3(_message));
-}
-
-Signature crypto::sign(Secret const& _key, h256 const& _hash)
-{
-	ECDSA::Signer signer;
-	initializeDLScheme(_key, signer);
-
-	Integer const& q = secp256k1Params.GetGroupOrder();
-	Integer const& qs = secp256k1Params.GetSubgroupOrder();
-	Integer e(_hash.asBytes().data(), 32);
-
-	Integer k(kdf(_key, _hash).data(), 32);
-	if (k == 0)
-		BOOST_THROW_EXCEPTION(InvalidState());
-	k = 1 + (k % (qs - 1));
-	
-	ECP::Point rp = secp256k1Params.ExponentiateBase(k);
-	Integer r = secp256k1Params.ConvertElementToInteger(rp);
-	int recid = ((r >= q) ? 2 : 0) | (rp.y.IsOdd() ? 1 : 0);
-	
-	Integer kInv = k.InverseMod(q);
-	Integer s = (kInv * (Integer(_key.asBytes().data(), 32)*r + e)) % q;
-	assert(!!r && !!s);
-	
-	if (s > qs)
-	{
-		s = q - s;
-		if (recid)
-			recid ^= 1;
-	}
-	
-	Signature sig;
-	r.Encode(sig.data(), 32);
-	s.Encode(sig.data() + 32, 32);
-	sig[64] = recid;
-	return sig;
-}
-
-bool crypto::verify(Signature const& _signature, bytesConstRef _message)
-{
-	return crypto::verify(crypto::recover(_signature, _message), _signature, _message);
-}
-
-bool crypto::verify(Public const& _p, Signature const& _sig, bytesConstRef _message, bool _hashed)
-{
-	static size_t derMaxEncodingLength = 72;
-	if (_hashed)
-	{
-		assert(_message.size() == 32);
-		byte encpub[65] = {0x04};
-		memcpy(&encpub[1], _p.data(), 64);
-		byte dersig[derMaxEncodingLength];
-		size_t cssz = DSAConvertSignatureFormat(dersig, derMaxEncodingLength, DSA_DER, _sig.data(), 64, DSA_P1363);
-		assert(cssz <= derMaxEncodingLength);
-		return (1 == secp256k1_ecdsa_verify(_message.data(), _message.size(), dersig, cssz, encpub, 65));
-	}
-	
-	ECDSA::Verifier verifier;
-	initializeDLScheme(_p, verifier);
-	return verifier.VerifyMessage(_message.data(), _message.size(), _sig.data(), sizeof(Signature) - 1);
-}
-
-Public crypto::recover(Signature _signature, bytesConstRef _message)
-{
-	secp256k1_start();
-	
-	int pubkeylen = 65;
-	byte pubkey[pubkeylen];
-	if (!secp256k1_ecdsa_recover_compact(_message.data(), 32, _signature.data(), pubkey, &pubkeylen, 0, (int)_signature[64]))
-		return Public();
-	
-#if ETH_CRYPTO_TRACE
-	h256* sig = (h256 const*)_signature.data();
-	cout << "---- RECOVER -------------------------------" << endl;
-	cout << "MSG: " << _message << endl;
-	cout << "R S V: " << sig[0] << " " << sig[1] << " " << (int)(_signature[64] - 27) << "+27" << endl;
-	cout << "PUB: " << toHex(bytesConstRef(&(pubkey[1]), 64)) << endl;
-#endif
-	
-	Public ret;
-	memcpy(&ret, &(pubkey[1]), sizeof(Public));
-	return ret;
-}
-
-bool crypto::verifySecret(Secret const& _s, Public const& _p)
-{
-	secp256k1_start();
-	int ok = secp256k1_ecdsa_seckey_verify(_s.data());
-	if (!ok)
-		return false;
-	
-	int pubkeylen = 65;
-	byte pubkey[pubkeylen];
-	ok = secp256k1_ecdsa_pubkey_create(pubkey, &pubkeylen, _s.data(), 0);
-	if (!ok || pubkeylen != 65)
-		return false;
-	
-	ok = secp256k1_ecdsa_pubkey_verify(pubkey, 65);
-	if (!ok)
-		return false;
-	
-	for (int i = 0; i < 32; i++)
-		if (pubkey[i+1]!=_p[i])
-			return false;
-
-	return true;
-}
-
diff --git a/libdevcrypto/EC.h b/libdevcrypto/EC.h
deleted file mode 100644
index 2a4155edf..000000000
--- a/libdevcrypto/EC.h
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- This file is part of cpp-ethereum.
-
- cpp-ethereum is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- cpp-ethereum is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with cpp-ethereum.  If not, see .
- */
-/** @file EC.h
- * @author Alex Leverington 
- * @date 2014
- *
- * ECDSA, ECIES
- */
-
-#pragma once
-
-#include "Common.h"
-
-namespace dev
-{
-namespace crypto
-{
-
-void toPublic(Secret const& _s, Public& o_public);
-h256 kdf(Secret const& _priv, h256 const& _hash);
-	
-/// Encrypts text (in place).
-void encrypt(Public const& _k, bytes& io_cipher);
-
-/// Decrypts text (in place).
-void decrypt(Secret const& _k, bytes& io_text);
-
-/// Returns siganture of message.
-Signature sign(Secret const& _k, bytesConstRef _message);
-	
-/// Returns compact siganture of message hash.
-Signature sign(Secret const& _k, h256 const& _hash);
-
-/// Verify compact signature (public key is extracted from message).
-bool verify(Signature const& _signature, bytesConstRef _message);
-	
-/// Verify signature.
-bool verify(Public const& _p, Signature const& _sig, bytesConstRef _message, bool _hashed = false);
-
-/// Recovers public key from compact signature. Uses libsecp256k1.
-Public recover(Signature _signature, bytesConstRef _message);
-
-bool verifySecret(Secret const& _s, Public const& _p);
-	
-}
-	
-}
-
diff --git a/libdevcrypto/ECDHE.cpp b/libdevcrypto/ECDHE.cpp
new file mode 100644
index 000000000..deae3bc6d
--- /dev/null
+++ b/libdevcrypto/ECDHE.cpp
@@ -0,0 +1,100 @@
+/*
+ This file is part of cpp-ethereum.
+ 
+ cpp-ethereum is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+ 
+ cpp-ethereum is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ GNU General Public License for more details.
+ 
+ You should have received a copy of the GNU General Public License
+ along with cpp-ethereum.  If not, see .
+ */
+/** @file ECDHE.cpp
+ * @author Alex Leverington 
+ * @date 2014
+ */
+
+#include "SHA3.h"
+#include "CryptoPP.h"
+#include "ECDHE.h"
+
+using namespace std;
+using namespace dev;
+using namespace dev::crypto;
+
+static Secp256k1 s_secp256k1;
+
+void ECDHE::agree(Public const& _remote, Secret& o_sharedSecret)
+{
+	if (m_remoteEphemeral)
+		// agreement can only occur once
+		BOOST_THROW_EXCEPTION(InvalidState());
+	
+	m_remoteEphemeral = _remote;
+	s_secp256k1.agree(m_ephemeral.sec(), m_remoteEphemeral, o_sharedSecret);
+}
+
+void ECDHEKeyExchange::agree(Public const& _remoteEphemeral)
+{
+	s_secp256k1.agree(m_ephemeral.sec(), _remoteEphemeral, m_ephemeralSecret);
+}
+
+void ECDHEKeyExchange::exchange(bytes& o_exchange)
+{
+	if (!m_ephemeralSecret)
+		// didn't agree on public remote
+		BOOST_THROW_EXCEPTION(InvalidState());
+
+	// The key exchange payload is in two parts and is encrypted
+	// using ephemeral keypair.
+	//
+	// The first part is the 'prefix' which is a zero-knowledge proof
+	// allowing the remote to resume or emplace a previous session.
+	// If a session previously exists:
+	//	prefix is sha3(token) // todo: ephemeral entropy from both sides
+	// If a session doesn't exist:
+	//	prefix is sha3(m_ephemeralSecret)
+	//
+	// The second part is encrypted using the public key which relates to the prefix.
+	
+	Public encpk = m_known.first ? m_known.first : m_remoteEphemeral;
+	bytes exchange(encpk.asBytes());
+	
+	// This is the public key which we would like the remote to use,
+	// which maybe different than the previously-known public key.
+	//
+	// Here we should pick an appropriate alias or generate a new one,
+	// but for now, we use static alias passed to constructor.
+	//
+	Public p = toPublic(m_alias.m_secret);
+	exchange.resize(exchange.size() + sizeof(p));
+	memcpy(&exchange[exchange.size() - sizeof(p)], p.data(), sizeof(p));
+	
+	// protocol parameters; should be fixed size
+	bytes v(1, 0x80);
+	exchange.resize(exchange.size() + v.size());
+	memcpy(&exchange[exchange.size() - v.size()], v.data(), v.size());
+	
+	h256 auth;
+	sha3mac(m_alias.m_secret.ref(), m_ephemeralSecret.ref(), auth.ref());
+	Signature sig = s_secp256k1.sign(m_alias.m_secret, auth);
+	exchange.resize(exchange.size() + sizeof(sig));
+	memcpy(&exchange[exchange.size() - sizeof(sig)], sig.data(), sizeof(sig));
+	
+	aes::AuthenticatedStream aes(aes::Encrypt, m_ephemeralSecret, 0);
+	h256 prefix(sha3(m_known.second ? m_known.second : (h256)m_remoteEphemeral));
+	aes.update(prefix.ref());
+	
+	s_secp256k1.encrypt(encpk, exchange);
+	aes.update(&exchange);
+
+	aes.streamOut(o_exchange);
+}
+
+
+
diff --git a/libdevcrypto/ECDHE.h b/libdevcrypto/ECDHE.h
new file mode 100644
index 000000000..f77f7fcff
--- /dev/null
+++ b/libdevcrypto/ECDHE.h
@@ -0,0 +1,109 @@
+/*
+ This file is part of cpp-ethereum.
+ 
+ cpp-ethereum is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+ 
+ cpp-ethereum is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ GNU General Public License for more details.
+ 
+ You should have received a copy of the GNU General Public License
+ along with cpp-ethereum.  If not, see .
+ */
+/** @file ECDHE.h
+ * @author Alex Leverington 
+ * @date 2014
+ *
+ * Elliptic curve Diffie-Hellman ephemeral key exchange
+ */
+
+#pragma once
+
+#include "AES.h"
+
+namespace dev
+{
+namespace crypto
+{
+	
+/// Public key of remote and corresponding shared secret.
+typedef std::pair AliasSession;
+	
+/**
+ * @brief An addressable EC key pair.
+ */
+class Alias
+{
+	friend class ECDHEKeyExchange; // todo: remove
+public:
+	Alias(Secret _s): m_secret(_s) {};
+	
+	AliasSession session(Address _a) { return m_sessions.count(_a) ? m_sessions.find(_a)->second : AliasSession(); }
+	
+private:
+	std::map m_sessions;
+	Secret m_secret;
+};
+	
+/**
+ * @brief Derive DH shared secret from EC keypairs.
+ * As ephemeral keys are single-use, agreement is limited to a single occurence.
+ */
+class ECDHE
+{
+public:
+	/// Constructor (pass public key for ingress exchange).
+	ECDHE(): m_ephemeral(KeyPair::create()) {};
+
+	/// Public key sent to remote.
+	Public pubkey() { return m_ephemeral.pub(); }
+	
+	/// Input public key for dh agreement, output generated shared secret.
+	void agree(Public const& _remoteEphemeral, Secret& o_sharedSecret);
+	
+protected:
+	KeyPair m_ephemeral;			///< Ephemeral keypair; generated.
+	Public m_remoteEphemeral;		///< Public key of remote; parameter.
+};
+
+/**
+ * @brief Secure exchange of static keys.
+ * Key exchange is encrypted with public key of remote and then encrypted by block cipher. For a blind remote the ecdhe public key is used to encrypt exchange, and for a known remote the known public key is used. The block cipher key is derived from ecdhe shared secret.
+ *
+ * Usage: Agree -> Exchange -> Authenticate
+ */
+class ECDHEKeyExchange: private ECDHE
+{
+public:
+	/// Exchange with unknown remote (pass public key for ingress exchange)
+	ECDHEKeyExchange(Alias& _k): m_alias(_k) {};
+
+	/// Exchange with known remote
+	ECDHEKeyExchange(Alias& _k, AliasSession _known): m_alias(_k), m_known(_known) {};
+
+	/// Provide public key for dh agreement to generate shared secret.
+	void agree(Public const& _remoteEphemeral);
+	
+	/// @returns encrypted payload of key exchange
+	void exchange(bytes& o_exchange);
+	
+	/// Decrypt payload, check mac, check trust, decrypt exchange, authenticate exchange, verify version, verify signature, and if no failure occurs, update or creats trust and derive session-shared-secret.
+	bool authenticate(bytes _exchangeIn);
+
+private:
+	Secret m_ephemeralSecret;
+	Alias m_alias;
+	AliasSession m_known;
+	Secret m_sharedAliasSecret;
+
+	FixedHash<16> m_sharedC;
+	FixedHash<16> m_sharedM;
+};
+
+}
+}
+
diff --git a/libdevcrypto/SHA3.cpp b/libdevcrypto/SHA3.cpp
index 4a0cd469e..b7a47b745 100644
--- a/libdevcrypto/SHA3.cpp
+++ b/libdevcrypto/SHA3.cpp
@@ -30,7 +30,7 @@ namespace dev
 {
 
 h256 EmptySHA3 = sha3(bytesConstRef());
-h256 EmptyListSHA3 = sha3(RLPEmptyList);
+h256 EmptyListSHA3 = sha3(rlpList());
 
 std::string sha3(std::string const& _input, bool _hex)
 {
@@ -86,6 +86,16 @@ h256 sha3(bytesConstRef _input)
 	sha3(_input, bytesRef(&ret[0], 32));
 	return ret;
 }
+	
+void sha3mac(bytesConstRef _secret, bytesConstRef _plain, bytesRef _output)
+{
+	CryptoPP::SHA3_256 ctx;
+	assert(_secret.size() > 0);
+	ctx.Update((byte*)_secret.data(), _secret.size());
+	ctx.Update((byte*)_plain.data(), _plain.size());
+	assert(_output.size() >= 32);
+	ctx.Final(_output.data());
+}
 
 bytes aesDecrypt(bytesConstRef _ivCipher, std::string const& _password, unsigned _rounds, bytesConstRef _salt)
 {
diff --git a/libdevcrypto/SHA3.h b/libdevcrypto/SHA3.h
index 7aa4db246..f27e378ba 100644
--- a/libdevcrypto/SHA3.h
+++ b/libdevcrypto/SHA3.h
@@ -55,6 +55,9 @@ inline h256 sha3(bytes const& _input) { return sha3(bytesConstRef((bytes*)&_inpu
 
 /// Calculate SHA3-256 hash of the given input (presented as a binary-filled string), returning as a 256-bit hash.
 inline h256 sha3(std::string const& _input) { return sha3(bytesConstRef(_input)); }
+	
+/// Calculate SHA3-256 MAC
+void sha3mac(bytesConstRef _secret, bytesConstRef _plain, bytesRef _output);
 
 /// Calculate SHA3-256 hash of the given input (presented as a FixedHash), returns a 256-bit hash.
 template inline h256 sha3(FixedHash const& _input) { return sha3(_input.ref()); }
diff --git a/libdevcrypto/SHA3MAC.h b/libdevcrypto/SHA3MAC.h
deleted file mode 100644
index 4b2d06eac..000000000
--- a/libdevcrypto/SHA3MAC.h
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- This file is part of cpp-ethereum.
-
- cpp-ethereum is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- cpp-ethereum is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with cpp-ethereum.  If not, see .
- */
-/** @file SHA3MAC.h
- * @author Alex Leverington 
- * @date 2014
- *
- * SHA3 MAC
- */
-
-#pragma once
-
-#include 
-#include 
-
-namespace dev
-{
-namespace crypto
-{
-
-void sha3mac(bytesConstRef _secret, bytesConstRef _plain, bytesRef _output);
-
-}
-}
-
diff --git a/libdevcrypto/TrieDB.cpp b/libdevcrypto/TrieDB.cpp
index 674f21aa4..6f476c14b 100644
--- a/libdevcrypto/TrieDB.cpp
+++ b/libdevcrypto/TrieDB.cpp
@@ -24,9 +24,5 @@
 using namespace std;
 using namespace dev;
 
-#if !ETH_LANGUAGES
-
 h256 const dev::c_shaNull = sha3(rlp(""));
 h256 const dev::EmptyTrie = c_shaNull;
-
-#endif
diff --git a/libethcore/All.h b/libethcore/All.h
deleted file mode 100644
index cb1d3f5a3..000000000
--- a/libethcore/All.h
+++ /dev/null
@@ -1,7 +0,0 @@
-#pragma once
-
-#include "BlockInfo.h"
-#include "CommonEth.h"
-#include "ProofOfWork.h"
-#include "Exceptions.h"
-
diff --git a/libethcore/BlockInfo.cpp b/libethcore/BlockInfo.cpp
index 44da9603c..bf973b565 100644
--- a/libethcore/BlockInfo.cpp
+++ b/libethcore/BlockInfo.cpp
@@ -19,8 +19,6 @@
  * @date 2014
  */
 
-#if !ETH_LANGUAGES
-
 #include 
 #include 
 #include 
@@ -49,19 +47,19 @@ BlockInfo BlockInfo::fromHeader(bytesConstRef _block)
 	return ret;
 }
 
-h256 BlockInfo::headerHashWithoutNonce() const
+h256 BlockInfo::headerHash(IncludeNonce _n) const
 {
 	RLPStream s;
-	streamRLP(s, false);
+	streamRLP(s, _n);
 	return sha3(s.out());
 }
 
-void BlockInfo::streamRLP(RLPStream& _s, bool _nonce) const
+void BlockInfo::streamRLP(RLPStream& _s, IncludeNonce _n) const
 {
-	_s.appendList(_nonce ? 15 : 14)
+	_s.appendList(_n == WithNonce ? 14 : 13)
 		<< parentHash << sha3Uncles << coinbaseAddress << stateRoot << transactionsRoot << receiptsRoot << logBloom
-		<< difficulty << number << minGasPrice << gasLimit << gasUsed << timestamp << extraData;
-	if (_nonce)
+		<< difficulty << number << gasLimit << gasUsed << timestamp << extraData;
+	if (_n == WithNonce)
 		_s << nonce;
 }
 
@@ -86,12 +84,11 @@ void BlockInfo::populateFromHeader(RLP const& _header, bool _checkNonce)
 		logBloom = _header[field = 6].toHash();
 		difficulty = _header[field = 7].toInt();
 		number = _header[field = 8].toInt();
-		minGasPrice = _header[field = 9].toInt();
-		gasLimit = _header[field = 10].toInt();
-		gasUsed = _header[field = 11].toInt();
-		timestamp = _header[field = 12].toInt();
-		extraData = _header[field = 13].toBytes();
-		nonce = _header[field = 14].toHash();
+		gasLimit = _header[field = 9].toInt();
+		gasUsed = _header[field = 10].toInt();
+		timestamp = _header[field = 11].toInt();
+		extraData = _header[field = 12].toBytes();
+		nonce = _header[field = 13].toHash();
 	}
 
 	catch (Exception const& _e)
@@ -101,8 +98,8 @@ void BlockInfo::populateFromHeader(RLP const& _header, bool _checkNonce)
 	}
 
 	// check it hashes according to proof of work or that it's the genesis block.
-	if (_checkNonce && parentHash && !ProofOfWork::verify(headerHashWithoutNonce(), nonce, difficulty))
-		BOOST_THROW_EXCEPTION(InvalidBlockNonce(headerHashWithoutNonce(), nonce, difficulty));
+	if (_checkNonce && parentHash && !ProofOfWork::verify(headerHash(WithoutNonce), nonce, difficulty))
+		BOOST_THROW_EXCEPTION(InvalidBlockNonce(headerHash(WithoutNonce), nonce, difficulty));
 
 	if (gasUsed > gasLimit)
 		BOOST_THROW_EXCEPTION(TooMuchGasUsed());
@@ -147,9 +144,6 @@ void BlockInfo::verifyInternals(bytesConstRef _block) const
 	if (transactionsRoot != t.root())
 		BOOST_THROW_EXCEPTION(InvalidTransactionsHash(t.root(), transactionsRoot));
 
-	if (minGasPrice > mgp)
-		BOOST_THROW_EXCEPTION(InvalidMinGasPrice(minGasPrice, mgp));
-
 	if (sha3Uncles != sha3(root[2].data()))
 		BOOST_THROW_EXCEPTION(InvalidUnclesHash());
 }
@@ -201,5 +195,3 @@ void BlockInfo::verifyParent(BlockInfo const& _parent) const
 			BOOST_THROW_EXCEPTION(InvalidNumber());
 	}
 }
-
-#endif
diff --git a/libethcore/BlockInfo.h b/libethcore/BlockInfo.h
index d91ff244d..18dd53ff3 100644
--- a/libethcore/BlockInfo.h
+++ b/libethcore/BlockInfo.h
@@ -32,6 +32,12 @@ namespace eth
 
 extern u256 c_genesisDifficulty;
 
+enum IncludeNonce
+{
+	WithoutNonce = 0,
+	WithNonce = 1
+};
+
 /** @brief Encapsulation of a block header.
  * Class to contain all of a block header's data. It is able to parse a block header and populate
  * from some given RLP block serialisation with the static fromHeader(), through the method
@@ -48,7 +54,7 @@ extern u256 c_genesisDifficulty;
  *
  * The difficulty and gas-limit derivations may be calculated with the calculateDifficulty()
  * and calculateGasLimit() and the object serialised to RLP with streamRLP. To determine the
- * header hash without the nonce (for mining), the method headerHashWithoutNonce() is provided.
+ * header hash without the nonce (for mining), the method headerHash(WithoutNonce) is provided.
  *
  * The default constructor creates an empty object, which can be tested against with the boolean
  * conversion operator.
@@ -63,10 +69,9 @@ public:
 	h256 stateRoot;
 	h256 transactionsRoot;
 	h256 receiptsRoot;
-	h512 logBloom;	// TODO LogBloom - get include
+	LogBloom logBloom;
 	u256 difficulty;
 	u256 number;
-	u256 minGasPrice;
 	u256 gasLimit;
 	u256 gasUsed;
 	u256 timestamp;
@@ -95,7 +100,6 @@ public:
 				logBloom == _cmp.logBloom &&
 				difficulty == _cmp.difficulty &&
 				number == _cmp.number &&
-				minGasPrice == _cmp.minGasPrice &&
 				gasLimit == _cmp.gasLimit &&
 				gasUsed == _cmp.gasUsed &&
 				timestamp == _cmp.timestamp &&
@@ -114,15 +118,15 @@ public:
 	u256 calculateDifficulty(BlockInfo const& _parent) const;
 	u256 calculateGasLimit(BlockInfo const& _parent) const;
 
-	/// No-nonce sha3 of the header only.
-	h256 headerHashWithoutNonce() const;
-	void streamRLP(RLPStream& _s, bool _nonce) const;
+	/// sha3 of the header only.
+	h256 headerHash(IncludeNonce _n) const;
+	void streamRLP(RLPStream& _s, IncludeNonce _n) const;
 };
 
 inline std::ostream& operator<<(std::ostream& _out, BlockInfo const& _bi)
 {
 	_out << _bi.hash << " " << _bi.parentHash << " " << _bi.sha3Uncles << " " << _bi.coinbaseAddress << " " << _bi.stateRoot << " " << _bi.transactionsRoot << " " <<
-			_bi.receiptsRoot << " " << _bi.logBloom << " " << _bi.difficulty << " " << _bi.number << " " << _bi.minGasPrice << " " << _bi.gasLimit << " " <<
+			_bi.receiptsRoot << " " << _bi.logBloom << " " << _bi.difficulty << " " << _bi.number << " " << _bi.gasLimit << " " <<
 			_bi.gasUsed << " " << _bi.timestamp << " " << _bi.nonce;
 	return _out;
 }
diff --git a/libethcore/CMakeLists.txt b/libethcore/CMakeLists.txt
index f5cf00b57..984aa3ce5 100644
--- a/libethcore/CMakeLists.txt
+++ b/libethcore/CMakeLists.txt
@@ -1,54 +1,29 @@
 cmake_policy(SET CMP0015 NEW)
+# this policy was introduced in cmake 3.0
+# remove if, once 3.0 will be used on unix
+if (${CMAKE_MAJOR_VERSION} GREATER 2)
+	# old policy do not use MACOSX_RPATH
+	cmake_policy(SET CMP0042 OLD)
+endif()
+set(CMAKE_AUTOMOC OFF)
 
 aux_source_directory(. SRC_LIST)
 
+include_directories(${Boost_INCLUDE_DIRS})
+include_directories(..)
+
 set(EXECUTABLE ethcore)
 
 file(GLOB HEADERS "*.h")
+
 if(ETH_STATIC)
 	add_library(${EXECUTABLE} STATIC ${SRC_LIST} ${HEADERS})
 else()
 	add_library(${EXECUTABLE} SHARED ${SRC_LIST} ${HEADERS})
 endif()
 
-include_directories(..)
-
 target_link_libraries(${EXECUTABLE} devcrypto)
 target_link_libraries(${EXECUTABLE} devcore)
-target_link_libraries(${EXECUTABLE} secp256k1)
-target_link_libraries(${EXECUTABLE} gmp)
-target_link_libraries(${EXECUTABLE} ${LEVELDB_LS})
-target_link_libraries(${EXECUTABLE} ${CRYPTOPP_LS})
-
-if("${TARGET_PLATFORM}" STREQUAL "w64")
-	target_link_libraries(${EXECUTABLE} boost_system-mt-s)
-	target_link_libraries(${EXECUTABLE} boost_filesystem-mt-s)
-	target_link_libraries(${EXECUTABLE} boost_thread_win32-mt-s)
-	target_link_libraries(${EXECUTABLE} iphlpapi)
-	target_link_libraries(${EXECUTABLE} ws2_32)
-	target_link_libraries(${EXECUTABLE} mswsock)
-	target_link_libraries(${EXECUTABLE} shlwapi)
-elseif (APPLE)
-	# Latest mavericks boost libraries only come with -mt
-	target_link_libraries(${EXECUTABLE} boost_system-mt)
-	target_link_libraries(${EXECUTABLE} boost_filesystem-mt)
-	target_link_libraries(${EXECUTABLE} boost_thread-mt)
-	find_package(Threads REQUIRED)
-	target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT})
-elseif (UNIX)
-	find_package(Boost 1.53 REQUIRED COMPONENTS filesystem)
-	target_link_libraries(${EXECUTABLE} ${Boost_SYSTEM_LIBRARY})
-	target_link_libraries(${EXECUTABLE} ${Boost_FILESYSTEM_LIBRARY})
-	target_link_libraries(${EXECUTABLE} ${Boost_THREAD_LIBRARY})
-	target_link_libraries(${EXECUTABLE} ${Boost_DATE_TIME_LIBRARY})
-	target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT})
-else ()
-	target_link_libraries(${EXECUTABLE} boost_system)
-	target_link_libraries(${EXECUTABLE} boost_filesystem)
-	target_link_libraries(${EXECUTABLE} boost_thread)
-	find_package(Threads REQUIRED)
-	target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT})
-endif ()
 
 install( TARGETS ${EXECUTABLE} ARCHIVE DESTINATION lib LIBRARY DESTINATION lib )
 install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} )
diff --git a/libethcore/CommonEth.cpp b/libethcore/CommonEth.cpp
index 8e21884ee..5e510572e 100644
--- a/libethcore/CommonEth.cpp
+++ b/libethcore/CommonEth.cpp
@@ -21,21 +21,19 @@
 
 #include "CommonEth.h"
 #include 
-#include 
 #include 
 #include "Exceptions.h"
 using namespace std;
 using namespace dev;
 using namespace dev::eth;
 
-//#define ETH_ADDRESS_DEBUG 1
 namespace dev
 {
 namespace eth
 {
 
-const unsigned c_protocolVersion = 39;
-const unsigned c_databaseVersion = 4;
+const unsigned c_protocolVersion = 49;
+const unsigned c_databaseVersion = 5;
 
 static const vector> g_units =
 {
@@ -84,30 +82,4 @@ std::string formatBalance(u256 _b)
 	return ret.str();
 }
 
-Address toAddress(Secret _private)
-{
-	secp256k1_start();
-
-	byte pubkey[65];
-	int pubkeylen = 65;
-	int ok = secp256k1_ecdsa_seckey_verify(_private.data());
-	if (!ok)
-		return Address();
-	ok = secp256k1_ecdsa_pubkey_create(pubkey, &pubkeylen, _private.data(), 0);
-	assert(pubkeylen == 65);
-	if (!ok)
-		return Address();
-	ok = secp256k1_ecdsa_pubkey_verify(pubkey, 65);
-	if (!ok)
-		return Address();
-	auto ret = right160(dev::sha3(bytesConstRef(&(pubkey[1]), 64)));
-#if ETH_ADDRESS_DEBUG
-	cout << "---- ADDRESS -------------------------------" << endl;
-	cout << "SEC: " << _private << endl;
-	cout << "PUB: " << toHex(bytesConstRef(&(pubkey[1]), 64)) << endl;
-	cout << "ADR: " << ret << endl;
-#endif
-	return ret;
-}
-
 }}
diff --git a/libethcore/CommonEth.h b/libethcore/CommonEth.h
index 1965a881a..be7db8434 100644
--- a/libethcore/CommonEth.h
+++ b/libethcore/CommonEth.h
@@ -44,6 +44,9 @@ std::string formatBalance(u256 _b);
 /// Get information concerning the currency denominations.
 std::vector> const& units();
 
+/// The log bloom's size (512 bit).
+using LogBloom = h512;
+
 // The various denominations; here for ease of use where needed within code.
 static const u256 Uether = ((((u256(1000000000) * 1000000000) * 1000000000) * 1000000000) * 1000000000) * 1000000000;
 static const u256 Vether = ((((u256(1000000000) * 1000000000) * 1000000000) * 1000000000) * 1000000000) * 1000000;
diff --git a/libethcore/Exceptions.h b/libethcore/Exceptions.h
index 5a07407d2..b53a62562 100644
--- a/libethcore/Exceptions.h
+++ b/libethcore/Exceptions.h
@@ -60,6 +60,7 @@ struct InvalidTransactionGasUsed: virtual dev::Exception {};
 struct InvalidTransactionsStateRoot: virtual dev::Exception {};
 struct InvalidReceiptsStateRoot: virtual dev::Exception {};
 struct InvalidTimestamp: virtual dev::Exception {};
+struct InvalidLogBloom: virtual dev::Exception {};
 class InvalidNonce: virtual public dev::Exception { public: InvalidNonce(u256 _required = 0, u256 _candidate = 0): required(_required), candidate(_candidate) {} u256 required; u256 candidate; virtual const char* what() const noexcept; };
 class InvalidBlockNonce: virtual public dev::Exception { public: InvalidBlockNonce(h256 _h = h256(), h256 _n = h256(), u256 _d = 0): h(_h), n(_n), d(_d) {} h256 h; h256 n; u256 d; virtual const char* what() const noexcept; };
 struct InvalidParentHash: virtual dev::Exception {};
diff --git a/libethcore/ProofOfWork.cpp b/libethcore/ProofOfWork.cpp
index bfb8942cc..181e379b5 100644
--- a/libethcore/ProofOfWork.cpp
+++ b/libethcore/ProofOfWork.cpp
@@ -19,8 +19,6 @@
  * @date 2014
  */
 
-#if !ETH_LANGUAGES
-
 #include 
 #include 
 #include 
@@ -107,4 +105,3 @@ h256 DaggerEvaluator::eval(h256 const& _root, h256 const& _nonce)
 
 }
 }
-#endif
diff --git a/libethcore/_libethcore.cpp b/libethcore/_libethcore.cpp
deleted file mode 100644
index 93eaf0d16..000000000
--- a/libethcore/_libethcore.cpp
+++ /dev/null
@@ -1,7 +0,0 @@
-#ifdef _MSC_VER
-#include "All.h"
-#include "BlockInfo.cpp"
-#include "CommonEth.cpp"
-#include "ProofOfWork.cpp"
-#include "Exceptions.cpp"
-#endif
diff --git a/libethereum/BlockChain.cpp b/libethereum/BlockChain.cpp
index 765b54627..6ed0a2ca6 100644
--- a/libethereum/BlockChain.cpp
+++ b/libethereum/BlockChain.cpp
@@ -101,9 +101,8 @@ bytes BlockChain::createGenesisBlock()
 		stateRoot = state.root();
 	}
 
-	block.appendList(15)
-			// TODO: maybe make logbloom correct?
-		<< h256() << EmptyListSHA3 << h160() << stateRoot << EmptyTrie << EmptyTrie << LogBloom() << c_genesisDifficulty << 0 << 0 << 1000000 << 0 << (unsigned)0 << string() << sha3(bytes(1, 42));
+	block.appendList(14)
+		<< h256() << EmptyListSHA3 << h160() << stateRoot << EmptyTrie << EmptyTrie << LogBloom() << c_genesisDifficulty << 0 << 1000000 << 0 << (unsigned)0 << string() << sha3(bytes(1, 42));
 	block.appendRaw(RLPEmptyList);
 	block.appendRaw(RLPEmptyList);
 	return block.out();
@@ -146,7 +145,7 @@ void BlockChain::open(std::string _path, bool _killExisting)
 	if (!details(m_genesisHash))
 	{
 		// Insert details of genesis block.
-		m_details[m_genesisHash] = BlockDetails(0, c_genesisDifficulty, h256(), {}, h256());
+		m_details[m_genesisHash] = BlockDetails(0, c_genesisDifficulty, h256(), {});
 		auto r = m_details[m_genesisHash].rlp();
 		m_extrasDB->Put(m_writeOptions, ldb::Slice((char const*)&m_genesisHash, 32), (ldb::Slice)dev::ref(r));
 	}
@@ -169,8 +168,6 @@ void BlockChain::close()
 	delete m_db;
 	m_lastBlockHash = m_genesisHash;
 	m_details.clear();
-	m_blooms.clear();
-	m_traces.clear();
 	m_cache.clear();
 }
 
@@ -306,15 +303,10 @@ h256s BlockChain::import(bytes const& _block, OverlayDB const& _db)
 		// Get total difficulty increase and update state, checking it.
 		State s(bi.coinbaseAddress, _db);
 		auto tdIncrease = s.enactOn(&_block, bi, *this);
-		auto b = s.oldBloom();
-		BlockBlooms bb;
-		BlockTraces bt;
 		BlockLogBlooms blb;
 		BlockReceipts br;
 		for (unsigned i = 0; i < s.pending().size(); ++i)
 		{
-			bb.blooms.push_back(s.changesFromPending(i).bloom());
-			bt.traces.push_back(s.changesFromPending(i));
 			blb.blooms.push_back(s.receipt(i).bloom());
 			br.receipts.push_back(s.receipt(i));
 		}
@@ -327,17 +319,9 @@ h256s BlockChain::import(bytes const& _block, OverlayDB const& _db)
 		// All ok - insert into DB
 		{
 			WriteGuard l(x_details);
-			m_details[newHash] = BlockDetails((unsigned)pd.number + 1, td, bi.parentHash, {}, b);
+			m_details[newHash] = BlockDetails((unsigned)pd.number + 1, td, bi.parentHash, {});
 			m_details[bi.parentHash].children.push_back(newHash);
 		}
-		{
-			WriteGuard l(x_blooms);
-			m_blooms[newHash] = bb;
-		}
-		{
-			WriteGuard l(x_traces);
-			m_traces[newHash] = bt;
-		}
 		{
 			WriteGuard l(x_logBlooms);
 			m_logBlooms[newHash] = blb;
@@ -349,8 +333,6 @@ h256s BlockChain::import(bytes const& _block, OverlayDB const& _db)
 
 		m_extrasDB->Put(m_writeOptions, toSlice(newHash), (ldb::Slice)dev::ref(m_details[newHash].rlp()));
 		m_extrasDB->Put(m_writeOptions, toSlice(bi.parentHash), (ldb::Slice)dev::ref(m_details[bi.parentHash].rlp()));
-		m_extrasDB->Put(m_writeOptions, toSlice(newHash, 1), (ldb::Slice)dev::ref(m_blooms[newHash].rlp()));
-		m_extrasDB->Put(m_writeOptions, toSlice(newHash, 2), (ldb::Slice)dev::ref(m_traces[newHash].rlp()));
 		m_extrasDB->Put(m_writeOptions, toSlice(newHash, 3), (ldb::Slice)dev::ref(m_logBlooms[newHash].rlp()));
 		m_extrasDB->Put(m_writeOptions, toSlice(newHash, 4), (ldb::Slice)dev::ref(m_receipts[newHash].rlp()));
 		m_db->Put(m_writeOptions, toSlice(newHash), (ldb::Slice)ref(_block));
diff --git a/libethereum/BlockChain.h b/libethereum/BlockChain.h
index 49f7b149e..d03818bd3 100644
--- a/libethereum/BlockChain.h
+++ b/libethereum/BlockChain.h
@@ -93,18 +93,14 @@ public:
 	/// Returns true if the given block is known (though not necessarily a part of the canon chain).
 	bool isKnown(h256 _hash) const;
 
+	/// Get the familial details concerning a block (or the most recent mined if none given). Thread-safe.
+	BlockInfo info(h256 _hash) const { return BlockInfo(block(_hash)); }
+	BlockInfo info() const { return BlockInfo(block()); }
+
 	/// Get the familial details concerning a block (or the most recent mined if none given). Thread-safe.
 	BlockDetails details(h256 _hash) const { return queryExtras(_hash, m_details, x_details, NullBlockDetails); }
 	BlockDetails details() const { return details(currentHash()); }
 
-	/// Get the transactions' bloom filters of a block (or the most recent mined if none given). Thread-safe.
-	BlockBlooms blooms(h256 _hash) const { return queryExtras(_hash, m_blooms, x_blooms, NullBlockBlooms); }
-	BlockBlooms blooms() const { return blooms(currentHash()); }
-
-	/// Get the transactions' trace manifests of a block (or the most recent mined if none given). Thread-safe.
-	BlockTraces traces(h256 _hash) const { return queryExtras(_hash, m_traces, x_traces, NullBlockTraces); }
-	BlockTraces traces() const { return traces(currentHash()); }
-
 	/// Get the transactions' log blooms of a block (or the most recent mined if none given). Thread-safe.
 	BlockLogBlooms logBlooms(h256 _hash) const { return queryExtras(_hash, m_logBlooms, x_logBlooms, NullBlockLogBlooms); }
 	BlockLogBlooms logBlooms() const { return logBlooms(currentHash()); }
@@ -189,10 +185,6 @@ private:
 	/// The caches of the disk DB and their locks.
 	mutable boost::shared_mutex x_details;
 	mutable BlockDetailsHash m_details;
-	mutable boost::shared_mutex x_blooms;
-	mutable BlockBloomsHash m_blooms;
-	mutable boost::shared_mutex x_traces;
-	mutable BlockTracesHash m_traces;
 	mutable boost::shared_mutex x_logBlooms;
 	mutable BlockLogBloomsHash m_logBlooms;
 	mutable boost::shared_mutex x_receipts;
diff --git a/libethereum/BlockDetails.cpp b/libethereum/BlockDetails.cpp
index 5a61eb037..58f37b7aa 100644
--- a/libethereum/BlockDetails.cpp
+++ b/libethereum/BlockDetails.cpp
@@ -32,10 +32,9 @@ BlockDetails::BlockDetails(RLP const& _r)
 	totalDifficulty = _r[1].toInt();
 	parent = _r[2].toHash();
 	children = _r[3].toVector();
-	bloom = _r[4].toHash();
 }
 
 bytes BlockDetails::rlp() const
 {
-	return rlpList(number, totalDifficulty, parent, children, bloom);
+	return rlpList(number, totalDifficulty, parent, children);
 }
diff --git a/libethereum/BlockDetails.h b/libethereum/BlockDetails.h
index 973e93070..bbfd48e56 100644
--- a/libethereum/BlockDetails.h
+++ b/libethereum/BlockDetails.h
@@ -28,7 +28,6 @@
 
 #include 
 #include 
-#include "Manifest.h"
 #include "TransactionReceipt.h"
 namespace ldb = leveldb;
 
@@ -40,7 +39,7 @@ namespace eth
 struct BlockDetails
 {
 	BlockDetails(): number(0), totalDifficulty(0) {}
-	BlockDetails(unsigned _n, u256 _tD, h256 _p, h256s _c, h256 _bloom): number(_n), totalDifficulty(_tD), parent(_p), children(_c), bloom(_bloom) {}
+	BlockDetails(unsigned _n, u256 _tD, h256 _p, h256s _c): number(_n), totalDifficulty(_tD), parent(_p), children(_c) {}
 	BlockDetails(RLP const& _r);
 	bytes rlp() const;
 
@@ -51,25 +50,6 @@ struct BlockDetails
 	u256 totalDifficulty;
 	h256 parent;
 	h256s children;
-	h256 bloom;
-};
-
-struct BlockBlooms
-{
-	BlockBlooms() {}
-	BlockBlooms(RLP const& _r) { blooms = _r.toVector(); }
-	bytes rlp() const { RLPStream s; s << blooms; return s.out(); }
-
-	h256s blooms;
-};
-
-struct BlockTraces
-{
-	BlockTraces() {}
-	BlockTraces(RLP const& _r) { for (auto const& i: _r) traces.emplace_back(i.data()); }
-	bytes rlp() const { RLPStream s(traces.size()); for (auto const& i: traces) i.streamRLP(s); return s.out(); }
-
-	Manifests traces;
 };
 
 struct BlockLogBlooms
@@ -91,14 +71,10 @@ struct BlockReceipts
 };
 
 typedef std::map BlockDetailsHash;
-typedef std::map BlockBloomsHash;
-typedef std::map BlockTracesHash;
 typedef std::map BlockLogBloomsHash;
 typedef std::map BlockReceiptsHash;
 
 static const BlockDetails NullBlockDetails;
-static const BlockBlooms NullBlockBlooms;
-static const BlockTraces NullBlockTraces;
 static const BlockLogBlooms NullBlockLogBlooms;
 static const BlockReceipts NullBlockReceipts;
 
diff --git a/libethereum/CMakeLists.txt b/libethereum/CMakeLists.txt
index cb2049886..792ed0cf1 100644
--- a/libethereum/CMakeLists.txt
+++ b/libethereum/CMakeLists.txt
@@ -1,19 +1,31 @@
 cmake_policy(SET CMP0015 NEW)
+# this policy was introduced in cmake 3.0
+# remove if, once 3.0 will be used on unix
+if (${CMAKE_MAJOR_VERSION} GREATER 2)
+	# old policy do not use MACOSX_RPATH
+	cmake_policy(SET CMP0042 OLD)
+endif()
+set(CMAKE_AUTOMOC OFF)
 
 set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DSTATICLIB")
 
 aux_source_directory(. SRC_LIST)
 
+include_directories(${LEVELDB_INCLUDE_DIRS})
+include_directories(..)
+
 set(EXECUTABLE ethereum)
 
 file(GLOB HEADERS "*.h")
-if(ETH_STATIC)
+
+if (ETH_STATIC)
 	add_library(${EXECUTABLE} STATIC ${SRC_LIST} ${HEADERS})
 else()
 	add_library(${EXECUTABLE} SHARED ${SRC_LIST} ${HEADERS})
 endif()
 
-include_directories(..)
+target_link_libraries(${EXECUTABLE} ${LEVELDB_LIBRARIES})
+target_link_libraries(${EXECUTABLE} ${Boost_REGEX_LIBRARY_RELEASE})
 
 target_link_libraries(${EXECUTABLE} evm)
 target_link_libraries(${EXECUTABLE} lll)
@@ -22,45 +34,6 @@ target_link_libraries(${EXECUTABLE} p2p)
 target_link_libraries(${EXECUTABLE} devcrypto)
 target_link_libraries(${EXECUTABLE} ethcore)
 target_link_libraries(${EXECUTABLE} secp256k1)
-if(MINIUPNPC_LS)
-target_link_libraries(${EXECUTABLE} ${MINIUPNPC_LS})
-endif()
-target_link_libraries(${EXECUTABLE} ${LEVELDB_LS})
-target_link_libraries(${EXECUTABLE} ${CRYPTOPP_LS})
-target_link_libraries(${EXECUTABLE} gmp)
-
-if("${TARGET_PLATFORM}" STREQUAL "w64")
-	target_link_libraries(${EXECUTABLE} boost_system-mt-s)
-	target_link_libraries(${EXECUTABLE} boost_regex-mt-s)
-	target_link_libraries(${EXECUTABLE} boost_filesystem-mt-s)
-	target_link_libraries(${EXECUTABLE} boost_thread_win32-mt-s)
-	target_link_libraries(${EXECUTABLE} iphlpapi)
-	target_link_libraries(${EXECUTABLE} ws2_32)
-	target_link_libraries(${EXECUTABLE} mswsock)
-	target_link_libraries(${EXECUTABLE} shlwapi)
-elseif (APPLE)
-	# Latest mavericks boost libraries only come with -mt
-	target_link_libraries(${EXECUTABLE} boost_system-mt)
-	target_link_libraries(${EXECUTABLE} boost_regex-mt)
-	target_link_libraries(${EXECUTABLE} boost_filesystem-mt)
-	target_link_libraries(${EXECUTABLE} boost_thread-mt)
-	find_package(Threads REQUIRED)
-	target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT})
-elseif (UNIX)
-	target_link_libraries(${EXECUTABLE} ${Boost_SYSTEM_LIBRARY})
-	target_link_libraries(${EXECUTABLE} ${Boost_REGEX_LIBRARY})
-	target_link_libraries(${EXECUTABLE} ${Boost_FILESYSTEM_LIBRARY})
-	target_link_libraries(${EXECUTABLE} ${Boost_THREAD_LIBRARY})
-	target_link_libraries(${EXECUTABLE} ${Boost_DATE_TIME_LIBRARY})
-	target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT})
-else ()
-	target_link_libraries(${EXECUTABLE} boost_system)
-	target_link_libraries(${EXECUTABLE} boost_regex)
-	target_link_libraries(${EXECUTABLE} boost_filesystem)
-	target_link_libraries(${EXECUTABLE} boost_thread)
-	find_package(Threads REQUIRED)
-	target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT})
-endif ()
 
 install( TARGETS ${EXECUTABLE} ARCHIVE DESTINATION lib LIBRARY DESTINATION lib )
 install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} )
diff --git a/libethereum/CachedAddressState.cpp b/libethereum/CachedAddressState.cpp
new file mode 100644
index 000000000..5f9be6944
--- /dev/null
+++ b/libethereum/CachedAddressState.cpp
@@ -0,0 +1,101 @@
+/*
+	This file is part of cpp-ethereum.
+
+	cpp-ethereum is free software: you can redistribute it and/or modify
+	it under the terms of the GNU General Public License as published by
+	the Free Software Foundation, either version 3 of the License, or
+	(at your option) any later version.
+
+	cpp-ethereum is distributed in the hope that it will be useful,
+	but WITHOUT ANY WARRANTY; without even the implied warranty of
+	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+	GNU General Public License for more details.
+
+	You should have received a copy of the GNU General Public License
+	along with cpp-ethereum.  If not, see .
+*/
+/** @file CachedAddressState.cpp
+ * @author Gav Wood 
+ * @date 2014
+ */
+
+#include "CachedAddressState.h"
+
+#include 
+#include 
+#include "Account.h"
+using namespace std;
+using namespace dev;
+using namespace dev::eth;
+
+bool CachedAddressState::exists() const
+{
+	return (m_r && (!m_s || m_s->isAlive())) || (m_s && m_s->isAlive());
+}
+
+u256 CachedAddressState::balance() const
+{
+	return m_r ? m_s ? m_s->balance() : m_r[1].toInt() : 0;
+}
+
+u256 CachedAddressState::nonce() const
+{
+	return m_r ? m_s ? m_s->nonce() : m_r[0].toInt() : 0;
+}
+
+bytes CachedAddressState::code() const
+{
+	if (m_s && m_s->codeCacheValid())
+		return m_s->code();
+	h256 h = m_r ? m_s ? m_s->codeHash() : m_r[3].toHash() : EmptySHA3;
+	return h == EmptySHA3 ? bytes() : asBytes(m_o->lookup(h));
+}
+
+std::map CachedAddressState::storage() const
+{
+	std::map ret;
+	if (m_r)
+	{
+		TrieDB memdb(const_cast(m_o), m_r[2].toHash());		// promise we won't alter the overlay! :)
+		for (auto const& j: memdb)
+			ret[j.first] = RLP(j.second).toInt();
+	}
+	if (m_s)
+		for (auto const& j: m_s->storageOverlay())
+			if ((!ret.count(j.first) && j.second) || (ret.count(j.first) && ret.at(j.first) != j.second))
+				ret[j.first] = j.second;
+	return ret;
+}
+
+AccountDiff CachedAddressState::diff(CachedAddressState const& _c)
+{
+	AccountDiff ret;
+	ret.exist = Diff(exists(), _c.exists());
+	ret.balance = Diff(balance(), _c.balance());
+	ret.nonce = Diff(nonce(), _c.nonce());
+	ret.code = Diff(code(), _c.code());
+	auto st = storage();
+	auto cst = _c.storage();
+	auto it = st.begin();
+	auto cit = cst.begin();
+	while (it != st.end() || cit != cst.end())
+	{
+		if (it != st.end() && cit != cst.end() && it->first == cit->first && (it->second || cit->second) && (it->second != cit->second))
+			ret.storage[it->first] = Diff(it->second, cit->second);
+		else if (it != st.end() && (cit == cst.end() || it->first < cit->first) && it->second)
+			ret.storage[it->first] = Diff(it->second, 0);
+		else if (cit != cst.end() && (it == st.end() || it->first > cit->first) && cit->second)
+			ret.storage[cit->first] = Diff(0, cit->second);
+		if (it == st.end())
+			++cit;
+		else if (cit == cst.end())
+			++it;
+		else if (it->first < cit->first)
+			++it;
+		else if (it->first > cit->first)
+			++cit;
+		else
+			++it, ++cit;
+	}
+	return ret;
+}
diff --git a/libethereum/CachedAddressState.h b/libethereum/CachedAddressState.h
new file mode 100644
index 000000000..301f54338
--- /dev/null
+++ b/libethereum/CachedAddressState.h
@@ -0,0 +1,60 @@
+/*
+	This file is part of cpp-ethereum.
+
+	cpp-ethereum is free software: you can redistribute it and/or modify
+	it under the terms of the GNU General Public License as published by
+	the Free Software Foundation, either version 3 of the License, or
+	(at your option) any later version.
+
+	cpp-ethereum is distributed in the hope that it will be useful,
+	but WITHOUT ANY WARRANTY; without even the implied warranty of
+	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+	GNU General Public License for more details.
+
+	You should have received a copy of the GNU General Public License
+	along with cpp-ethereum.  If not, see .
+*/
+/** @file CachedAddressState.h
+ * @author Gav Wood 
+ * @date 2014
+ */
+
+#pragma once
+
+#include 
+#include 
+#include 
+#include "AccountDiff.h"
+
+namespace dev
+{
+
+class OverlayDB;
+
+namespace eth
+{
+
+class Account;
+
+class CachedAddressState
+{
+public:
+	CachedAddressState(std::string const& _rlp, Account const* _s, OverlayDB const* _o): m_rS(_rlp), m_r(m_rS), m_s(_s), m_o(_o) {}
+
+	bool exists() const;
+	u256 balance() const;
+	u256 nonce() const;
+	bytes code() const;
+	std::map storage() const;
+	AccountDiff diff(CachedAddressState const& _c);
+
+private:
+	std::string m_rS;
+	RLP m_r;
+	Account const* m_s;
+	OverlayDB const* m_o;
+};
+
+}
+
+}
diff --git a/libethereum/Client.cpp b/libethereum/Client.cpp
index d87e9c33e..e3346754b 100644
--- a/libethereum/Client.cpp
+++ b/libethereum/Client.cpp
@@ -159,7 +159,7 @@ void Client::clearPending()
 		if (!m_postMine.pending().size())
 			return;
 		for (unsigned i = 0; i < m_postMine.pending().size(); ++i)
-			appendFromNewPending(m_postMine.oldBloom(i), changeds);
+			appendFromNewPending(m_postMine.logBloom(i), changeds);
 		changeds.insert(PendingChangedFilter);
 		m_postMine = m_preMine;
 	}
@@ -181,7 +181,7 @@ unsigned Client::installWatch(h256 _h)
 	return ret;
 }
 
-unsigned Client::installWatch(MessageFilter const& _f)
+unsigned Client::installWatch(LogFilter const& _f)
 {
 	lock_guard l(m_filterLock);
 
@@ -217,13 +217,14 @@ void Client::noteChanged(h256Set const& _filters)
 	for (auto& i: m_watches)
 		if (_filters.count(i.second.id))
 		{
-			cwatch << "!!!" << i.first << i.second.id;
+//			cwatch << "!!!" << i.first << i.second.id;
 			i.second.changes++;
 		}
 }
 
-void Client::appendFromNewPending(h256 _bloom, h256Set& o_changed) const
+void Client::appendFromNewPending(LogBloom _bloom, h256Set& o_changed) const
 {
+	// TODO: more precise check on whether the txs match.
 	lock_guard l(m_filterLock);
 	for (pair const& i: m_filters)
 		if ((unsigned)i.second.filter.latest() > m_bc.number() && i.second.filter.matches(_bloom))
@@ -232,11 +233,12 @@ void Client::appendFromNewPending(h256 _bloom, h256Set& o_changed) const
 
 void Client::appendFromNewBlock(h256 _block, h256Set& o_changed) const
 {
-	auto d = m_bc.details(_block);
+	// TODO: more precise check on whether the txs match.
+	auto d = m_bc.info(_block);
 
 	lock_guard l(m_filterLock);
 	for (pair const& i: m_filters)
-		if ((unsigned)i.second.filter.latest() >= d.number && (unsigned)i.second.filter.earliest() <= d.number && i.second.filter.matches(d.bloom))
+		if ((unsigned)i.second.filter.latest() >= d.number && (unsigned)i.second.filter.earliest() <= d.number && i.second.filter.matches(d.logBloom))
 			o_changed.insert(i.first);
 }
 
@@ -341,7 +343,7 @@ bytes Client::call(Secret _secret, u256 _value, Address _dest, bytes const& _dat
 			n = temp.transactionsFrom(toAddress(_secret));
 		}
 		Transaction t(_value, _gasPrice, _gas, _dest, _data, n, _secret);
-		u256 gasUsed = temp.execute(t.data(), &out, false);
+		u256 gasUsed = temp.execute(t.rlp(), &out, false);
 		(void)gasUsed; // TODO: do something with gasused which it returns.
 	}
 	catch (...)
@@ -440,7 +442,7 @@ void Client::doWork()
 
 		// returns h256s as blooms, once for each transaction.
 		cwork << "postSTATE <== TQ";
-		h256s newPendingBlooms = m_postMine.sync(m_tq);
+		h512s newPendingBlooms = m_postMine.sync(m_tq);
 		if (newPendingBlooms.size())
 		{
 			for (auto i: newPendingBlooms)
@@ -564,9 +566,9 @@ BlockInfo Client::uncle(h256 _blockHash, unsigned _i) const
 	return BlockInfo::fromHeader(b[2][_i].data());
 }
 
-PastMessages Client::messages(MessageFilter const& _f) const
+LogEntries Client::logs(LogFilter const& _f) const
 {
-	PastMessages ret;
+	LogEntries ret;
 	unsigned begin = min(m_bc.number(), (unsigned)_f.latest());
 	unsigned end = min(begin, (unsigned)_f.earliest());
 	unsigned m = _f.max();
@@ -578,23 +580,22 @@ PastMessages Client::messages(MessageFilter const& _f) const
 		ReadGuard l(x_stateDB);
 		for (unsigned i = 0; i < m_postMine.pending().size(); ++i)
 		{
-			// Might have a transaction that contains a matching message.
-			Manifest const& ms = m_postMine.changesFromPending(i);
-			PastMessages pm = _f.matches(ms, i);
-			if (pm.size())
+			// Might have a transaction that contains a matching log.
+			TransactionReceipt const& tr = m_postMine.receipt(i);
+			LogEntries le = _f.matches(tr);
+			if (le.size())
 			{
-				auto ts = time(0);
-				for (unsigned j = 0; j < pm.size() && ret.size() != m; ++j)
+				for (unsigned j = 0; j < le.size() && ret.size() != m; ++j)
 					if (s)
 						s--;
 					else
-						// Have a transaction that contains a matching message.
-						ret.insert(ret.begin(), pm[j].polish(h256(), ts, m_bc.number() + 1, m_postMine.address()));
+						ret.insert(ret.begin(), le[j]);
 			}
 		}
 	}
 
 #if ETH_DEBUG
+	// fill these params
 	unsigned skipped = 0;
 	unsigned falsePos = 0;
 #endif
@@ -602,55 +603,44 @@ PastMessages Client::messages(MessageFilter const& _f) const
 	unsigned n = begin;
 	for (; ret.size() != m && n != end; n--, h = m_bc.details(h).parent)
 	{
-		auto d = m_bc.details(h);
 #if ETH_DEBUG
 		int total = 0;
 #endif
-		if (_f.matches(d.bloom))
-		{
-			// Might have a block that contains a transaction that contains a matching message.
-			auto bs = m_bc.blooms(h).blooms;
-			Manifests ms;
-			BlockInfo bi;
-			for (unsigned i = 0; i < bs.size(); ++i)
-				if (_f.matches(bs[i]))
+		// check block bloom
+		if (_f.matches(m_bc.info(h).logBloom))
+			for (TransactionReceipt receipt: m_bc.receipts(h).receipts)
+			{
+				if (_f.matches(receipt.bloom()))
 				{
-					// Might have a transaction that contains a matching message.
-					if (ms.empty())
-						ms = m_bc.traces(h).traces;
-					Manifest const& changes = ms[i];
-					PastMessages pm = _f.matches(changes, i);
-					if (pm.size())
+					LogEntries le = _f.matches(receipt);
+					if (le.size())
 					{
 #if ETH_DEBUG
-						total += pm.size();
+						total += le.size();
 #endif
-						if (!bi)
-							bi.populate(m_bc.block(h));
-						auto ts = bi.timestamp;
-						auto cb = bi.coinbaseAddress;
-						for (unsigned j = 0; j < pm.size() && ret.size() != m; ++j)
+						for (unsigned j = 0; j < le.size() && ret.size() != m; ++j)
+						{
 							if (s)
 								s--;
 							else
-								// Have a transaction that contains a matching message.
-								ret.push_back(pm[j].polish(h, ts, n, cb));
+								ret.insert(ret.begin(), le[j]);
+						}
 					}
 				}
 #if ETH_DEBUG
-			if (!total)
-				falsePos++;
-		}
+				if (!total)
+					falsePos++;
+#endif
+			}
+#if ETH_DEBUG
 		else
 			skipped++;
-#else
-		}
 #endif
 		if (n == end)
 			break;
 	}
 #if ETH_DEBUG
-//	cdebug << (begin - n) << "searched; " << skipped << "skipped; " << falsePos << "false +ves";
+	cdebug << (begin - n) << "searched; " << skipped << "skipped; " << falsePos << "false +ves";
 #endif
 	return ret;
 }
diff --git a/libethereum/Client.h b/libethereum/Client.h
index 8ec65c199..e8c460093 100644
--- a/libethereum/Client.h
+++ b/libethereum/Client.h
@@ -36,8 +36,7 @@
 #include "TransactionQueue.h"
 #include "State.h"
 #include "CommonNet.h"
-#include "PastMessage.h"
-#include "MessageFilter.h"
+#include "LogFilter.h"
 #include "Miner.h"
 #include "Interface.h"
 
@@ -79,9 +78,9 @@ static const int GenesisBlock = INT_MIN;
 
 struct InstalledFilter
 {
-	InstalledFilter(MessageFilter const& _f): filter(_f) {}
+	InstalledFilter(LogFilter const& _f): filter(_f) {}
 
-	MessageFilter filter;
+	LogFilter filter;
 	unsigned refCount = 1;
 };
 
@@ -152,14 +151,14 @@ public:
 	virtual bytes codeAt(Address _a, int _block) const;
 	virtual std::map storageAt(Address _a, int _block) const;
 
-	virtual unsigned installWatch(MessageFilter const& _filter);
+	virtual unsigned installWatch(LogFilter const& _filter);
 	virtual unsigned installWatch(h256 _filterId);
 	virtual void uninstallWatch(unsigned _watchId);
 	virtual bool peekWatch(unsigned _watchId) const { std::lock_guard l(m_filterLock); try { return m_watches.at(_watchId).changes != 0; } catch (...) { return false; } }
 	virtual bool checkWatch(unsigned _watchId) { std::lock_guard l(m_filterLock); bool ret = false; try { ret = m_watches.at(_watchId).changes != 0; m_watches.at(_watchId).changes = 0; } catch (...) {} return ret; }
 
-	virtual PastMessages messages(unsigned _watchId) const { try { std::lock_guard l(m_filterLock); return messages(m_filters.at(m_watches.at(_watchId).id).filter); } catch (...) { return PastMessages(); } }
-	virtual PastMessages messages(MessageFilter const& _filter) const;
+	virtual LogEntries logs(unsigned _watchId) const { try { std::lock_guard l(m_filterLock); return logs(m_filters.at(m_watches.at(_watchId).id).filter); } catch (...) { return LogEntries(); } }
+	virtual LogEntries logs(LogFilter const& _filter) const;
 
 	// [EXTRA API]:
 
@@ -259,7 +258,7 @@ private:
 
 	/// Collate the changed filters for the bloom filter of the given pending transaction.
 	/// Insert any filters that are activated into @a o_changed.
-	void appendFromNewPending(h256 _pendingTransactionBloom, h256Set& o_changed) const;
+	void appendFromNewPending(LogBloom _pendingTransactionBloom, h256Set& o_changed) const;
 
 	/// Collate the changed filters for the hash of the given block.
 	/// Insert any filters that are activated into @a o_changed.
diff --git a/libethereum/EthereumHost.h b/libethereum/EthereumHost.h
index 18ba765aa..c732f2dc1 100644
--- a/libethereum/EthereumHost.h
+++ b/libethereum/EthereumHost.h
@@ -51,6 +51,7 @@ class BlockQueue;
 /**
  * @brief The EthereumHost class
  * @warning None of this is thread-safe. You have been warned.
+ * @doWork Syncs to peers and sends new blocks and transactions.
  */
 class EthereumHost: public p2p::HostCapability, Worker
 {
diff --git a/libethereum/Executive.cpp b/libethereum/Executive.cpp
index fb89eb21e..438505f1a 100644
--- a/libethereum/Executive.cpp
+++ b/libethereum/Executive.cpp
@@ -19,25 +19,22 @@
  * @date 2014
  */
 
+#include "Executive.h"
+
 #include 
 #include 
+#include 
 #include 
-#include "Executive.h"
+#include "Interface.h"
 #include "State.h"
 #include "ExtVM.h"
+#include "Precompiled.h"
 using namespace std;
 using namespace dev;
 using namespace dev::eth;
 
 #define ETH_VMTRACE 1
 
-Executive::~Executive()
-{
-	// TODO: Make safe.
-	delete m_ext;
-	delete m_vm;
-}
-
 u256 Executive::gasUsed() const
 {
 	return m_t.gas() - m_endGas;
@@ -58,20 +55,13 @@ bool Executive::setup(bytesConstRef _rlp)
 		BOOST_THROW_EXCEPTION(InvalidNonce(nonceReq, m_t.nonce()));
 	}
 
-	// Don't like transactions whose gas price is too low. NOTE: this won't stay here forever - it's just until we get a proper gas price discovery protocol going.
-	if (m_t.gasPrice() < m_s.m_currentBlock.minGasPrice)
-	{
-		clog(StateDetail) << "Offered gas-price is too low: Require >" << m_s.m_currentBlock.minGasPrice << " Got" << m_t.gasPrice();
-		BOOST_THROW_EXCEPTION(GasPriceTooLow());
-	}
-
 	// Check gas cost is enough.
-	u256 gasCost = m_t.data().size() * c_txDataGas + c_txGas;
+	auto gasCost = Interface::txGas(m_t.data());
 
 	if (m_t.gas() < gasCost)
 	{
 		clog(StateDetail) << "Not enough gas to pay for the transaction: Require >" << gasCost << " Got" << m_t.gas();
-		BOOST_THROW_EXCEPTION(OutOfGas());
+		BOOST_THROW_EXCEPTION(OutOfGas() << RequirementError((bigint)gasCost, (bigint)m_t.gas()));
 	}
 
 	u256 cost = m_t.value() + m_t.gas() * m_t.gasPrice();
@@ -80,14 +70,14 @@ bool Executive::setup(bytesConstRef _rlp)
 	if (m_s.balance(m_sender) < cost)
 	{
 		clog(StateDetail) << "Not enough cash: Require >" << cost << " Got" << m_s.balance(m_sender);
-		BOOST_THROW_EXCEPTION(NotEnoughCash() << RequirementError((int)cost, (int)m_s.balance(m_sender)));
+		BOOST_THROW_EXCEPTION(NotEnoughCash() << RequirementError((bigint)cost, (bigint)m_s.balance(m_sender)));
 	}
 
 	u256 startGasUsed = m_s.gasUsed();
 	if (startGasUsed + m_t.gas() > m_s.m_currentBlock.gasLimit)
 	{
 		clog(StateDetail) << "Too much gas used in this block: Require <" << (m_s.m_currentBlock.gasLimit - startGasUsed) << " Got" << m_t.gas();
-		BOOST_THROW_EXCEPTION(BlockGasLimitReached() << RequirementError((int)(m_s.m_currentBlock.gasLimit - startGasUsed), (int)m_t.gas()));
+		BOOST_THROW_EXCEPTION(BlockGasLimitReached() << RequirementError((bigint)(m_s.m_currentBlock.gasLimit - startGasUsed), (bigint)m_t.gas()));
 	}
 
 	// Increment associated nonce for sender.
@@ -97,42 +87,49 @@ bool Executive::setup(bytesConstRef _rlp)
 	clog(StateDetail) << "Paying" << formatBalance(cost) << "from sender (includes" << m_t.gas() << "gas at" << formatBalance(m_t.gasPrice()) << ")";
 	m_s.subBalance(m_sender, cost);
 
-	if (m_ms)
-	{
-		m_ms->from = m_sender;
-		m_ms->to = m_t.receiveAddress();
-		m_ms->value = m_t.value();
-		m_ms->input = m_t.data();
-	}
-
 	if (m_t.isCreation())
-		return create(m_sender, m_t.value(), m_t.gasPrice(), m_t.gas() - gasCost, &m_t.data(), m_sender);
+		return create(m_sender, m_t.value(), m_t.gasPrice(), m_t.gas() - (u256)gasCost, &m_t.data(), m_sender);
 	else
-		return call(m_t.receiveAddress(), m_sender, m_t.value(), m_t.gasPrice(), bytesConstRef(&m_t.data()), m_t.gas() - gasCost, m_sender);
+		return call(m_t.receiveAddress(), m_t.receiveAddress(), m_sender, m_t.value(), m_t.gasPrice(), bytesConstRef(&m_t.data()), m_t.gas() - (u256)gasCost, m_sender);
 }
 
-bool Executive::call(Address _receiveAddress, Address _senderAddress, u256 _value, u256 _gasPrice, bytesConstRef _data, u256 _gas, Address _originAddress)
+bool Executive::call(Address _receiveAddress, Address _codeAddress, Address _senderAddress, u256 _value, u256 _gasPrice, bytesConstRef _data, u256 _gas, Address _originAddress)
 {
+	m_isCreation = false;
 //	cnote << "Transferring" << formatBalance(_value) << "to receiver.";
 	m_s.addBalance(_receiveAddress, _value);
 
-	if (m_s.addressHasCode(_receiveAddress))
+	auto it = !(_codeAddress & ~h160(0xffffffff)) ? precompiled().find((unsigned)(u160)_codeAddress) : precompiled().end();
+	if (it != precompiled().end())
 	{
-		m_vm = new VM(_gas);
-		bytes const& c = m_s.code(_receiveAddress);
-		m_ext = new ExtVM(m_s, _receiveAddress, _senderAddress, _originAddress, _value, _gasPrice, _data, &c, m_ms);
+		bigint g = it->second.gas(_data);
+		if (_gas < g)
+		{
+			m_endGas = 0;
+			m_excepted = true;
+		}
+		else
+		{
+			m_endGas = (u256)(_gas - g);
+			m_precompiledOut = it->second.exec(_data);
+			m_out = &m_precompiledOut;
+		}
 	}
-	else
+	else if (m_s.addressHasCode(_codeAddress))
 	{
-		m_endGas = _gas;
-		if (m_ext)
-			m_ext->sub.logs.push_back(LogEntry(_receiveAddress, {u256((u160)_senderAddress) + 1}, bytes()));
+		m_vm = VMFactory::create(_gas);
+		bytes const& c = m_s.code(_codeAddress);
+		m_ext = make_shared(m_s, _receiveAddress, _senderAddress, _originAddress, _value, _gasPrice, _data, &c, m_depth);
 	}
+	else
+		m_endGas = _gas;
 	return !m_ext;
 }
 
 bool Executive::create(Address _sender, u256 _endowment, u256 _gasPrice, u256 _gas, bytesConstRef _init, Address _origin)
 {
+	m_isCreation = true;
+
 	// We can allow for the reverted state (i.e. that with which m_ext is constructed) to contain the m_newAddress, since
 	// we delete it explicitly if we decide we need to revert.
 	m_newAddress = right160(sha3(rlpList(_sender, m_s.transactionsFrom(_sender) - 1)));
@@ -141,17 +138,17 @@ bool Executive::create(Address _sender, u256 _endowment, u256 _gasPrice, u256 _g
 	m_s.m_cache[m_newAddress] = Account(m_s.balance(m_newAddress) + _endowment, Account::ContractConception);
 
 	// Execute _init.
-	m_vm = new VM(_gas);
-	m_ext = new ExtVM(m_s, m_newAddress, _sender, _origin, _endowment, _gasPrice, bytesConstRef(), _init, m_ms);
+	m_vm = VMFactory::create(_gas);
+	m_ext = make_shared(m_s, m_newAddress, _sender, _origin, _endowment, _gasPrice, bytesConstRef(), _init, m_depth);
 	return _init.empty();
 }
 
 OnOpFunc Executive::simpleTrace()
 {
-	return [](uint64_t steps, Instruction inst, bigint newMemSize, bigint gasCost, void* voidVM, void const* voidExt)
+	return [](uint64_t steps, Instruction inst, bigint newMemSize, bigint gasCost, VM* voidVM, ExtVMFace const* voidExt)
 	{
-		ExtVM const& ext = *(ExtVM const*)voidExt;
-		VM& vm = *(VM*)voidVM;
+		ExtVM const& ext = *static_cast(voidExt);
+		VM& vm = *voidVM;
 
 		ostringstream o;
 		o << endl << "    STACK" << endl;
@@ -170,15 +167,22 @@ bool Executive::go(OnOpFunc const& _onOp)
 {
 	if (m_vm)
 	{
+#if ETH_TIMED_EXECUTIONS
 		boost::timer t;
-		auto sgas = m_vm->gas();
-		bool revert = false;
+#endif
 		try
 		{
 			m_out = m_vm->go(*m_ext, _onOp);
-			if (m_ext)
-				m_endGas += min((m_t.gas() - m_endGas) / 2, m_ext->sub.refunds);
 			m_endGas = m_vm->gas();
+
+			if (m_isCreation)
+			{
+				if (m_out.size() * c_createDataGas <= m_endGas)
+					m_endGas -= m_out.size() * c_createDataGas;
+				else
+					m_out.reset();
+				m_s.m_cache[m_newAddress].setCode(m_out);
+			}
 		}
 		catch (StepsDone const&)
 		{
@@ -186,9 +190,10 @@ bool Executive::go(OnOpFunc const& _onOp)
 		}
 		catch (VMException const& _e)
 		{
-			clog(StateChat) << "Safe VM Exception: " << diagnostic_information(_e);
-			m_endGas = 0;//m_vm->gas();
-			revert = true;
+			clog(StateSafeExceptions) << "Safe VM Exception. " << diagnostic_information(_e);
+			m_endGas = 0;
+			m_excepted = true;
+			m_ext->revert();
 		}
 		catch (Exception const& _e)
 		{
@@ -200,46 +205,35 @@ bool Executive::go(OnOpFunc const& _onOp)
 			// TODO: AUDIT: check that this can never reasonably happen. Consider what to do if it does.
 			cwarn << "Unexpected std::exception in VM. This is probably unrecoverable. " << _e.what();
 		}
+#if ETH_TIMED_EXECUTIONS
 		cnote << "VM took:" << t.elapsed() << "; gas used: " << (sgas - m_endGas);
-
-		// Write state out only in the case of a non-excepted transaction.
-		if (revert)
-		{
-			m_ext->revert();
-			// Explicitly delete a newly created address - this will still be in the reverted state.
-			if (m_newAddress)
-			{
-				m_s.m_cache.erase(m_newAddress);
-				m_newAddress = Address();
-			}
-		}
+#endif
 	}
 	return true;
 }
 
-u256 Executive::gas() const
+/*u256 Executive::gas() const
 {
 	return m_vm ? m_vm->gas() : m_endGas;
-}
+}*/
 
 void Executive::finalize(OnOpFunc const&)
 {
-	if (m_t.isCreation() && m_newAddress && m_out.size())
-		// non-reverted creation - put code in place.
-		m_s.m_cache[m_newAddress].setCode(m_out);
+	// SSTORE refunds.
+	m_endGas += min((m_t.gas() - m_endGas) / 2, m_ext->sub.refunds);
 
-//	cnote << "Refunding" << formatBalance(m_endGas * m_ext->gasPrice) << "to origin (=" << m_endGas << "*" << formatBalance(m_ext->gasPrice) << ")";
+	//	cnote << "Refunding" << formatBalance(m_endGas * m_ext->gasPrice) << "to origin (=" << m_endGas << "*" << formatBalance(m_ext->gasPrice) << ")";
 	m_s.addBalance(m_sender, m_endGas * m_t.gasPrice());
 
 	u256 feesEarned = (m_t.gas() - m_endGas) * m_t.gasPrice();
 //	cnote << "Transferring" << formatBalance(gasSpent) << "to miner.";
 	m_s.addBalance(m_s.m_currentBlock.coinbaseAddress, feesEarned);
 
-	if (m_ms)
-		m_ms->output = m_out.toBytes();
-
 	// Suicides...
 	if (m_ext)
 		for (auto a: m_ext->sub.suicides)
 			m_s.m_cache[a].kill();
+
+	// Logs
+	m_logs = m_ext->sub.logs;
 }
diff --git a/libethereum/Executive.h b/libethereum/Executive.h
index 930c2859b..c5baada1d 100644
--- a/libethereum/Executive.h
+++ b/libethereum/Executive.h
@@ -25,30 +25,32 @@
 #include 
 #include 
 #include 
-#include 
+#include 
 #include "Transaction.h"
-#include "Manifest.h"
 
 namespace dev
 {
 namespace eth
 {
 
-class VM;
-class ExtVM;
 class State;
+class ExtVM;
+struct Manifest;
 
 struct VMTraceChannel: public LogChannel { static const char* name() { return "EVM"; } static const int verbosity = 11; };
 
+
 class Executive
 {
 public:
-	Executive(State& _s, Manifest* o_ms = nullptr): m_s(_s), m_ms(o_ms) {}
-	~Executive();
+	Executive(State& _s, unsigned _level): m_s(_s), m_depth(_level) {}
+	~Executive() = default;
+	Executive(Executive const&) = delete;
+	void operator=(Executive) = delete;
 
 	bool setup(bytesConstRef _transaction);
 	bool create(Address _txSender, u256 _endowment, u256 _gasPrice, u256 _gas, bytesConstRef _code, Address _originAddress);
-	bool call(Address _myAddress, Address _txSender, u256 _txValue, u256 _gasPrice, bytesConstRef _txData, u256 _gas, Address _originAddress);
+	bool call(Address _myAddress, Address _codeAddress, Address _txSender, u256 _txValue, u256 _gasPrice, bytesConstRef _txData, u256 _gas, Address _originAddress);
 	bool go(OnOpFunc const& _onOp = OnOpFunc());
 	void finalize(OnOpFunc const& _onOp = OnOpFunc());
 	u256 gasUsed() const;
@@ -57,25 +59,29 @@ public:
 
 	Transaction const& t() const { return m_t; }
 
-	u256 gas() const;
+	u256 endGas() const { return m_endGas; }
 
 	bytesConstRef out() const { return m_out; }
 	h160 newAddress() const { return m_newAddress; }
 	LogEntries const& logs() const { return m_logs; }
+	bool excepted() const { return m_excepted; }
 
-	VM const& vm() const { return *m_vm; }
-	State const& state() const { return m_s; }
+	VMFace const& vm() const { return *m_vm; }
 	ExtVM const& ext() const { return *m_ext; }
+	State const& state() const { return m_s; }
 
 private:
 	State& m_s;
-	ExtVM* m_ext = nullptr;	// TODO: make safe.
-	VM* m_vm = nullptr;
-	Manifest* m_ms = nullptr;
-	bytesConstRef m_out;
+	std::shared_ptr m_ext;
+	std::unique_ptr m_vm;
+	bytes m_precompiledOut;				///< Used for the output when there is no VM for a contract (i.e. precompiled).
+	bytesConstRef m_out;				///< Holds the copyable output.
 	Address m_newAddress;
 
 	Transaction m_t;
+	bool m_isCreation;
+	bool m_excepted = false;
+	unsigned m_depth = 0;
 	Address m_sender;
 	u256 m_endGas;
 
diff --git a/libethereum/ExtVM.cpp b/libethereum/ExtVM.cpp
index 4c343c162..fcd703b25 100644
--- a/libethereum/ExtVM.cpp
+++ b/libethereum/ExtVM.cpp
@@ -21,5 +21,37 @@
 
 #include "ExtVM.h"
 
-#pragma GCC diagnostic ignored "-Wunused-variable"
-namespace { char dummy; };
+#include "Executive.h"
+using namespace std;
+using namespace dev;
+using namespace dev::eth;
+
+bool ExtVM::call(Address _receiveAddress, u256 _txValue, bytesConstRef _txData, u256& io_gas, bytesRef _out, OnOpFunc const& _onOp, Address _myAddressOverride, Address _codeAddressOverride)
+{
+	Executive e(m_s, depth + 1);
+	if (!e.call(_receiveAddress, _codeAddressOverride ? _codeAddressOverride : _receiveAddress, _myAddressOverride ? _myAddressOverride : myAddress, _txValue, gasPrice, _txData, io_gas, origin))
+	{
+		e.go(_onOp);
+		sub += e.ext().sub;
+	}
+	io_gas = e.endGas();
+	e.out().copyTo(_out);
+
+	return !e.excepted();
+}
+
+h160 ExtVM::create(u256 _endowment, u256& io_gas, bytesConstRef _code, OnOpFunc const& _onOp)
+{
+	// Increment associated nonce for sender.
+	m_s.noteSending(myAddress);
+
+	Executive e(m_s, depth + 1);
+	if (!e.create(myAddress, _endowment, gasPrice, io_gas, _code, origin))
+	{
+		e.go(_onOp);
+		sub += e.ext().sub;
+	}
+	io_gas = e.endGas();
+	return e.newAddress();
+}
+
diff --git a/libethereum/ExtVM.h b/libethereum/ExtVM.h
index 24ce618ed..9699a68ad 100644
--- a/libethereum/ExtVM.h
+++ b/libethereum/ExtVM.h
@@ -39,8 +39,8 @@ class ExtVM: public ExtVMFace
 {
 public:
 	/// Full constructor.
-	ExtVM(State& _s, Address _myAddress, Address _caller, Address _origin, u256 _value, u256 _gasPrice, bytesConstRef _data, bytesConstRef _code, Manifest* o_ms, unsigned _depth = 0):
-		ExtVMFace(_myAddress, _caller, _origin, _value, _gasPrice, _data, _code.toBytes(), _s.m_previousBlock, _s.m_currentBlock, _depth), m_s(_s), m_origCache(_s.m_cache), m_ms(o_ms)
+	ExtVM(State& _s, Address _myAddress, Address _caller, Address _origin, u256 _value, u256 _gasPrice, bytesConstRef _data, bytesConstRef _code, unsigned _depth = 0):
+		ExtVMFace(_myAddress, _caller, _origin, _value, _gasPrice, _data, _code.toBytes(), _s.m_previousBlock, _s.m_currentBlock, _depth), m_s(_s), m_origCache(_s.m_cache)
 	{
 		m_s.ensureCached(_myAddress, true, true);
 	}
@@ -49,34 +49,16 @@ public:
 	virtual u256 store(u256 _n) override final { return m_s.storage(myAddress, _n); }
 
 	/// Write a value in storage.
-	virtual void setStore(u256 _n, u256 _v) override final { m_s.setStorage(myAddress, _n, _v); if (m_ms) m_ms->altered.push_back(_n); }
+	virtual void setStore(u256 _n, u256 _v) override final { m_s.setStorage(myAddress, _n, _v); }
 
 	/// Read address's code.
 	virtual bytes const& codeAt(Address _a) override final { return m_s.code(_a); }
 
 	/// Create a new contract.
-	virtual h160 create(u256 _endowment, u256* _gas, bytesConstRef _code, OnOpFunc const& _onOp = OnOpFunc()) override final
-	{
-		// Increment associated nonce for sender.
-		m_s.noteSending(myAddress);
-		if (m_ms)
-			m_ms->internal.resize(m_ms->internal.size() + 1);
-		auto ret = m_s.create(myAddress, _endowment, gasPrice, _gas, _code, origin, &sub, m_ms ? &(m_ms->internal.back()) : nullptr, _onOp, depth + 1);
-		if (m_ms && !m_ms->internal.back().from)
-			m_ms->internal.pop_back();
-		return ret;
-	}
+	virtual h160 create(u256 _endowment, u256& io_gas, bytesConstRef _code, OnOpFunc const& _onOp = {}) override final;
 
 	/// Create a new message call. Leave _myAddressOverride as the default to use the present address as caller.
-	virtual bool call(Address _receiveAddress, u256 _txValue, bytesConstRef _txData, u256* _gas, bytesRef _out, OnOpFunc const& _onOp = {}, Address _myAddressOverride = {}, Address _codeAddressOverride = {}) override final
-	{
-		if (m_ms)
-			m_ms->internal.resize(m_ms->internal.size() + 1);
-		auto ret = m_s.call(_receiveAddress, _codeAddressOverride ? _codeAddressOverride : _receiveAddress, _myAddressOverride ? _myAddressOverride : myAddress, _txValue, gasPrice, _txData, _gas, _out, origin, &sub, m_ms ? &(m_ms->internal.back()) : nullptr, _onOp, depth + 1);
-		if (m_ms && !m_ms->internal.back().from)
-			m_ms->internal.pop_back();
-		return ret;
-	}
+	virtual bool call(Address _receiveAddress, u256 _txValue, bytesConstRef _txData, u256& io_gas, bytesRef _out, OnOpFunc const& _onOp = {}, Address _myAddressOverride = {}, Address _codeAddressOverride = {}) override final;
 
 	/// Read address's balance.
 	virtual u256 balance(Address _a) override final { return m_s.balance(_a); }
@@ -96,14 +78,13 @@ public:
 
 	/// Revert any changes made (by any of the other calls).
 	/// @TODO check call site for the parent manifest being discarded.
-	virtual void revert() override final { if (m_ms) *m_ms = Manifest(); m_s.m_cache = m_origCache; }
+	virtual void revert() override final { m_s.m_cache = m_origCache; sub.clear(); }
 
 	State& state() const { return m_s; }
 
 private:
 	State& m_s;										///< A reference to the base state.
 	std::map m_origCache;			///< The cache of the address states (i.e. the externalities) as-was prior to the execution.
-	Manifest* m_ms;
 };
 
 }
diff --git a/libethereum/Interface.h b/libethereum/Interface.h
index 7ae650590..28ac26819 100644
--- a/libethereum/Interface.h
+++ b/libethereum/Interface.h
@@ -26,7 +26,7 @@
 #include 
 #include 
 #include 
-#include "MessageFilter.h"
+#include "LogFilter.h"
 #include "Transaction.h"
 #include "AccountDiff.h"
 #include "BlockDetails.h"
@@ -84,13 +84,13 @@ public:
 	virtual bytes codeAt(Address _a, int _block) const = 0;
 	virtual std::map storageAt(Address _a, int _block) const = 0;
 
-	// [MESSAGE API]
-
-	virtual PastMessages messages(unsigned _watchId) const = 0;
-	virtual PastMessages messages(MessageFilter const& _filter) const = 0;
+	// [LOGS API]
+	
+	virtual LogEntries logs(unsigned _watchId) const = 0;
+	virtual LogEntries logs(LogFilter const& _filter) const = 0;
 
 	/// Install, uninstall and query watches.
-	virtual unsigned installWatch(MessageFilter const& _filter) = 0;
+	virtual unsigned installWatch(LogFilter const& _filter) = 0;
 	virtual unsigned installWatch(h256 _filterId) = 0;
 	virtual void uninstallWatch(unsigned _watchId) = 0;
 	virtual bool peekWatch(unsigned _watchId) const = 0;
@@ -123,7 +123,7 @@ public:
 	virtual Addresses addresses(int _block) const = 0;
 
 	/// Get the fee associated for a transaction with the given data.
-	static u256 txGas(unsigned _dataCount, u256 _gas = 0) { return c_txDataGas * _dataCount + c_txGas + _gas; }
+	template  static bigint txGas(T const& _data, u256 _gas = 0) { bigint ret = c_txGas + _gas; for (auto i: _data) ret += i ? c_txDataNonZeroGas : c_txDataZeroGas; return ret; }
 
 	/// Get the remaining gas limit in this block.
 	virtual u256 gasLimitRemaining() const = 0;
@@ -175,12 +175,13 @@ class Watch: public boost::noncopyable
 public:
 	Watch() {}
 	Watch(Interface& _c, h256 _f): m_c(&_c), m_id(_c.installWatch(_f)) {}
-	Watch(Interface& _c, MessageFilter const& _tf): m_c(&_c), m_id(_c.installWatch(_tf)) {}
+	Watch(Interface& _c, LogFilter const& _tf): m_c(&_c), m_id(_c.installWatch(_tf)) {}
 	~Watch() { if (m_c) m_c->uninstallWatch(m_id); }
 
 	bool check() { return m_c ? m_c->checkWatch(m_id) : false; }
 	bool peek() { return m_c ? m_c->peekWatch(m_id) : false; }
-	PastMessages messages() const { return m_c->messages(m_id); }
+//	PastMessages messages() const { return m_c->messages(m_id); }
+	LogEntries logs() const { return m_c->logs(m_id); }
 
 private:
 	Interface* m_c = nullptr;
diff --git a/libethereum/LogFilter.cpp b/libethereum/LogFilter.cpp
new file mode 100644
index 000000000..81cb439ba
--- /dev/null
+++ b/libethereum/LogFilter.cpp
@@ -0,0 +1,81 @@
+/*
+	This file is part of cpp-ethereum.
+
+	cpp-ethereum is free software: you can redistribute it and/or modify
+	it under the terms of the GNU General Public License as published by
+	the Free Software Foundation, either version 3 of the License, or
+	(at your option) any later version.
+
+	cpp-ethereum is distributed in the hope that it will be useful,
+	but WITHOUT ANY WARRANTY; without even the implied warranty of
+	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+	GNU General Public License for more details.
+
+	You should have received a copy of the GNU General Public License
+	along with cpp-ethereum.  If not, see .
+*/
+/** @file LogFilter.cpp
+ * @author Gav Wood 
+ * @date 2014
+ */
+
+#include "LogFilter.h"
+
+#include 
+#include "State.h"
+using namespace std;
+using namespace dev;
+using namespace dev::eth;
+
+void LogFilter::streamRLP(RLPStream& _s) const
+{
+	_s.appendList(6) << m_addresses << m_topics << m_earliest << m_latest << m_max << m_skip;
+}
+
+h256 LogFilter::sha3() const
+{
+	RLPStream s;
+	streamRLP(s);
+	return dev::sha3(s.out());
+}
+
+bool LogFilter::matches(LogBloom _bloom) const
+{
+	if (m_addresses.size())
+	{
+		for (auto i: m_addresses)
+			if (_bloom.containsBloom<3>(dev::sha3(i)))
+				goto OK1;
+		return false;
+	}
+	OK1:
+	if (m_topics.size())
+	{
+		for (auto i: m_topics)
+			if (_bloom.containsBloom<3>(dev::sha3(i)))
+				goto OK2;
+		return false;
+	}
+	OK2:
+	return true;
+}
+
+bool LogFilter::matches(State const& _s, unsigned _i) const
+{
+	return matches(_s.receipt(_i)).size() > 0;
+}
+
+LogEntries LogFilter::matches(TransactionReceipt const& _m) const
+{
+	LogEntries ret;
+	for (LogEntry const& e: _m.log())
+	{
+		if (!m_addresses.empty() && !m_addresses.count(e.address))
+			continue;
+		for (auto const& t: m_topics)
+			if (!std::count(e.topics.begin(), e.topics.end(), t))
+				continue;
+		ret.push_back(e);
+	}
+	return ret;
+}
diff --git a/libethereum/MessageFilter.h b/libethereum/LogFilter.h
similarity index 55%
rename from libethereum/MessageFilter.h
rename to libethereum/LogFilter.h
index 5602d7a17..bda8e46a2 100644
--- a/libethereum/MessageFilter.h
+++ b/libethereum/LogFilter.h
@@ -14,7 +14,7 @@
 	You should have received a copy of the GNU General Public License
 	along with cpp-ethereum.  If not, see .
 */
-/** @file MessageFilter.h
+/** @file LogFilter.h
  * @author Gav Wood 
  * @date 2014
  */
@@ -24,7 +24,6 @@
 #include 
 #include 
 #include 
-#include "PastMessage.h"
 #include "TransactionReceipt.h"
 
 namespace dev
@@ -32,47 +31,8 @@ namespace dev
 namespace eth
 {
 
-struct Manifest;
 class State;
 
-class MessageFilter
-{
-public:
-	MessageFilter(int _earliest = 0, int _latest = -1, unsigned _max = 10, unsigned _skip = 0): m_earliest(_earliest), m_latest(_latest), m_max(_max), m_skip(_skip) {}
-
-	void streamRLP(RLPStream& _s) const;
-	h256 sha3() const;
-
-	int earliest() const { return m_earliest; }
-	int latest() const { return m_latest; }
-	unsigned max() const { return m_max; }
-	unsigned skip() const { return m_skip; }
-	bool matches(h256 _bloom) const;
-	bool matches(State const& _s, unsigned _i) const;
-	PastMessages matches(Manifest const& _m, unsigned _i) const;
-
-	MessageFilter from(Address _a) { m_from.insert(_a); return *this; }
-	MessageFilter to(Address _a) { m_to.insert(_a); return *this; }
-	MessageFilter altered(Address _a, u256 _l) { m_stateAltered.insert(std::make_pair(_a, _l)); return *this; }
-	MessageFilter altered(Address _a) { m_altered.insert(_a); return *this; }
-	MessageFilter withMax(unsigned _m) { m_max = _m; return *this; }
-	MessageFilter withSkip(unsigned _m) { m_skip = _m; return *this; }
-	MessageFilter withEarliest(int _e) { m_earliest = _e; return *this; }
-	MessageFilter withLatest(int _e) { m_latest = _e; return *this; }
-
-private:
-	bool matches(Manifest const& _m, std::vector _p, Address _o, PastMessages _limbo, PastMessages& o_ret) const;
-
-	std::set
m_from; - std::set
m_to; - std::set> m_stateAltered; - std::set
m_altered; - int m_earliest = 0; - int m_latest = -1; - unsigned m_max; - unsigned m_skip; -}; - class LogFilter { public: @@ -90,7 +50,6 @@ public: LogEntries matches(TransactionReceipt const& _r) const; LogFilter address(Address _a) { m_addresses.insert(_a); return *this; } - LogFilter from(Address _a) { return topic(u256((u160)_a) + 1); } LogFilter topic(h256 const& _t) { m_topics.insert(_t); return *this; } LogFilter withMax(unsigned _m) { m_max = _m; return *this; } LogFilter withSkip(unsigned _m) { m_skip = _m; return *this; } diff --git a/libethereum/Manifest.h b/libethereum/Manifest.h deleted file mode 100644 index e0e512c92..000000000 --- a/libethereum/Manifest.h +++ /dev/null @@ -1,73 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - cpp-ethereum is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with cpp-ethereum. If not, see . -*/ -/** @file Manifest.h - * @author Gav Wood - * @date 2014 - */ - -#pragma once - -#include -#include -#include -#include - -namespace dev -{ -namespace eth -{ - -struct Manifest; -using Manifests = std::vector; - -/** - * @brief A record of the state-interaction of a transaction/call/create. - */ -struct Manifest -{ - Manifest() {} - Manifest(bytesConstRef _r); - void streamRLP(RLPStream& _s) const; - - h256 bloom() const { h256 ret = from.bloom() | to.bloom(); for (auto const& i: internal) ret |= i.bloom(); for (auto const& i: altered) ret |= h256(i).bloom(); return ret; } - - std::string toString(unsigned _indent = 0) const - { - std::ostringstream oss; - oss << std::string(_indent * 3, ' ') << from << " -> " << to << " [" << value << "]: {"; - if (internal.size()) - { - oss << std::endl; - for (auto const& m: internal) - oss << m.toString(_indent + 1) << std::endl; - oss << std::string(_indent * 3, ' '); - } - oss << "} I:" << toHex(input) << "; O:" << toHex(output); - return oss.str(); - } - - Address from; - Address to; - u256 value; - u256s altered; - bytes input; - bytes output; - Manifests internal; -}; - -} -} diff --git a/libethereum/MessageFilter.cpp b/libethereum/MessageFilter.cpp deleted file mode 100644 index b04d213f9..000000000 --- a/libethereum/MessageFilter.cpp +++ /dev/null @@ -1,206 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - cpp-ethereum is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with cpp-ethereum. If not, see . -*/ -/** @file MessageFilter.cpp - * @author Gav Wood - * @date 2014 - */ - -#include "MessageFilter.h" - -#include -#include "State.h" -using namespace std; -using namespace dev; -using namespace dev::eth; - -void MessageFilter::streamRLP(RLPStream& _s) const -{ - _s.appendList(8) << m_from << m_to << m_stateAltered << m_altered << m_earliest << m_latest << m_max << m_skip; -} - -h256 MessageFilter::sha3() const -{ - RLPStream s; - streamRLP(s); - return dev::sha3(s.out()); -} - -bool MessageFilter::matches(h256 _bloom) const -{ - auto have = [=](Address const& a) { return _bloom.contains(a.bloom()); }; - if (m_from.size()) - { - for (auto i: m_from) - if (have(i)) - goto OK1; - return false; - } - OK1: - if (m_to.size()) - { - for (auto i: m_to) - if (have(i)) - goto OK2; - return false; - } - OK2: - if (m_stateAltered.size() || m_altered.size()) - { - for (auto i: m_altered) - if (have(i)) - goto OK3; - for (auto i: m_stateAltered) - if (have(i.first) && _bloom.contains(h256(i.second).bloom())) - goto OK3; - return false; - } - OK3: - return true; -} - -bool MessageFilter::matches(State const& _s, unsigned _i) const -{ - h256 b = _s.changesFromPending(_i).bloom(); - if (!matches(b)) - return false; - - Transaction t = _s.pending()[_i]; - if (!m_to.empty() && !m_to.count(t.receiveAddress())) - return false; - if (!m_from.empty() && !m_from.count(t.sender())) - return false; - if (m_stateAltered.empty() && m_altered.empty()) - return true; - StateDiff d = _s.pendingDiff(_i); - if (!m_altered.empty()) - { - for (auto const& s: m_altered) - if (d.accounts.count(s)) - return true; - return false; - } - if (!m_stateAltered.empty()) - { - for (auto const& s: m_stateAltered) - if (d.accounts.count(s.first) && d.accounts.at(s.first).storage.count(s.second)) - return true; - return false; - } - return true; -} - -PastMessages MessageFilter::matches(Manifest const& _m, unsigned _i) const -{ - PastMessages ret; - matches(_m, vector(1, _i), _m.from, PastMessages(), ret); - return ret; -} - -bool MessageFilter::matches(Manifest const& _m, vector _p, Address _o, PastMessages _limbo, PastMessages& o_ret) const -{ - bool ret; - - if ((m_from.empty() || m_from.count(_m.from)) && (m_to.empty() || m_to.count(_m.to))) - _limbo.push_back(PastMessage(_m, _p, _o)); - - // Handle limbos, by checking against all addresses in alteration. - bool alters = m_altered.empty() && m_stateAltered.empty(); - alters = alters || m_altered.count(_m.from) || m_altered.count(_m.to); - - if (!alters) - for (auto const& i: _m.altered) - if (m_altered.count(_m.to) || m_stateAltered.count(make_pair(_m.to, i))) - { - alters = true; - break; - } - // If we do alter stuff, - if (alters) - { - o_ret += _limbo; - _limbo.clear(); - ret = true; - } - - _p.push_back(0); - for (auto const& m: _m.internal) - { - if (matches(m, _p, _o, _limbo, o_ret)) - { - _limbo.clear(); - ret = true; - } - _p.back()++; - } - - return ret; -} - - - -void LogFilter::streamRLP(RLPStream& _s) const -{ - _s.appendList(6) << m_addresses << m_topics << m_earliest << m_latest << m_max << m_skip; -} - -h256 LogFilter::sha3() const -{ - RLPStream s; - streamRLP(s); - return dev::sha3(s.out()); -} - -bool LogFilter::matches(LogBloom _bloom) const -{ - if (m_addresses.size()) - { - for (auto i: m_addresses) - if (_bloom.containsBloom<3>(dev::sha3(i))) - goto OK1; - return false; - } - OK1: - if (m_topics.size()) - { - for (auto i: m_topics) - if (_bloom.containsBloom<3>(dev::sha3(i))) - goto OK2; - return false; - } - OK2: - return true; -} - -bool LogFilter::matches(State const& _s, unsigned _i) const -{ - return matches(_s.receipt(_i)).size() > 0; -} - -LogEntries LogFilter::matches(TransactionReceipt const& _m) const -{ - LogEntries ret; - for (LogEntry const& e: _m.log()) - { - if (!m_addresses.empty() && !m_addresses.count(e.address)) - continue; - for (auto const& t: m_topics) - if (!e.topics.count(t)) - continue; - ret.push_back(e); - } - return ret; -} diff --git a/libethereum/PastMessage.h b/libethereum/PastMessage.h deleted file mode 100644 index 6446eff5a..000000000 --- a/libethereum/PastMessage.h +++ /dev/null @@ -1,56 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - cpp-ethereum is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with cpp-ethereum. If not, see . -*/ -/** @file PastMessage.h - * @author Gav Wood - * @date 2014 - */ - -#pragma once - -#include -#include -#include "Manifest.h" - -namespace dev -{ -namespace eth -{ - -struct PastMessage -{ - PastMessage(Manifest const& _m, std::vector _path, Address _o): to(_m.to), from(_m.from), value(_m.value), input(_m.input), output(_m.output), path(_path), origin(_o) {} - - PastMessage& polish(h256 _b, u256 _ts, unsigned _n, Address _coinbase) { block = _b; timestamp = _ts; number = _n; coinbase = _coinbase; return *this; } - - Address to; ///< The receiving address of the transaction. Address() in the case of a creation. - Address from; ///< The receiving address of the transaction. Address() in the case of a creation. - u256 value; ///< The value associated with the call. - bytes input; ///< The data associated with the message, or the initialiser if it's a creation transaction. - bytes output; ///< The data returned by the message, or the body code if it's a creation transaction. - - std::vector path; ///< Call path into the block transaction. size() is always > 0. First item is the transaction index in the block. - Address origin; ///< Originating sender of the transaction. - Address coinbase; ///< Block coinbase. - h256 block; ///< Block hash. - u256 timestamp; ///< Block timestamp. - unsigned number; ///< Block number. -}; - -typedef std::vector PastMessages; - -} -} diff --git a/libethereum/Precompiled.cpp b/libethereum/Precompiled.cpp new file mode 100644 index 000000000..1861385da --- /dev/null +++ b/libethereum/Precompiled.cpp @@ -0,0 +1,88 @@ +/* + This file is part of cpp-ethereum. + + cpp-ethereum is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + cpp-ethereum is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with cpp-ethereum. If not, see . +*/ +/** @file Precompiled.cpp + * @author Gav Wood + * @date 2014 + */ + +#include "Precompiled.h" + +#include +#include +#include +using namespace std; +using namespace dev; +using namespace dev::eth; + +static bytes ecrecoverCode(bytesConstRef _in) +{ + struct inType + { + h256 hash; + h256 v; + h256 r; + h256 s; + } in; + + memcpy(&in, _in.data(), min(_in.size(), sizeof(in))); + + h256 ret; + + if ((u256)in.v > 28) + return ret.asBytes(); + SignatureStruct sig(in.r, in.s, (byte)((int)(u256)in.v - 27)); + if (!sig.isValid()) + return ret.asBytes(); + + try + { + ret = dev::sha3(recover(sig, in.hash)); + } + catch (...) {} + + memset(ret.data(), 0, 12); + return ret.asBytes(); +} + +static bytes sha256Code(bytesConstRef _in) +{ + bytes ret(32); + sha256(_in, &ret); + return ret; +} + +static bytes ripemd160Code(bytesConstRef _in) +{ + bytes ret(32); + ripemd160(_in, &ret); + // leaves the 20-byte hash left-aligned. we want it right-aligned: + memmove(ret.data() + 12, ret.data(), 20); + memset(ret.data(), 0, 12); + return ret; +} + +static const std::map c_precompiled = +{ + { 1, { [](bytesConstRef) -> bigint { return (bigint)500; }, ecrecoverCode }}, + { 2, { [](bytesConstRef i) -> bigint { return (bigint)50 + (i.size() + 31) / 32 * 50; }, sha256Code }}, + { 3, { [](bytesConstRef i) -> bigint { return (bigint)50 + (i.size() + 31) / 32 * 50; }, ripemd160Code }} +}; + +std::map const& dev::eth::precompiled() +{ + return c_precompiled; +} diff --git a/libethereum/Precompiled.h b/libethereum/Precompiled.h new file mode 100644 index 000000000..c65cd9a63 --- /dev/null +++ b/libethereum/Precompiled.h @@ -0,0 +1,44 @@ +/* + This file is part of cpp-ethereum. + + cpp-ethereum is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + cpp-ethereum is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with cpp-ethereum. If not, see . +*/ +/** @file Precompiled.h + * @author Gav Wood + * @date 2014 + */ + +#pragma once + +#include +#include +#include + +namespace dev +{ +namespace eth +{ + +/// Information structure regarding an account that is precompiled (i.e. 1, 2, 3). +struct PrecompiledAddress +{ + std::function gas; + std::function exec; +}; + +/// Info on precompiled contract accounts baked into the protocol. +std::map const& precompiled(); + +} +} diff --git a/libethereum/State.cpp b/libethereum/State.cpp index 5eb315439..64210f20a 100644 --- a/libethereum/State.cpp +++ b/libethereum/State.cpp @@ -21,17 +21,20 @@ #include "State.h" -#include -#include +#include #include +#include +#include #include #include #include #include -#include +#include #include "BlockChain.h" #include "Defaults.h" #include "ExtVM.h" +#include "Executive.h" +#include "CachedAddressState.h" using namespace std; using namespace dev; using namespace dev::eth; @@ -40,53 +43,6 @@ using namespace dev::eth; static const u256 c_blockReward = 1500 * finney; -void ecrecoverCode(bytesConstRef _in, bytesRef _out) -{ - struct inType - { - h256 hash; - h256 v; - h256 r; - h256 s; - } in; - - h256 ret; - - memcpy(&in, _in.data(), min(_in.size(), sizeof(in))); - - byte pubkey[65]; - int pubkeylen = 65; - secp256k1_start(); - if (secp256k1_ecdsa_recover_compact(in.hash.data(), 32, in.r.data(), pubkey, &pubkeylen, 0, (int)(u256)in.v - 27)) - ret = dev::sha3(bytesConstRef(&(pubkey[1]), 64)); - - memset(ret.data(), 0, 12); - memcpy(_out.data(), &ret, min(_out.size(), sizeof(ret))); -} - -void sha256Code(bytesConstRef _in, bytesRef _out) -{ - h256 ret; - sha256(_in, bytesRef(ret.data(), 32)); - memcpy(_out.data(), &ret, min(_out.size(), sizeof(ret))); -} - -void ripemd160Code(bytesConstRef _in, bytesRef _out) -{ - h256 ret; - ripemd160(_in, bytesRef(ret.data(), 32)); - memset(_out.data(), 0, std::min(12, _out.size())); - if (_out.size() > 12) - memcpy(_out.data() + 12, &ret, min(_out.size() - 12, sizeof(ret))); -} - -const std::map State::c_precompiled = -{ - { 1, { 500, ecrecoverCode }}, - { 2, { 100, sha256Code }}, - { 3, { 100, ripemd160Code }} -}; - OverlayDB State::openDB(std::string _path, bool _killExisting) { if (_path.empty()) @@ -113,8 +69,6 @@ State::State(Address _coinbaseAddress, OverlayDB const& _db): m_ourAddress(_coinbaseAddress), m_blockReward(c_blockReward) { - secp256k1_start(); - // Initialise to the state entailed by the genesis block; this guarantees the trie is built correctly. m_state.init(); @@ -138,8 +92,6 @@ State::State(OverlayDB const& _db, BlockChain const& _bc, h256 _h): m_state(&m_db), m_blockReward(c_blockReward) { - secp256k1_start(); - // TODO THINK: is this necessary? m_state.init(); @@ -222,89 +174,6 @@ Address State::nextActiveAddress(Address _a) const return (*it).first; } -// TODO: repot -struct CachedAddressState -{ - CachedAddressState(std::string const& _rlp, Account const* _s, OverlayDB const* _o): rS(_rlp), r(rS), s(_s), o(_o) {} - - bool exists() const - { - return (r && (!s || s->isAlive())) || (s && s->isAlive()); - } - - u256 balance() const - { - return r ? s ? s->balance() : r[1].toInt() : 0; - } - - u256 nonce() const - { - return r ? s ? s->nonce() : r[0].toInt() : 0; - } - - bytes code() const - { - if (s && s->codeCacheValid()) - return s->code(); - h256 h = r ? s ? s->codeHash() : r[3].toHash() : EmptySHA3; - return h == EmptySHA3 ? bytes() : asBytes(o->lookup(h)); - } - - std::map storage() const - { - std::map ret; - if (r) - { - TrieDB memdb(const_cast(o), r[2].toHash()); // promise we won't alter the overlay! :) - for (auto const& j: memdb) - ret[j.first] = RLP(j.second).toInt(); - } - if (s) - for (auto const& j: s->storageOverlay()) - if ((!ret.count(j.first) && j.second) || (ret.count(j.first) && ret.at(j.first) != j.second)) - ret[j.first] = j.second; - return ret; - } - - AccountDiff diff(CachedAddressState const& _c) - { - AccountDiff ret; - ret.exist = Diff(exists(), _c.exists()); - ret.balance = Diff(balance(), _c.balance()); - ret.nonce = Diff(nonce(), _c.nonce()); - ret.code = Diff(code(), _c.code()); - auto st = storage(); - auto cst = _c.storage(); - auto it = st.begin(); - auto cit = cst.begin(); - while (it != st.end() || cit != cst.end()) - { - if (it != st.end() && cit != cst.end() && it->first == cit->first && (it->second || cit->second) && (it->second != cit->second)) - ret.storage[it->first] = Diff(it->second, cit->second); - else if (it != st.end() && (cit == cst.end() || it->first < cit->first) && it->second) - ret.storage[it->first] = Diff(it->second, 0); - else if (cit != cst.end() && (it == st.end() || it->first > cit->first) && cit->second) - ret.storage[cit->first] = Diff(0, cit->second); - if (it == st.end()) - ++cit; - else if (cit == cst.end()) - ++it; - else if (it->first < cit->first) - ++it; - else if (it->first > cit->first) - ++cit; - else - ++it, ++cit; - } - return ret; - } - - std::string rS; - RLP r; - Account const* s; - OverlayDB const* o; -}; - StateDiff State::diff(State const& _c) const { StateDiff ret; @@ -325,8 +194,8 @@ StateDiff State::diff(State const& _c) const for (auto i: _c.m_cache) ads.insert(i.first); - cnote << *this; - cnote << _c; +// cnote << *this; +// cnote << _c; for (auto i: ads) { @@ -498,7 +367,6 @@ void State::resetCurrent() m_currentBlock.timestamp = time(0); m_currentBlock.transactionsRoot = h256(); m_currentBlock.sha3Uncles = h256(); - m_currentBlock.minGasPrice = 10 * szabo; m_currentBlock.populateFromParent(m_previousBlock); // Update timestamp according to clock. @@ -537,10 +405,10 @@ bool State::cull(TransactionQueue& _tq) const return ret; } -h256s State::sync(TransactionQueue& _tq, bool* o_transactionQueueChanged) +h512s State::sync(TransactionQueue& _tq, bool* o_transactionQueueChanged) { // TRANSACTIONS - h256s ret; + h512s ret; auto ts = _tq.transactions(); for (int goodTxs = 1; goodTxs;) @@ -553,10 +421,12 @@ h256s State::sync(TransactionQueue& _tq, bool* o_transactionQueueChanged) try { uncommitToMine(); +// boost::timer t; execute(i.second); - ret.push_back(m_receipts.back().changes().bloom()); + ret.push_back(m_receipts.back().bloom()); _tq.noteGood(i); ++goodTxs; +// cnote << "TX took:" << t.elapsed() * 1000; } catch (InvalidNonce const& in) { @@ -662,6 +532,12 @@ u256 State::enact(bytesConstRef _block, BlockChain const* _bc, bool _checkNonce) BOOST_THROW_EXCEPTION(InvalidReceiptsStateRoot()); } + if (m_currentBlock.logBloom != logBloom()) + { + cwarn << "Bad log bloom!"; + BOOST_THROW_EXCEPTION(InvalidLogBloom()); + } + // Initialise total difficulty calculation. u256 tdIncrease = m_currentBlock.difficulty; @@ -754,7 +630,7 @@ bool State::amIJustParanoid(BlockChain const& _bc) // Compile block: RLPStream block; block.appendList(3); - m_currentBlock.streamRLP(block, true); + m_currentBlock.streamRLP(block, WithNonce); block.appendRaw(m_currentTxs); block.appendRaw(m_currentUncles); @@ -781,19 +657,9 @@ bool State::amIJustParanoid(BlockChain const& _bc) return false; } -h256 State::oldBloom() const -{ - h256 ret = m_currentBlock.coinbaseAddress.bloom(); - for (auto const& i: m_receipts) - ret |= i.changes().bloom(); - return ret; -} - LogBloom State::logBloom() const { LogBloom ret; - auto sa = sha3(m_currentBlock.coinbaseAddress.ref()); - ret.shiftBloom<3>(sa); for (TransactionReceipt const& i: m_receipts) ret |= i.bloom(); return ret; @@ -805,7 +671,7 @@ void State::commitToMine(BlockChain const& _bc) { uncommitToMine(); - cnote << "Committing to mine on block" << m_previousBlock.hash.abridged(); +// cnote << "Committing to mine on block" << m_previousBlock.hash.abridged(); #ifdef ETH_PARANOIA commit(); cnote << "Pre-reward stateRoot:" << m_state.root(); @@ -831,7 +697,7 @@ void State::commitToMine(BlockChain const& _bc) if (!knownUncles.count(u)) // ignore any uncles/mainline blocks that we know about. { BlockInfo ubi(_bc.block(u)); - ubi.streamRLP(unclesData, true); + ubi.streamRLP(unclesData, WithNonce); ++unclesCount; uncleAddresses.push_back(ubi.coinbaseAddress); } @@ -880,7 +746,7 @@ void State::commitToMine(BlockChain const& _bc) // Commit any and all changes to the trie that are in the cache, then update the state root accordingly. commit(); - cnote << "Post-reward stateRoot:" << m_state.root().abridged(); +// cnote << "Post-reward stateRoot:" << m_state.root().abridged(); // cnote << m_state; // cnote << *this; @@ -895,13 +761,13 @@ MineInfo State::mine(unsigned _msTimeout, bool _turbo) m_currentBlock.difficulty = m_currentBlock.calculateDifficulty(m_previousBlock); // TODO: Miner class that keeps dagger between mine calls (or just non-polling mining). - auto ret = m_pow.mine(/*out*/m_currentBlock.nonce, m_currentBlock.headerHashWithoutNonce(), m_currentBlock.difficulty, _msTimeout, true, _turbo); + auto ret = m_pow.mine(/*out*/m_currentBlock.nonce, m_currentBlock.headerHash(WithoutNonce), m_currentBlock.difficulty, _msTimeout, true, _turbo); if (!ret.completed) m_currentBytes.clear(); else { - cnote << "Completed" << m_currentBlock.headerHashWithoutNonce().abridged() << m_currentBlock.nonce.abridged() << m_currentBlock.difficulty << ProofOfWork::verify(m_currentBlock.headerHashWithoutNonce(), m_currentBlock.nonce, m_currentBlock.difficulty); + cnote << "Completed" << m_currentBlock.headerHash(WithoutNonce).abridged() << m_currentBlock.nonce.abridged() << m_currentBlock.difficulty << ProofOfWork::verify(m_currentBlock.headerHash(WithoutNonce), m_currentBlock.nonce, m_currentBlock.difficulty); } return ret; @@ -915,7 +781,7 @@ void State::completeMine() // Compile block: RLPStream ret; ret.appendList(3); - m_currentBlock.streamRLP(ret, true); + m_currentBlock.streamRLP(ret, WithNonce); ret.appendRaw(m_currentTxs); ret.appendRaw(m_currentUncles); ret.swapOut(m_currentBytes); @@ -1093,7 +959,7 @@ bool State::isTrieGood(bool _enforceRefs, bool _requireNoLeftOvers) const return false; } } - catch (InvalidTrie) + catch (InvalidTrie const&) { cwarn << "BAD TRIE" << (e ? "[enforced" : "[unenforced") << "refs]"; cnote << m_db.keys(); @@ -1118,9 +984,7 @@ u256 State::execute(bytesConstRef _rlp, bytes* o_output, bool _commit) auto h = rootHash(); #endif - Manifest ms; - - Executive e(*this, &ms); + Executive e(*this, 0); e.setup(_rlp); u256 startGasUsed = gasUsed(); @@ -1170,154 +1034,11 @@ u256 State::execute(bytesConstRef _rlp, bytes* o_output, bool _commit) // Add to the user-originated transactions that we've executed. m_transactions.push_back(e.t()); - m_receipts.push_back(TransactionReceipt(rootHash(), startGasUsed + e.gasUsed(), e.logs(), ms)); + m_receipts.push_back(TransactionReceipt(rootHash(), startGasUsed + e.gasUsed(), e.logs())); m_transactionSet.insert(e.t().sha3()); return e.gasUsed(); } -bool State::call(Address _receiveAddress, Address _codeAddress, Address _senderAddress, u256 _value, u256 _gasPrice, bytesConstRef _data, u256* _gas, bytesRef _out, Address _originAddress, SubState* o_sub, Manifest* o_ms, OnOpFunc const& _onOp, unsigned _level) -{ - if (!_originAddress) - _originAddress = _senderAddress; - -// cnote << "Transferring" << formatBalance(_value) << "to receiver."; - addBalance(_receiveAddress, _value); - - if (o_ms) - { - o_ms->from = _senderAddress; - o_ms->to = _receiveAddress; - o_ms->value = _value; - o_ms->input = _data.toBytes(); - } - - auto it = !(_codeAddress & ~h160(0xffffffff)) ? c_precompiled.find((unsigned)(u160)_codeAddress) : c_precompiled.end(); - if (it != c_precompiled.end()) - { - if (*_gas < it->second.gas) - { - *_gas = 0; - return false; - } - - *_gas -= it->second.gas; - it->second.exec(_data, _out); - } - else if (addressHasCode(_codeAddress)) - { - VM vm(*_gas); - ExtVM evm(*this, _receiveAddress, _senderAddress, _originAddress, _value, _gasPrice, _data, &code(_codeAddress), o_ms, _level); - bool revert = false; - - try - { - auto out = vm.go(evm, _onOp); - memcpy(_out.data(), out.data(), std::min(out.size(), _out.size())); - if (o_sub) - *o_sub += evm.sub; - if (o_ms) - o_ms->output = out.toBytes(); - *_gas = vm.gas(); - } - catch (VMException const& _e) - { - clog(StateChat) << "Safe VM Exception: " << diagnostic_information(_e); - revert = true; - *_gas = 0; - } - catch (Exception const& _e) - { - cwarn << "Unexpected exception in VM: " << diagnostic_information(_e) << ". This is exceptionally bad."; - // TODO: use fallback known-safe VM. - } - catch (std::exception const& _e) - { - cwarn << "Unexpected exception in VM: " << _e.what() << ". This is exceptionally bad."; - // TODO: use fallback known-safe VM. - } - - // Write state out only in the case of a non-excepted transaction. - if (revert) - evm.revert(); - - return !revert; - } - else - { - // non-contract call - if (o_sub) - o_sub->logs.push_back(LogEntry(_receiveAddress, {u256((u160)_senderAddress) + 1}, bytes())); - } - return true; -} - -h160 State::create(Address _sender, u256 _endowment, u256 _gasPrice, u256* _gas, bytesConstRef _code, Address _origin, SubState* o_sub, Manifest* o_ms, OnOpFunc const& _onOp, unsigned _level) -{ - if (!_origin) - _origin = _sender; - - if (o_ms) - { - o_ms->from = _sender; - o_ms->to = Address(); - o_ms->value = _endowment; - o_ms->input = _code.toBytes(); - } - - Address newAddress = right160(sha3(rlpList(_sender, transactionsFrom(_sender) - 1))); - - // Set up new account... - m_cache[newAddress] = Account(balance(newAddress) + _endowment, Account::ContractConception); - - // Execute init code. - VM vm(*_gas); - ExtVM evm(*this, newAddress, _sender, _origin, _endowment, _gasPrice, bytesConstRef(), _code, o_ms, _level); - bool revert = false; - bytesConstRef out; - - try - { - out = vm.go(evm, _onOp); - if (o_ms) - o_ms->output = out.toBytes(); - if (o_sub) - *o_sub += evm.sub; - *_gas = vm.gas(); - } - catch (VMException const& _e) - { - clog(StateChat) << "Safe VM Exception: " << diagnostic_information(_e); - revert = true; - *_gas = 0; - } - catch (Exception const& _e) - { - // TODO: AUDIT: check that this can never reasonably happen. Consider what to do if it does. - cwarn << "Unexpected exception in VM. There may be a bug in this implementation. " << diagnostic_information(_e); - } - catch (std::exception const& _e) - { - // TODO: AUDIT: check that this can never reasonably happen. Consider what to do if it does. - cwarn << "Unexpected std::exception in VM. This is probably unrecoverable. " << _e.what(); - } - - // TODO: CHECK: AUDIT: IS THIS CORRECT?! (esp. given account created prior to revertion init.) - - // Write state out only in the case of a non-out-of-gas transaction. - if (revert) - { - evm.revert(); - m_cache.erase(newAddress); - newAddress = Address(); - } - else - // Set code. - if (addressInUse(newAddress)) - m_cache[newAddress].setCode(out); - - return newAddress; -} - State State::fromPending(unsigned _i) const { State ret = *this; diff --git a/libethereum/State.h b/libethereum/State.h index d3c7fa313..611647566 100644 --- a/libethereum/State.h +++ b/libethereum/State.h @@ -36,7 +36,6 @@ #include "Account.h" #include "Transaction.h" #include "TransactionReceipt.h" -#include "Executive.h" #include "AccountDiff.h" namespace dev @@ -52,12 +51,7 @@ class BlockChain; struct StateChat: public LogChannel { static const char* name() { return "-S-"; } static const int verbosity = 4; }; struct StateTrace: public LogChannel { static const char* name() { return "=S="; } static const int verbosity = 7; }; struct StateDetail: public LogChannel { static const char* name() { return "/S/"; } static const int verbosity = 14; }; - -struct PrecompiledAddress -{ - unsigned gas; - std::function exec; -}; +struct StateSafeExceptions: public LogChannel { static const char* name() { return "(S)"; } static const int verbosity = 21; }; /** * @brief Model of the current state of the ledger. @@ -147,7 +141,7 @@ public: /// @returns a list of bloom filters one for each transaction placed from the queue into the state. /// @a o_transactionQueueChanged boolean pointer, the value of which will be set to true if the transaction queue /// changed and the pointer is non-null - h256s sync(TransactionQueue& _tq, bool* o_transactionQueueChanged = nullptr); + h512s sync(TransactionQueue& _tq, bool* o_transactionQueueChanged = nullptr); /// Like sync but only operate on _tq, killing the invalid/old ones. bool cull(TransactionQueue& _tq) const; @@ -211,15 +205,6 @@ public: /// Get the list of pending transactions. Transactions const& pending() const { return m_transactions; } - /// Get the list of pending transactions. TODO: PoC-7: KILL - Manifest changesFromPending(unsigned _i) const { return m_receipts[_i].changes(); } - - /// Get the bloom filter of all changes happened in the block. TODO: PoC-7: KILL - h256 oldBloom() const; - - /// Get the bloom filter of a particular transaction that happened in the block. TODO: PoC-7: KILL - h256 oldBloom(unsigned _i) const { return m_receipts[_i].changes().bloom(); } - /// Get the transaction receipt for the transaction of the given index. TransactionReceipt const& receipt(unsigned _i) const { return m_receipts[_i]; } @@ -279,17 +264,6 @@ private: /// Throws on failure. u256 enact(bytesConstRef _block, BlockChain const* _bc = nullptr, bool _checkNonce = true); - // Two priviledged entry points for the VM (these don't get added to the Transaction lists): - // We assume all instrinsic fees are paid up before this point. - - /// Execute a contract-creation transaction. - h160 create(Address _txSender, u256 _endowment, u256 _gasPrice, u256* _gas, bytesConstRef _code, Address _originAddress = Address(), SubState* o_sub = nullptr, Manifest* o_ms = nullptr, OnOpFunc const& _onOp = OnOpFunc(), unsigned _level = 0); - - /// Execute a call. - /// @a _gas points to the amount of gas to use for the call, and will lower it accordingly. - /// @returns false if the call ran out of gas before completion. true otherwise. - bool call(Address _myAddress, Address _codeAddress, Address _txSender, u256 _txValue, u256 _gasPrice, bytesConstRef _txData, u256* _gas, bytesRef _out, Address _originAddress = Address(), SubState* o_sub = nullptr, Manifest* o_ms = nullptr, OnOpFunc const& _onOp = OnOpFunc(), unsigned _level = 0); - /// Sets m_currentBlock to a clean state, (i.e. no change from m_previousBlock). void resetCurrent(); @@ -328,8 +302,6 @@ private: static std::string c_defaultPath; - static const std::map c_precompiled; - friend std::ostream& operator<<(std::ostream& _out, State const& _s); }; diff --git a/libethereum/Transaction.cpp b/libethereum/Transaction.cpp index d94a31425..1edfe3927 100644 --- a/libethereum/Transaction.cpp +++ b/libethereum/Transaction.cpp @@ -82,7 +82,9 @@ Address Transaction::sender() const void Transaction::sign(Secret _priv) { auto sig = dev::sign(_priv, sha3(WithoutSignature)); - m_vrs = *(SignatureStruct const*)&sig; + SignatureStruct sigStruct = *(SignatureStruct const*)&sig; + if (sigStruct.isValid()) + m_vrs = sigStruct; } void Transaction::streamRLP(RLPStream& _s, IncludeSignature _sig) const diff --git a/libethereum/Manifest.cpp b/libethereum/TransactionReceipt.cpp similarity index 55% rename from libethereum/Manifest.cpp rename to libethereum/TransactionReceipt.cpp index 9e6d2f651..0fb104490 100644 --- a/libethereum/Manifest.cpp +++ b/libethereum/TransactionReceipt.cpp @@ -14,33 +14,38 @@ You should have received a copy of the GNU General Public License along with cpp-ethereum. If not, see . */ -/** @file Manifest.cpp +/** @file TransactionReceipt.cpp * @author Gav Wood * @date 2014 */ -#include "Manifest.h" +#include "TransactionReceipt.h" + using namespace std; using namespace dev; using namespace dev::eth; -Manifest::Manifest(bytesConstRef _r) +TransactionReceipt::TransactionReceipt(bytesConstRef _rlp) { - RLP r(_r); - from = r[0].toHash
(); - to = r[1].toHash
(); - value = r[2].toInt(); - altered = r[3].toVector(); - input = r[4].toBytes(); - output = r[5].toBytes(); - for (auto const& i: r[6]) - internal.emplace_back(i.data()); + RLP r(_rlp); + m_stateRoot = (h256)r[0]; + m_gasUsed = (u256)r[1]; + m_bloom = (LogBloom)r[2]; + for (auto const& i: r[3]) + m_log.emplace_back(i); } -void Manifest::streamRLP(RLPStream& _s) const +TransactionReceipt::TransactionReceipt(h256 _root, u256 _gasUsed, LogEntries const& _log): + m_stateRoot(_root), + m_gasUsed(_gasUsed), + m_bloom(eth::bloom(_log)), + m_log(_log) +{} + +void TransactionReceipt::streamRLP(RLPStream& _s) const { - _s.appendList(7) << from << to << value << altered << input << output; - _s.appendList(internal.size()); - for (auto const& i: internal) - i.streamRLP(_s); + _s.appendList(4) << m_stateRoot << m_gasUsed << m_bloom; + _s.appendList(m_log.size()); + for (LogEntry const& l: m_log) + l.streamRLP(_s); } diff --git a/libethereum/TransactionReceipt.h b/libethereum/TransactionReceipt.h index 26539c4a9..23995c75a 100644 --- a/libethereum/TransactionReceipt.h +++ b/libethereum/TransactionReceipt.h @@ -26,7 +26,6 @@ #include #include #include -#include "Manifest.h" namespace dev { @@ -37,31 +36,23 @@ namespace eth class TransactionReceipt { public: - TransactionReceipt(bytesConstRef _rlp) { RLP r(_rlp); m_stateRoot = (h256)r[0]; m_gasUsed = (u256)r[1]; m_bloom = (LogBloom)r[2]; for (auto const& i: r[3]) m_log.emplace_back(i); } - TransactionReceipt(h256 _root, u256 _gasUsed, LogEntries const& _log, Manifest const& _ms): m_stateRoot(_root), m_gasUsed(_gasUsed), m_bloom(eth::bloom(_log)), m_log(_log), m_changes(_ms) {} - - Manifest const& changes() const { return m_changes; } + TransactionReceipt(bytesConstRef _rlp); + TransactionReceipt(h256 _root, u256 _gasUsed, LogEntries const& _log); h256 const& stateRoot() const { return m_stateRoot; } u256 const& gasUsed() const { return m_gasUsed; } LogBloom const& bloom() const { return m_bloom; } LogEntries const& log() const { return m_log; } - void streamRLP(RLPStream& _s) const - { - _s.appendList(4) << m_stateRoot << m_gasUsed << m_bloom; - _s.appendList(m_log.size()); - for (LogEntry const& l: m_log) - l.streamRLP(_s); - } + void streamRLP(RLPStream& _s) const; + + bytes rlp() const { RLPStream s; streamRLP(s); return s.out(); } private: h256 m_stateRoot; u256 m_gasUsed; LogBloom m_bloom; LogEntries m_log; - - Manifest m_changes; ///< TODO: PoC-7: KILL }; using TransactionReceipts = std::vector; diff --git a/libethereum/Utility.h b/libethereum/Utility.h index 93c3d54c8..893604139 100644 --- a/libethereum/Utility.h +++ b/libethereum/Utility.h @@ -29,6 +29,17 @@ namespace dev namespace eth { +/** + * Takes a user-authorable string with several whitespace delimited arguments and builds a byte array + * from it. Arguments can be hex data/numerals, decimal numbers or ASCII strings. Literals are padded + * to 32 bytes if prefixed by a '@' (or not prefixed at all), and tightly packed if prefixed by a '$'. + * Currency multipliers can be provided. + * + * Example: + * @code + * parseData("$42 0x42 $\"Hello\""); // == bytes(1, 0x2a) + bytes(31, 0) + bytes(1, 0x42) + asBytes("Hello"); + * @endcode + */ bytes parseData(std::string const& _args); } diff --git a/libethereumx/CMakeLists.txt b/libethereumx/CMakeLists.txt index 1c74bf2c3..4a3cdcda7 100644 --- a/libethereumx/CMakeLists.txt +++ b/libethereumx/CMakeLists.txt @@ -1,66 +1,33 @@ cmake_policy(SET CMP0015 NEW) +set(CMAKE_AUTOMOC OFF) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DSTATICLIB") aux_source_directory(. SRC_LIST) +include_directories(..) set(EXECUTABLE ethereumx) -# set(CMAKE_INSTALL_PREFIX ../lib) -if(ETH_STATIC) - add_library(${EXECUTABLE} STATIC ${SRC_LIST}) +file(GLOB HEADERS "*.h") + +if (ETH_STATIC) + add_library(${EXECUTABLE} STATIC ${SRC_LIST} ${HEADERS}) else() - add_library(${EXECUTABLE} SHARED ${SRC_LIST}) + add_library(${EXECUTABLE} SHARED ${SRC_LIST} ${HEADERS}) endif() -file(GLOB HEADERS "*.h") +target_link_libraries(${EXECUTABLE} ${LEVELDB_LS}) +target_link_libraries(${EXECUTABLE} ${CRYPTOPP_LS}) -include_directories(..) +if (MINIUPNPC_LS) + target_link_libraries(${EXECUTABLE} ${MINIUPNPC_LS}) +endif() target_link_libraries(${EXECUTABLE} ethereum) target_link_libraries(${EXECUTABLE} evm) target_link_libraries(${EXECUTABLE} lll) target_link_libraries(${EXECUTABLE} ethcore) target_link_libraries(${EXECUTABLE} secp256k1) -if(MINIUPNPC_LS) -target_link_libraries(${EXECUTABLE} ${MINIUPNPC_LS}) -endif() -target_link_libraries(${EXECUTABLE} ${LEVELDB_LS}) -target_link_libraries(${EXECUTABLE} ${CRYPTOPP_LS}) -target_link_libraries(${EXECUTABLE} gmp) - -if("${TARGET_PLATFORM}" STREQUAL "w64") - target_link_libraries(${EXECUTABLE} boost_system-mt-s) - target_link_libraries(${EXECUTABLE} boost_regex-mt-s) - target_link_libraries(${EXECUTABLE} boost_filesystem-mt-s) - target_link_libraries(${EXECUTABLE} boost_thread_win32-mt-s) - target_link_libraries(${EXECUTABLE} iphlpapi) - target_link_libraries(${EXECUTABLE} ws2_32) - target_link_libraries(${EXECUTABLE} mswsock) - target_link_libraries(${EXECUTABLE} shlwapi) -elseif (APPLE) - # Latest mavericks boost libraries only come with -mt - target_link_libraries(${EXECUTABLE} boost_system-mt) - target_link_libraries(${EXECUTABLE} boost_regex-mt) - target_link_libraries(${EXECUTABLE} boost_filesystem-mt) - target_link_libraries(${EXECUTABLE} boost_thread-mt) - find_package(Threads REQUIRED) - target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT}) -elseif (UNIX) - target_link_libraries(${EXECUTABLE} ${Boost_SYSTEM_LIBRARY}) - target_link_libraries(${EXECUTABLE} ${Boost_REGEX_LIBRARY}) - target_link_libraries(${EXECUTABLE} ${Boost_FILESYSTEM_LIBRARY}) - target_link_libraries(${EXECUTABLE} ${Boost_THREAD_LIBRARY}) - target_link_libraries(${EXECUTABLE} ${Boost_DATE_TIME_LIBRARY}) - target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT}) -else () - target_link_libraries(${EXECUTABLE} boost_system) - target_link_libraries(${EXECUTABLE} boost_regex) - target_link_libraries(${EXECUTABLE} boost_filesystem) - target_link_libraries(${EXECUTABLE} boost_thread) - find_package(Threads REQUIRED) - target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT}) -endif () install( TARGETS ${EXECUTABLE} ARCHIVE DESTINATION lib LIBRARY DESTINATION lib ) install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} ) diff --git a/libevm/CMakeLists.txt b/libevm/CMakeLists.txt index b4aa1eef2..96b8f9ade 100644 --- a/libevm/CMakeLists.txt +++ b/libevm/CMakeLists.txt @@ -1,60 +1,35 @@ cmake_policy(SET CMP0015 NEW) +# this policy was introduced in cmake 3.0 +# remove if, once 3.0 will be used on unix +if (${CMAKE_MAJOR_VERSION} GREATER 2) + # old policy do not use MACOSX_RPATH + cmake_policy(SET CMP0042 OLD) +endif() +set(CMAKE_AUTOMOC OFF) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DSTATICLIB") aux_source_directory(. SRC_LIST) +# we may not use it in libevm, but one of our dependecies is including boost in header file +# and windows is failing to build without that +include_directories(${Boost_INCLUDE_DIRS}) +include_directories(..) + set(EXECUTABLE evm) file(GLOB HEADERS "*.h") -if(ETH_STATIC) + +if (ETH_STATIC) add_library(${EXECUTABLE} STATIC ${SRC_LIST} ${HEADERS}) else() add_library(${EXECUTABLE} SHARED ${SRC_LIST} ${HEADERS}) endif() -include_directories(..) - target_link_libraries(${EXECUTABLE} ethcore) target_link_libraries(${EXECUTABLE} devcrypto) target_link_libraries(${EXECUTABLE} evmcore) target_link_libraries(${EXECUTABLE} devcore) -target_link_libraries(${EXECUTABLE} secp256k1) -target_link_libraries(${EXECUTABLE} gmp) -if(MINIUPNPC_LS) -target_link_libraries(${EXECUTABLE} ${MINIUPNPC_LS}) -endif() -target_link_libraries(${EXECUTABLE} ${LEVELDB_LS}) -target_link_libraries(${EXECUTABLE} ${CRYPTOPP_LS}) - -if("${TARGET_PLATFORM}" STREQUAL "w64") - target_link_libraries(${EXECUTABLE} boost_system-mt-s) - target_link_libraries(${EXECUTABLE} boost_filesystem-mt-s) - target_link_libraries(${EXECUTABLE} boost_thread_win32-mt-s) - target_link_libraries(${EXECUTABLE} iphlpapi) - target_link_libraries(${EXECUTABLE} ws2_32) - target_link_libraries(${EXECUTABLE} mswsock) - target_link_libraries(${EXECUTABLE} shlwapi) -elseif (APPLE) - # Latest mavericks boost libraries only come with -mt - target_link_libraries(${EXECUTABLE} boost_system-mt) - target_link_libraries(${EXECUTABLE} boost_filesystem-mt) - target_link_libraries(${EXECUTABLE} boost_thread-mt) - find_package(Threads REQUIRED) - target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT}) -elseif (UNIX) - target_link_libraries(${EXECUTABLE} ${Boost_SYSTEM_LIBRARY}) - target_link_libraries(${EXECUTABLE} ${Boost_FILESYSTEM_LIBRARY}) - target_link_libraries(${EXECUTABLE} ${Boost_THREAD_LIBRARY}) - target_link_libraries(${EXECUTABLE} ${Boost_DATE_TIME_LIBRARY}) - target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT}) -else () - target_link_libraries(${EXECUTABLE} boost_system) - target_link_libraries(${EXECUTABLE} boost_filesystem) - target_link_libraries(${EXECUTABLE} boost_thread) - find_package(Threads REQUIRED) - target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT}) -endif () install( TARGETS ${EXECUTABLE} ARCHIVE DESTINATION lib LIBRARY DESTINATION lib ) install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} ) diff --git a/libevm/ExtVMFace.h b/libevm/ExtVMFace.h index 8a6b2edc9..84dee4272 100644 --- a/libevm/ExtVMFace.h +++ b/libevm/ExtVMFace.h @@ -36,21 +36,11 @@ namespace dev namespace eth { -template inline std::set toSet(std::vector const& _ts) -{ - std::set ret; - for (auto const& t: _ts) - ret.insert(t); - return ret; -} - -using LogBloom = h512; - struct LogEntry { LogEntry() {} - LogEntry(RLP const& _r) { address = (Address)_r[0]; topics = (h256Set)_r[1]; data = (bytes)_r[2]; } - LogEntry(Address const& _address, h256s const& _ts, bytes&& _d): address(_address), topics(toSet(_ts)), data(std::move(_d)) {} + LogEntry(RLP const& _r) { address = (Address)_r[0]; topics = _r[1].toVector(); data = _r[2].toBytes(); } + LogEntry(Address const& _address, h256s const& _ts, bytes&& _d): address(_address), topics(_ts), data(std::move(_d)) {} void streamRLP(RLPStream& _s) const { _s.appendList(3) << address << topics << data; } @@ -64,7 +54,7 @@ struct LogEntry } Address address; - h256Set topics; + h256s topics; bytes data; }; @@ -88,11 +78,22 @@ struct SubState { suicides += _s.suicides; refunds += _s.refunds; + logs += _s.logs; return *this; } + + void clear() + { + suicides.clear(); + logs.clear(); + refunds = 0; + } }; -using OnOpFunc = std::function; +class ExtVMFace; +class VM; + +using OnOpFunc = std::function; /** * @brief Interface and null implementation of the class for specifying VM externalities. @@ -133,10 +134,10 @@ public: virtual void suicide(Address) { sub.suicides.insert(myAddress); } /// Create a new (contract) account. - virtual h160 create(u256, u256*, bytesConstRef, OnOpFunc const&) { return h160(); } + virtual h160 create(u256, u256&, bytesConstRef, OnOpFunc const&) { return h160(); } /// Make a new message call. - virtual bool call(Address, u256, bytesConstRef, u256*, bytesRef, OnOpFunc const&, Address, Address) { return false; } + virtual bool call(Address, u256, bytesConstRef, u256&, bytesRef, OnOpFunc const&, Address, Address) { return false; } /// Revert any changes made (by any of the other calls). virtual void log(h256s&& _topics, bytesConstRef _data) { sub.logs.push_back(LogEntry(myAddress, std::move(_topics), _data.toBytes())); } @@ -153,11 +154,11 @@ public: u256 value; ///< Value (in Wei) that was passed to this address. u256 gasPrice; ///< Price of gas (that we already paid). bytesConstRef data; ///< Current input data. - bytes code; ///< Current code that is executing. + bytes code; ///< Current code that is executing. BlockInfo previousBlock; ///< The previous block's information. BlockInfo currentBlock; ///< The current block's information. SubState sub; ///< Sub-band VM state (suicides, refund counter, logs). - unsigned depth; ///< Depth of the present call. + unsigned depth = 0; ///< Depth of the present call. }; } diff --git a/libevm/FeeStructure.cpp b/libevm/FeeStructure.cpp index 47236b506..94eb956af 100644 --- a/libevm/FeeStructure.cpp +++ b/libevm/FeeStructure.cpp @@ -27,13 +27,22 @@ using namespace dev::eth; u256 const dev::eth::c_stepGas = 1; u256 const dev::eth::c_balanceGas = 20; -u256 const dev::eth::c_sha3Gas = 20; +u256 const dev::eth::c_sha3Gas = 10; +u256 const dev::eth::c_sha3WordGas = 10; u256 const dev::eth::c_sloadGas = 20; u256 const dev::eth::c_sstoreSetGas = 300; u256 const dev::eth::c_sstoreResetGas = 100; u256 const dev::eth::c_sstoreRefundGas = 100; u256 const dev::eth::c_createGas = 100; +u256 const dev::eth::c_createDataGas = 5; u256 const dev::eth::c_callGas = 20; +u256 const dev::eth::c_expGas = 1; +u256 const dev::eth::c_expByteGas = 1; u256 const dev::eth::c_memoryGas = 1; -u256 const dev::eth::c_txDataGas = 5; +u256 const dev::eth::c_txDataZeroGas = 1; +u256 const dev::eth::c_txDataNonZeroGas = 5; u256 const dev::eth::c_txGas = 500; +u256 const dev::eth::c_logGas = 32; +u256 const dev::eth::c_logDataGas = 1; +u256 const dev::eth::c_logTopicGas = 32; +u256 const dev::eth::c_copyGas = 1; diff --git a/libevm/FeeStructure.h b/libevm/FeeStructure.h index 84a2551d9..8ef384265 100644 --- a/libevm/FeeStructure.h +++ b/libevm/FeeStructure.h @@ -31,15 +31,24 @@ namespace eth extern u256 const c_stepGas; ///< Once per operation, except for SSTORE, SLOAD, BALANCE, SHA3, CREATE, CALL. extern u256 const c_balanceGas; ///< Once per BALANCE operation. extern u256 const c_sha3Gas; ///< Once per SHA3 operation. +extern u256 const c_sha3WordGas; extern u256 const c_sloadGas; ///< Once per SLOAD operation. extern u256 const c_sstoreSetGas; ///< Once per SSTORE operation if the zeroness changes from zero. extern u256 const c_sstoreResetGas; ///< Once per SSTORE operation if the zeroness doesn't change. extern u256 const c_sstoreRefundGas; ///< Refunded gas, once per SSTORE operation if the zeroness changes to zero. extern u256 const c_createGas; ///< Once per CREATE operation & contract-creation transaction. +extern u256 const c_createDataGas; extern u256 const c_callGas; ///< Once per CALL operation & message call transaction. +extern u256 const c_expGas; ///< Once per EXP instuction. +extern u256 const c_expByteGas; ///< Times ceil(log256(exponent)) for the EXP instruction. extern u256 const c_memoryGas; ///< Times the address of the (highest referenced byte in memory + 1). NOTE: referencing happens on read, write and in instructions such as RETURN and CALL. -extern u256 const c_txDataGas; ///< Per byte of data attached to a transaction. NOTE: Not payable on data of calls between transactions. +extern u256 const c_txDataZeroGas; ///< Per byte of data attached to a transaction that equals zero. NOTE: Not payable on data of calls between transactions. +extern u256 const c_txDataNonZeroGas; ///< Per byte of data attached to a transaction that is not equal to zero. NOTE: Not payable on data of calls between transactions. extern u256 const c_txGas; ///< Per transaction. NOTE: Not payable on data of calls between transactions. +extern u256 const c_logGas; ///< Per LOG* operation. +extern u256 const c_logDataGas; ///< Per byte in a LOG* operation's data. +extern u256 const c_logTopicGas; ///< Multiplied by the * of the LOG*, per LOG transaction. e.g. LOG0 incurs 0 * c_txLogTopicGas, LOG4 incurs 4 * c_txLogTopicGas. +extern u256 const c_copyGas; ///< Multiplied by the number of 32-byte words that are copied (round up) for any *COPY operation and added. } } diff --git a/libevm/VM.cpp b/libevm/VM.cpp index bded9a10d..b8452e4f5 100644 --- a/libevm/VM.cpp +++ b/libevm/VM.cpp @@ -20,14 +20,14 @@ */ #include "VM.h" +#include -using namespace std; using namespace dev; using namespace dev::eth; -void VM::reset(u256 _gas) +void VM::reset(u256 _gas) noexcept { - m_gas = _gas; + VMFace::reset(_gas); m_curPC = 0; m_jumpDests.clear(); } diff --git a/libevm/VM.h b/libevm/VM.h index a35b3f005..3eb330fcd 100644 --- a/libevm/VM.h +++ b/libevm/VM.h @@ -28,21 +28,13 @@ #include #include #include "FeeStructure.h" -#include "ExtVMFace.h" +#include "VMFace.h" namespace dev { namespace eth { -struct VMException: virtual Exception {}; -struct StepsDone: virtual VMException {}; -struct BreakPointHit: virtual VMException {}; -struct BadInstruction: virtual VMException {}; -struct BadJumpDestination: virtual VMException {}; -struct OutOfGas: virtual VMException {}; -struct StackTooSmall: virtual public VMException {}; - // Convert from a 256-bit integer stack/memory entry into a 160-bit Address hash. // Currently we just pull out the right (low-order in BE) 160-bits. inline Address asAddress(u256 _item) @@ -53,46 +45,42 @@ inline Address asAddress(u256 _item) inline u256 fromAddress(Address _a) { return (u160)_a; -// h256 ret; -// memcpy(&ret, &_a, sizeof(_a)); -// return ret; } /** */ -class VM +class VM: public VMFace { public: - /// Construct VM object. - explicit VM(u256 _gas = 0) { reset(_gas); } + virtual void reset(u256 _gas = 0) noexcept override final; - void reset(u256 _gas = 0); + virtual bytesConstRef go(ExtVMFace& _ext, OnOpFunc const& _onOp = {}, uint64_t _steps = (uint64_t)-1) override final; - template - bytesConstRef go(Ext& _ext, OnOpFunc const& _onOp = OnOpFunc(), uint64_t _steps = (uint64_t)-1); - - void require(u256 _n) { if (m_stack.size() < _n) BOOST_THROW_EXCEPTION(StackTooSmall() << RequirementError(int(_n), m_stack.size())); } + void require(u256 _n) { if (m_stack.size() < _n) { if (m_onFail) m_onFail(); BOOST_THROW_EXCEPTION(StackTooSmall() << RequirementError((bigint)_n, (bigint)m_stack.size())); } } void requireMem(unsigned _n) { if (m_temp.size() < _n) { m_temp.resize(_n); } } - u256 gas() const { return m_gas; } + u256 curPC() const { return m_curPC; } bytes const& memory() const { return m_temp; } u256s const& stack() const { return m_stack; } private: - u256 m_gas = 0; + friend class VMFactory; + + /// Construct VM object. + explicit VM(u256 _gas): VMFace(_gas) {} + u256 m_curPC = 0; bytes m_temp; u256s m_stack; std::set m_jumpDests; + std::function m_onFail; }; -} - -// INLINE: -template dev::bytesConstRef dev::eth::VM::go(Ext& _ext, OnOpFunc const& _onOp, uint64_t _steps) +// TODO: Move it to cpp file. Not done to make review easier. +inline bytesConstRef VM::go(ExtVMFace& _ext, OnOpFunc const& _onOp, uint64_t _steps) { - auto memNeed = [](dev::u256 _offset, dev::u256 _size) { return _size ? _offset + _size : 0; }; + auto memNeed = [](dev::u256 _offset, dev::u256 _size) { return _size ? (bigint)_offset + _size : (bigint)0; }; if (m_jumpDests.empty()) { @@ -129,6 +117,16 @@ template dev::bytesConstRef dev::eth::VM::go(Ext& _ext, OnOpFunc con // FEES... bigint runGas = c_stepGas; bigint newTempSize = m_temp.size(); + bigint copySize = 0; + + auto onOperation = [&]() + { + if (_onOp) + _onOp(osteps - _steps - 1, inst, newTempSize > m_temp.size() ? (newTempSize - m_temp.size()) / 32 : bigint(0), runGas, this, &_ext); + }; + // should work, but just seems to result in immediate errorless exit on initial execution. yeah. weird. + //m_onFail = std::function(onOperation); + switch (inst) { case Instruction::STOP: @@ -155,21 +153,21 @@ template dev::bytesConstRef dev::eth::VM::go(Ext& _ext, OnOpFunc con case Instruction::SLOAD: require(1); - runGas = c_sloadGas; + runGas = c_sloadGas; break; // These all operate on memory and therefore potentially expand it: case Instruction::MSTORE: require(2); - newTempSize = m_stack.back() + 32; + newTempSize = (bigint)m_stack.back() + 32; break; case Instruction::MSTORE8: require(2); - newTempSize = m_stack.back() + 1; + newTempSize = (bigint)m_stack.back() + 1; break; case Instruction::MLOAD: require(1); - newTempSize = m_stack.back() + 32; + newTempSize = (bigint)m_stack.back() + 32; break; case Instruction::RETURN: require(2); @@ -177,19 +175,22 @@ template dev::bytesConstRef dev::eth::VM::go(Ext& _ext, OnOpFunc con break; case Instruction::SHA3: require(2); - runGas = c_sha3Gas; + runGas = c_sha3Gas + (m_stack[m_stack.size() - 2] + 31) / 32 * c_sha3WordGas; newTempSize = memNeed(m_stack.back(), m_stack[m_stack.size() - 2]); break; case Instruction::CALLDATACOPY: require(3); + copySize = m_stack[m_stack.size() - 3]; newTempSize = memNeed(m_stack.back(), m_stack[m_stack.size() - 3]); break; case Instruction::CODECOPY: require(3); + copySize = m_stack[m_stack.size() - 3]; newTempSize = memNeed(m_stack.back(), m_stack[m_stack.size() - 3]); break; case Instruction::EXTCODECOPY: require(4); + copySize = m_stack[m_stack.size() - 4]; newTempSize = memNeed(m_stack[m_stack.size() - 2], m_stack[m_stack.size() - 4]); break; @@ -206,24 +207,32 @@ template dev::bytesConstRef dev::eth::VM::go(Ext& _ext, OnOpFunc con { unsigned n = (unsigned)inst - (unsigned)Instruction::LOG0; require(n + 2); - newTempSize = memNeed(m_stack[m_stack.size() - 1 - n], m_stack[m_stack.size() - 2 - n]); + runGas = c_logGas + c_logTopicGas * n + (bigint)c_logDataGas * m_stack[m_stack.size() - 2]; + newTempSize = memNeed(m_stack[m_stack.size() - 1], m_stack[m_stack.size() - 2]); break; } case Instruction::CALL: case Instruction::CALLCODE: require(7); - runGas = c_callGas + m_stack[m_stack.size() - 1]; + runGas = (bigint)c_callGas + m_stack[m_stack.size() - 1]; newTempSize = std::max(memNeed(m_stack[m_stack.size() - 6], m_stack[m_stack.size() - 7]), memNeed(m_stack[m_stack.size() - 4], m_stack[m_stack.size() - 5])); break; case Instruction::CREATE: { require(3); - auto inOff = m_stack[m_stack.size() - 2]; - auto inSize = m_stack[m_stack.size() - 3]; - newTempSize = inOff + inSize; - runGas = c_createGas; + u256 inOff = m_stack[m_stack.size() - 2]; + u256 inSize = m_stack[m_stack.size() - 3]; + newTempSize = (bigint)inOff + inSize; + runGas = c_createGas; + break; + } + case Instruction::EXP: + { + require(2); + auto expon = m_stack[m_stack.size() - 2]; + runGas = c_expGas + c_expByteGas * (32 - (h256(expon).firstBitSet() / 8)); break; } @@ -292,7 +301,6 @@ template dev::bytesConstRef dev::eth::VM::go(Ext& _ext, OnOpFunc con case Instruction::SDIV: case Instruction::MOD: case Instruction::SMOD: - case Instruction::EXP: case Instruction::LT: case Instruction::GT: case Instruction::SLT: @@ -353,9 +361,11 @@ template dev::bytesConstRef dev::eth::VM::go(Ext& _ext, OnOpFunc con newTempSize = (newTempSize + 31) / 32 * 32; if (newTempSize > m_temp.size()) runGas += c_memoryGas * (newTempSize - m_temp.size()) / 32; + runGas += c_copyGas * (copySize + 31) / 32; - if (_onOp) - _onOp(osteps - _steps - 1, inst, newTempSize > m_temp.size() ? (newTempSize - m_temp.size()) / 32 : bigint(0), runGas, this, &_ext); + onOperation(); +// if (_onOp) +// _onOp(osteps - _steps - 1, inst, newTempSize > m_temp.size() ? (newTempSize - m_temp.size()) / 32 : bigint(0), runGas, this, &_ext); if (m_gas < runGas) { @@ -391,7 +401,7 @@ template dev::bytesConstRef dev::eth::VM::go(Ext& _ext, OnOpFunc con m_stack.pop_back(); break; case Instruction::SDIV: - m_stack[m_stack.size() - 2] = m_stack[m_stack.size() - 2] ? s2u(u2s(m_stack.back()) / u2s(m_stack[m_stack.size() - 2])) : 0; + m_stack[m_stack.size() - 2] = m_stack[m_stack.size() - 2] ? s2u(u2s(m_stack.back()) / u2s(m_stack[m_stack.size() - 2])) : 0; m_stack.pop_back(); break; case Instruction::MOD: @@ -399,7 +409,7 @@ template dev::bytesConstRef dev::eth::VM::go(Ext& _ext, OnOpFunc con m_stack.pop_back(); break; case Instruction::SMOD: - m_stack[m_stack.size() - 2] = m_stack[m_stack.size() - 2] ? s2u(u2s(m_stack.back()) % u2s(m_stack[m_stack.size() - 2])) : 0; + m_stack[m_stack.size() - 2] = m_stack[m_stack.size() - 2] ? s2u(u2s(m_stack.back()) % u2s(m_stack[m_stack.size() - 2])) : 0; m_stack.pop_back(); break; case Instruction::EXP: @@ -422,11 +432,11 @@ template dev::bytesConstRef dev::eth::VM::go(Ext& _ext, OnOpFunc con m_stack.pop_back(); break; case Instruction::SLT: - m_stack[m_stack.size() - 2] = u2s(m_stack.back()) < u2s(m_stack[m_stack.size() - 2]) ? 1 : 0; + m_stack[m_stack.size() - 2] = u2s(m_stack.back()) < u2s(m_stack[m_stack.size() - 2]) ? 1 : 0; m_stack.pop_back(); break; case Instruction::SGT: - m_stack[m_stack.size() - 2] = u2s(m_stack.back()) > u2s(m_stack[m_stack.size() - 2]) ? 1 : 0; + m_stack[m_stack.size() - 2] = u2s(m_stack.back()) > u2s(m_stack[m_stack.size() - 2]) ? 1 : 0; m_stack.pop_back(); break; case Instruction::EQ: @@ -503,12 +513,12 @@ template dev::bytesConstRef dev::eth::VM::go(Ext& _ext, OnOpFunc con break; case Instruction::CALLDATALOAD: { - if ((unsigned)m_stack.back() + 31 < _ext.data.size()) + if ((unsigned)m_stack.back() + (uint64_t)31 < _ext.data.size()) m_stack.back() = (u256)*(h256 const*)(_ext.data.data() + (unsigned)m_stack.back()); else { h256 r; - for (unsigned i = (unsigned)m_stack.back(), e = (unsigned)m_stack.back() + 32, j = 0; i < e; ++i, ++j) + for (uint64_t i = (unsigned)m_stack.back(), e = (unsigned)m_stack.back() + (uint64_t)32, j = 0; i < e; ++i, ++j) r[j] = i < _ext.data.size() ? _ext.data[i] : 0; m_stack.back() = (u256)r; } @@ -517,51 +527,49 @@ template dev::bytesConstRef dev::eth::VM::go(Ext& _ext, OnOpFunc con case Instruction::CALLDATASIZE: m_stack.push_back(_ext.data.size()); break; - case Instruction::CALLDATACOPY: - { - unsigned mf = (unsigned)m_stack.back(); - m_stack.pop_back(); - u256 cf = m_stack.back(); - m_stack.pop_back(); - unsigned l = (unsigned)m_stack.back(); - m_stack.pop_back(); - unsigned el = cf + l > (u256)_ext.data.size() ? (u256)_ext.data.size() < cf ? 0 : _ext.data.size() - (unsigned)cf : l; - memcpy(m_temp.data() + mf, _ext.data.data() + (unsigned)cf, el); - memset(m_temp.data() + mf + el, 0, l - el); - break; - } case Instruction::CODESIZE: m_stack.push_back(_ext.code.size()); break; - case Instruction::CODECOPY: - { - unsigned mf = (unsigned)m_stack.back(); - m_stack.pop_back(); - u256 cf = (u256)m_stack.back(); - m_stack.pop_back(); - unsigned l = (unsigned)m_stack.back(); - m_stack.pop_back(); - unsigned el = cf + l > (u256)_ext.code.size() ? (u256)_ext.code.size() < cf ? 0 : _ext.code.size() - (unsigned)cf : l; - memcpy(m_temp.data() + mf, _ext.code.data() + (unsigned)cf, el); - memset(m_temp.data() + mf + el, 0, l - el); - break; - } case Instruction::EXTCODESIZE: m_stack.back() = _ext.codeAt(asAddress(m_stack.back())).size(); break; + case Instruction::CALLDATACOPY: + case Instruction::CODECOPY: case Instruction::EXTCODECOPY: { - Address a = asAddress(m_stack.back()); - m_stack.pop_back(); - unsigned mf = (unsigned)m_stack.back(); + Address a; + if (inst == Instruction::EXTCODECOPY) + { + a = asAddress(m_stack.back()); + m_stack.pop_back(); + } + unsigned offset = (unsigned)m_stack.back(); m_stack.pop_back(); - u256 cf = m_stack.back(); + u256 index = m_stack.back(); m_stack.pop_back(); - unsigned l = (unsigned)m_stack.back(); + unsigned size = (unsigned)m_stack.back(); m_stack.pop_back(); - unsigned el = cf + l > (u256)_ext.codeAt(a).size() ? (u256)_ext.codeAt(a).size() < cf ? 0 : _ext.codeAt(a).size() - (unsigned)cf : l; - memcpy(m_temp.data() + mf, _ext.codeAt(a).data() + (unsigned)cf, el); - memset(m_temp.data() + mf + el, 0, l - el); + unsigned sizeToBeCopied; + switch(inst) + { + case Instruction::CALLDATACOPY: + sizeToBeCopied = index + (bigint)size > (u256)_ext.data.size() ? (u256)_ext.data.size() < index ? 0 : _ext.data.size() - (unsigned)index : size; + memcpy(m_temp.data() + offset, _ext.data.data() + (unsigned)index, sizeToBeCopied); + break; + case Instruction::CODECOPY: + sizeToBeCopied = index + (bigint)size > (u256)_ext.code.size() ? (u256)_ext.code.size() < index ? 0 : _ext.code.size() - (unsigned)index : size; + memcpy(m_temp.data() + offset, _ext.code.data() + (unsigned)index, sizeToBeCopied); + break; + case Instruction::EXTCODECOPY: + sizeToBeCopied = index + (bigint)size > (u256)_ext.codeAt(a).size() ? (u256)_ext.codeAt(a).size() < index ? 0 : _ext.codeAt(a).size() - (unsigned)index : size; + memcpy(m_temp.data() + offset, _ext.codeAt(a).data() + (unsigned)index, sizeToBeCopied); + break; + default: + // this is unreachable, but if someone introduces a bug in the future, he may get here. + BOOST_THROW_EXCEPTION(InvalidOpcode() << errinfo_comment("CALLDATACOPY, CODECOPY or EXTCODECOPY instruction requested.")); + break; + } + memset(m_temp.data() + offset + sizeToBeCopied, 0, size - sizeToBeCopied); break; } case Instruction::GASPRICE: @@ -743,18 +751,38 @@ template dev::bytesConstRef dev::eth::VM::go(Ext& _ext, OnOpFunc con break;*/ case Instruction::LOG0: _ext.log({}, bytesConstRef(m_temp.data() + (unsigned)m_stack[m_stack.size() - 1], (unsigned)m_stack[m_stack.size() - 2])); + m_stack.pop_back(); + m_stack.pop_back(); break; case Instruction::LOG1: _ext.log({m_stack[m_stack.size() - 3]}, bytesConstRef(m_temp.data() + (unsigned)m_stack[m_stack.size() - 1], (unsigned)m_stack[m_stack.size() - 2])); + m_stack.pop_back(); + m_stack.pop_back(); + m_stack.pop_back(); break; case Instruction::LOG2: _ext.log({m_stack[m_stack.size() - 3], m_stack[m_stack.size() - 4]}, bytesConstRef(m_temp.data() + (unsigned)m_stack[m_stack.size() - 1], (unsigned)m_stack[m_stack.size() - 2])); + m_stack.pop_back(); + m_stack.pop_back(); + m_stack.pop_back(); + m_stack.pop_back(); break; case Instruction::LOG3: _ext.log({m_stack[m_stack.size() - 3], m_stack[m_stack.size() - 4], m_stack[m_stack.size() - 5]}, bytesConstRef(m_temp.data() + (unsigned)m_stack[m_stack.size() - 1], (unsigned)m_stack[m_stack.size() - 2])); + m_stack.pop_back(); + m_stack.pop_back(); + m_stack.pop_back(); + m_stack.pop_back(); + m_stack.pop_back(); break; case Instruction::LOG4: _ext.log({m_stack[m_stack.size() - 3], m_stack[m_stack.size() - 4], m_stack[m_stack.size() - 5], m_stack[m_stack.size() - 6]}, bytesConstRef(m_temp.data() + (unsigned)m_stack[m_stack.size() - 1], (unsigned)m_stack[m_stack.size() - 2])); + m_stack.pop_back(); + m_stack.pop_back(); + m_stack.pop_back(); + m_stack.pop_back(); + m_stack.pop_back(); + m_stack.pop_back(); break; case Instruction::CREATE: { @@ -770,7 +798,7 @@ template dev::bytesConstRef dev::eth::VM::go(Ext& _ext, OnOpFunc con if (_ext.depth == 1024) BOOST_THROW_EXCEPTION(OutOfGas()); _ext.subBalance(endowment); - m_stack.push_back((u160)_ext.create(endowment, &m_gas, bytesConstRef(m_temp.data() + initOff, initSize), _onOp)); + m_stack.push_back((u160)_ext.create(endowment, m_gas, bytesConstRef(m_temp.data() + initOff, initSize), _onOp)); } else m_stack.push_back(0); @@ -800,7 +828,7 @@ template dev::bytesConstRef dev::eth::VM::go(Ext& _ext, OnOpFunc con if (_ext.depth == 1024) BOOST_THROW_EXCEPTION(OutOfGas()); _ext.subBalance(value); - m_stack.push_back(_ext.call(inst == Instruction::CALL ? receiveAddress : _ext.myAddress, value, bytesConstRef(m_temp.data() + inOff, inSize), &gas, bytesRef(m_temp.data() + outOff, outSize), _onOp, Address(), receiveAddress)); + m_stack.push_back(_ext.call(inst == Instruction::CALL ? receiveAddress : _ext.myAddress, value, bytesConstRef(m_temp.data() + inOff, inSize), gas, bytesRef(m_temp.data() + outOff, outSize), _onOp, {}, receiveAddress)); } else m_stack.push_back(0); @@ -831,4 +859,6 @@ template dev::bytesConstRef dev::eth::VM::go(Ext& _ext, OnOpFunc con BOOST_THROW_EXCEPTION(StepsDone()); return bytesConstRef(); } + +} } diff --git a/libevm/VMFace.h b/libevm/VMFace.h new file mode 100644 index 000000000..44ae03868 --- /dev/null +++ b/libevm/VMFace.h @@ -0,0 +1,55 @@ +/* + This file is part of cpp-ethereum. + + cpp-ethereum is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + cpp-ethereum is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with cpp-ethereum. If not, see . +*/ +#pragma once + +#include +#include +#include "ExtVMFace.h" + +namespace dev +{ +namespace eth +{ + +struct VMException: virtual Exception {}; +struct StepsDone: virtual VMException {}; +struct BreakPointHit: virtual VMException {}; +struct BadInstruction: virtual VMException {}; +struct BadJumpDestination: virtual VMException {}; +struct OutOfGas: virtual VMException {}; +struct StackTooSmall: virtual VMException {}; + +/// EVM Virtual Machine interface +class VMFace +{ +public: + explicit VMFace(u256 _gas): m_gas(_gas) {} + virtual ~VMFace() = default; + VMFace(VMFace const&) = delete; + void operator=(VMFace const&) = delete; + + virtual void reset(u256 _gas = 0) noexcept { m_gas = _gas; } + u256 gas() const noexcept { return m_gas; } + + virtual bytesConstRef go(ExtVMFace& _ext, OnOpFunc const& _onOp = {}, uint64_t _steps = (uint64_t)-1) = 0; + +protected: + u256 m_gas = 0; +}; + +} +} diff --git a/libevm/VMFactory.cpp b/libevm/VMFactory.cpp new file mode 100644 index 000000000..af37ec710 --- /dev/null +++ b/libevm/VMFactory.cpp @@ -0,0 +1,42 @@ +/* + This file is part of cpp-ethereum. + + cpp-ethereum is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + cpp-ethereum is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with cpp-ethereum. If not, see . +*/ + +#include "VMFactory.h" +#include "VM.h" + +namespace dev +{ +namespace eth +{ +namespace +{ + VMKind g_kind = VMKind::Interpreter; +} + +void VMFactory::setKind(VMKind _kind) +{ + g_kind = _kind; +} + +std::unique_ptr VMFactory::create(u256 _gas) +{ + asserts(g_kind == VMKind::Interpreter && "Only interpreter supported for now"); + return std::unique_ptr(new VM(_gas)); +} + +} +} diff --git a/libethereum/PastMessage.cpp b/libevm/VMFactory.h similarity index 71% rename from libethereum/PastMessage.cpp rename to libevm/VMFactory.h index d81ae672c..d0d02e0c4 100644 --- a/libethereum/PastMessage.cpp +++ b/libevm/VMFactory.h @@ -14,15 +14,29 @@ You should have received a copy of the GNU General Public License along with cpp-ethereum. If not, see . */ -/** @file PastMessage.cpp - * @author Gav Wood - * @date 2014 - */ - -#include "PastMessage.h" -using namespace std; -using namespace dev; -using namespace dev::eth; - -#pragma GCC diagnostic ignored "-Wunused-variable" -namespace { char dummy; }; +#pragma once + +#include "VMFace.h" + +namespace dev +{ +namespace eth +{ + +enum class VMKind: bool +{ + Interpreter, + JIT +}; + +class VMFactory +{ +public: + VMFactory() = delete; + + static std::unique_ptr create(u256 _gas); + static void setKind(VMKind _kind); +}; + +} +} diff --git a/libevm/_libevm.cpp b/libevm/_libevm.cpp deleted file mode 100644 index 27186cbf2..000000000 --- a/libevm/_libevm.cpp +++ /dev/null @@ -1,6 +0,0 @@ -#ifdef _MSC_VER -#include "All.h" -#include "ExtVMFace.cpp" -#include "FeeStructure.cpp" -#include "VM.cpp" -#endif diff --git a/libevmcore/Assembly.cpp b/libevmcore/Assembly.cpp index 4725c8c1a..059810af8 100644 --- a/libevmcore/Assembly.cpp +++ b/libevmcore/Assembly.cpp @@ -27,6 +27,32 @@ using namespace std; using namespace dev; using namespace dev::eth; +unsigned AssemblyItem::bytesRequired(unsigned _addressLength) const +{ + switch (m_type) + { + case Operation: + case Tag: // 1 byte for the JUMPDEST + return 1; + case PushString: + return 33; + case Push: + return 1 + max(1, dev::bytesRequired(m_data)); + case PushSubSize: + return 4; // worst case: a 16MB program + case PushTag: + case PushData: + case PushSub: + return 1 + _addressLength; + case NoOptimizeBegin: + case NoOptimizeEnd: + return 0; + default: + break; + } + BOOST_THROW_EXCEPTION(InvalidOpcode()); +} + int AssemblyItem::deposit() const { switch (m_type) @@ -51,32 +77,7 @@ unsigned Assembly::bytesRequired() const ret += i.second.size(); for (AssemblyItem const& i: m_items) - switch (i.m_type) - { - case Operation: - case Tag: // 1 byte for the JUMPDEST - ret++; - break; - case PushString: - ret += 33; - break; - case Push: - ret += 1 + max(1, dev::bytesRequired(i.m_data)); - break; - case PushSubSize: - ret += 4; // worst case: a 16MB program - break; - case PushTag: - case PushData: - case PushSub: - ret += 1 + br; - break; - case NoOptimizeBegin: - case NoOptimizeEnd: - break; - default: - BOOST_THROW_EXCEPTION(InvalidOpcode()); - } + ret += i.bytesRequired(br); if (dev::bytesRequired(ret) <= br) return ret; } @@ -243,6 +244,18 @@ inline bool popCountIncreased(AssemblyItemsConstRef _pre, AssemblyItems const& _ return count_if(begin(_post), end(_post), isPop) > count_if(begin(_pre), end(_pre), isPop); } +//@todo this has to move to a special optimizer class soon +template +unsigned bytesRequiredBySlice(Iterator _begin, Iterator _end) +{ + // this is only used in the optimizer, so we can provide a guess for the address length + unsigned addressLength = 4; + unsigned size = 0; + for (; _begin != _end; ++_begin) + size += _begin->bytesRequired(addressLength); + return size; +} + struct OptimiserChannel: public LogChannel { static const char* name() { return "OPT"; } static const int verbosity = 12; }; #define copt dev::LogOutputStream() @@ -258,7 +271,7 @@ Assembly& Assembly::optimise(bool _enable) u256 mask = (u256(1) << testBit) - 1; return boost::multiprecision::bit_test(b, testBit) ? b | ~mask : b & mask; }; - map> c_simple = + map> const c_simple = { { Instruction::SUB, [](u256 a, u256 b)->u256{return a - b;} }, { Instruction::DIV, [](u256 a, u256 b)->u256{return a / b;} }, @@ -273,7 +286,7 @@ Assembly& Assembly::optimise(bool _enable) { Instruction::SGT, [](u256 a, u256 b)->u256{return u2s(a) > u2s(b) ? 1 : 0;} }, { Instruction::EQ, [](u256 a, u256 b)->u256{return a == b ? 1 : 0;} }, }; - map> c_associative = + map> const c_associative = { { Instruction::ADD, [](u256 a, u256 b)->u256{return a + b;} }, { Instruction::MUL, [](u256 a, u256 b)->u256{return a * b;} }, @@ -281,6 +294,8 @@ Assembly& Assembly::optimise(bool _enable) { Instruction::OR, [](u256 a, u256 b)->u256{return a | b;} }, { Instruction::XOR, [](u256 a, u256 b)->u256{return a ^ b;} }, }; + std::vector> const c_identities = + { { Instruction::ADD, 0}, { Instruction::MUL, 1}, { Instruction::MOD, 0}, { Instruction::OR, 0}, { Instruction::XOR, 0} }; std::vector>> rules = { { { Push, Instruction::POP }, [](AssemblyItemsConstRef) -> AssemblyItems { return {}; } }, @@ -299,8 +314,11 @@ Assembly& Assembly::optimise(bool _enable) rules.push_back({ { Push, Push, i.first }, [&](AssemblyItemsConstRef m) -> AssemblyItems { return { i.second(m[1].data(), m[0].data()) }; } }); rules.push_back({ { Push, i.first, Push, i.first }, [&](AssemblyItemsConstRef m) -> AssemblyItems { return { i.second(m[2].data(), m[0].data()), i.first }; } }); } + for (auto const& i: c_identities) + rules.push_back({{Push, i.first}, [&](AssemblyItemsConstRef m) -> AssemblyItems + { return m[0].data() == i.second ? AssemblyItems() : m.toVector(); }}); // jump to next instruction - rules.push_back({ { PushTag, Instruction::JUMP, Tag }, [&](AssemblyItemsConstRef m) -> AssemblyItems { if (m[0].m_data == m[2].m_data) return {m[2]}; else return m.toVector(); }}); + rules.push_back({ { PushTag, Instruction::JUMP, Tag }, [](AssemblyItemsConstRef m) -> AssemblyItems { if (m[0].m_data == m[2].m_data) return {m[2]}; else return m.toVector(); }}); // pop optimization, do not compute values that are popped again anyway rules.push_back({ { AssemblyItem(UndefinedItem), Instruction::POP }, [](AssemblyItemsConstRef m) -> AssemblyItems @@ -315,6 +333,29 @@ Assembly& Assembly::optimise(bool _enable) return m.toVector(); return AssemblyItems(info.args, Instruction::POP); } }); + // compute constants close to powers of two by expressions + auto computeConstants = [](AssemblyItemsConstRef m) -> AssemblyItems + { + u256 const& c = m[0].data(); + unsigned const minBits = 4 * 8; + if (c < (bigint(1) << minBits)) + return m.toVector(); // we need at least "PUSH1 PUSH1 <2> EXP" + if (c == u256(-1)) + return {u256(0), Instruction::NOT}; + for (unsigned bits = minBits; bits < 256; ++bits) + { + bigint const diff = c - (bigint(1) << bits); + if (abs(diff) > 0xff) + continue; + AssemblyItems powerOfTwo{u256(bits), u256(2), Instruction::EXP}; + if (diff == 0) + return powerOfTwo; + return AssemblyItems{u256(abs(diff))} + powerOfTwo + + AssemblyItems{diff > 0 ? Instruction::ADD : Instruction::SUB}; + } + return m.toVector(); + }; + rules.push_back({{Push}, computeConstants}); copt << *this; @@ -336,15 +377,27 @@ Assembly& Assembly::optimise(bool _enable) if (matches(vr, &r.first)) { auto rw = r.second(vr); - if (rw.size() < vr.size() || (rw.size() == vr.size() && popCountIncreased(vr, rw))) + unsigned const vrSize = bytesRequiredBySlice(vr.begin(), vr.end()); + unsigned const rwSize = bytesRequiredBySlice(rw.begin(), rw.end()); + //@todo check the actual size (including constant sizes) + if (rwSize < vrSize || (rwSize == vrSize && popCountIncreased(vr, rw))) { copt << vr << "matches" << AssemblyItemsConstRef(&r.first) << "becomes..."; - for (unsigned j = 0; j < vr.size(); ++j) + copt << AssemblyItemsConstRef(&rw); + if (rw.size() > vr.size()) + { + // create hole in the vector + unsigned sizeIncrease = rw.size() - vr.size(); + m_items.resize(m_items.size() + sizeIncrease, AssemblyItem(UndefinedItem)); + move_backward(m_items.begin() + i, m_items.end() - sizeIncrease, m_items.end()); + } + + for (unsigned j = 0; j < max(rw.size(), vr.size()); ++j) if (j < rw.size()) m_items[i + j] = rw[j]; else m_items.erase(m_items.begin() + i + rw.size()); - copt << AssemblyItemsConstRef(&rw); + count++; copt << "Now:\n" << m_items; } diff --git a/libevmcore/Assembly.h b/libevmcore/Assembly.h index b8e59a474..b144dd8d9 100644 --- a/libevmcore/Assembly.h +++ b/libevmcore/Assembly.h @@ -51,6 +51,9 @@ public: AssemblyItemType type() const { return m_type; } u256 data() const { return m_data; } + /// @returns an upper bound for the number of bytes required by this item, assuming that + /// the value of a jump tag takes @a _addressLength bytes. + unsigned bytesRequired(unsigned _addressLength) const; int deposit() const; bool match(AssemblyItem const& _i) const { return _i.m_type == UndefinedItem || (m_type == _i.m_type && (m_type != Operation || m_data == _i.m_data)); } diff --git a/libevmcore/CMakeLists.txt b/libevmcore/CMakeLists.txt index 738303271..9727ee1c9 100644 --- a/libevmcore/CMakeLists.txt +++ b/libevmcore/CMakeLists.txt @@ -1,20 +1,29 @@ cmake_policy(SET CMP0015 NEW) +# this policy was introduced in cmake 3.0 +# remove if, once 3.0 will be used on unix +if (${CMAKE_MAJOR_VERSION} GREATER 2) + # old policy do not use MACOSX_RPATH + cmake_policy(SET CMP0042 OLD) +endif() +set(CMAKE_AUTOMOC OFF) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DSTATICLIB") aux_source_directory(. SRC_LIST) +include_directories(${Boost_INCLUDE_DIRS}) +include_directories(..) + set(EXECUTABLE evmcore) file(GLOB HEADERS "*.h") -if(ETH_STATIC) + +if (ETH_STATIC) add_library(${EXECUTABLE} STATIC ${SRC_LIST} ${HEADERS}) else() add_library(${EXECUTABLE} SHARED ${SRC_LIST} ${HEADERS}) endif() -include_directories(..) - target_link_libraries(${EXECUTABLE} devcore) install( TARGETS ${EXECUTABLE} ARCHIVE DESTINATION lib LIBRARY DESTINATION lib ) diff --git a/libevmcore/Instruction.cpp b/libevmcore/Instruction.cpp index 5d94a22ca..b4a4d9f3b 100644 --- a/libevmcore/Instruction.cpp +++ b/libevmcore/Instruction.cpp @@ -282,11 +282,11 @@ static const std::map c_instructionInfo = { Instruction::SWAP14, { "SWAP14", 0, 15, 15, false } }, { Instruction::SWAP15, { "SWAP15", 0, 16, 16, false } }, { Instruction::SWAP16, { "SWAP16", 0, 17, 17, false } }, - { Instruction::LOG0, { "LOG0", 0, 1, 0, true } }, - { Instruction::LOG1, { "LOG1", 0, 2, 0, true } }, - { Instruction::LOG2, { "LOG2", 0, 3, 0, true } }, - { Instruction::LOG3, { "LOG3", 0, 4, 0, true } }, - { Instruction::LOG4, { "LOG4", 0, 5, 0, true } }, + { Instruction::LOG0, { "LOG0", 0, 2, 0, true } }, + { Instruction::LOG1, { "LOG1", 0, 3, 0, true } }, + { Instruction::LOG2, { "LOG2", 0, 4, 0, true } }, + { Instruction::LOG3, { "LOG3", 0, 5, 0, true } }, + { Instruction::LOG4, { "LOG4", 0, 6, 0, true } }, { Instruction::CREATE, { "CREATE", 0, 3, 1, true } }, { Instruction::CALL, { "CALL", 0, 7, 1, true } }, { Instruction::CALLCODE, { "CALLCODE", 0, 7, 1, true } }, @@ -326,7 +326,11 @@ InstructionInfo dev::eth::instructionInfo(Instruction _inst) } catch (...) { +#ifndef BOOST_NO_EXCEPTIONS cwarn << "\n" << boost::current_exception_diagnostic_information(); +#else + cwarn << "\n"; +#endif return InstructionInfo({"", 0, 0, 0, false}); } } diff --git a/libevmcore/Instruction.h b/libevmcore/Instruction.h index eb85c0610..f8a0478f1 100644 --- a/libevmcore/Instruction.h +++ b/libevmcore/Instruction.h @@ -168,8 +168,8 @@ enum class Instruction: uint8_t CREATE = 0xf0, ///< create a new account with associated code CALL, ///< message-call into an account + CALLCODE, ///< message-call with another account's code only RETURN, ///< halt execution returning output data - CALLCODE, SUICIDE = 0xff ///< halt execution and register account for later deletion }; diff --git a/libjsqrc/CMakeLists.txt b/libjsqrc/CMakeLists.txt index 9c505df2b..a6dbf023b 100644 --- a/libjsqrc/CMakeLists.txt +++ b/libjsqrc/CMakeLists.txt @@ -1,24 +1,15 @@ cmake_policy(SET CMP0015 NEW) - -# Find Qt5 for Apple and update src_list for windows -if (APPLE) - # homebrew defaults to qt4 and installs qt5 as 'keg-only' - # which places it into /usr/local/opt insteadof /usr/local. - - set(CMAKE_PREFIX_PATH /usr/local/opt/qt5) - include_directories(/usr/local/opt/qt5/include /usr/local/include) -elseif ("${TARGET_PLATFORM}" STREQUAL "w64") - set(SRC_LIST ${SRC_LIST} ../windows/qt_plugin_import.cpp) -elseif (UNIX) - set(CMAKE_PREFIX_PATH ${CMAKE_PREFIX_PATH} ";$ENV{QTDIR}/lib/cmake") -endif () - -find_package(Qt5Core) - +# let cmake autolink dependencies on windows +cmake_policy(SET CMP0020 NEW) +# this policy was introduced in cmake 3.0 +# remove if, once 3.0 will be used on unix +if (${CMAKE_MAJOR_VERSION} GREATER 2) + cmake_policy(SET CMP0043 OLD) +endif() set(CMAKE_AUTOMOC OFF) qt5_add_resources(JSQRC js.qrc) add_library(jsqrc STATIC ${JSQRC}) -qt5_use_modules(jsqrc Core) +target_link_libraries(jsqrc Qt5::Core) install( TARGETS jsqrc ARCHIVE DESTINATION lib LIBRARY DESTINATION lib ) diff --git a/libjsqrc/ethereum.js b/libjsqrc/ethereum.js new file mode 100644 index 000000000..cc8afc932 --- /dev/null +++ b/libjsqrc/ethereum.js @@ -0,0 +1,1068 @@ +require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o. +*/ +/** @file abi.js + * @authors: + * Marek Kotewicz + * @date 2014 + */ + +var findIndex = function (array, callback) { + var end = false; + var i = 0; + for (; i < array.length && !end; i++) { + end = callback(array[i]); + } + return end ? i - 1 : -1; +}; + +var findMethodIndex = function (json, methodName) { + return findIndex(json, function (method) { + return method.name === methodName; + }); +}; + +var padLeft = function (number, n) { + return (new Array(n * 2 - number.toString().length + 1)).join("0") + number; +}; + +var setupInputTypes = function () { + var prefixedType = function (prefix) { + return function (type, value) { + var expected = prefix; + if (type.indexOf(expected) !== 0) { + return false; + } + + var padding = parseInt(type.slice(expected.length)) / 8; + return padLeft(value, padding); + }; + }; + + var namedType = function (name, padding, formatter) { + return function (type, value) { + if (type !== name) { + return false; + } + + return padLeft(formatter ? value : formatter(value), padding); + }; + }; + + var formatBool = function (value) { + return value ? '1' : '0'; + }; + + return [ + prefixedType('uint'), + prefixedType('int'), + namedType('address', 20), + namedType('bool', 1, formatBool), + ]; +}; + +var inputTypes = setupInputTypes(); + +var toAbiInput = function (json, methodName, params) { + var bytes = ""; + var index = findMethodIndex(json, methodName); + + if (index === -1) { + return; + } + + // it needs to be checked in WebThreeStubServer + // something wrong might be with this additional zero + bytes = bytes + index + 'x' + '0'; + var method = json[index]; + + for (var i = 0; i < method.inputs.length; i++) { + var found = false; + for (var j = 0; j < inputTypes.length && !found; j++) { + var val = parseInt(params[i]).toString(16); + found = inputTypes[j](method.inputs[i].type, val); + } + if (!found) { + console.error('unsupported json type: ' + method.inputs[i].type); + } + bytes += found; + } + return bytes; +}; + +var setupOutputTypes = function () { + var prefixedType = function (prefix) { + return function (type) { + var expected = prefix; + if (type.indexOf(expected) !== 0) { + return -1; + } + + var padding = parseInt(type.slice(expected.length)) / 8; + return padding * 2; + }; + }; + + var namedType = function (name, padding) { + return function (type) { + return name === type ? padding * 2: -1; + }; + }; + + var formatInt = function (value) { + return parseInt(value, 16); + }; + + var formatBool = function (value) { + return value === '1' ? true : false; + }; + + return [ + { padding: prefixedType('uint'), format: formatInt }, + { padding: prefixedType('int'), format: formatInt }, + { padding: namedType('address', 20) }, + { padding: namedType('bool', 1), format: formatBool } + ]; +}; + +var outputTypes = setupOutputTypes(); + +var fromAbiOutput = function (json, methodName, output) { + var index = findMethodIndex(json, methodName); + + if (index === -1) { + return; + } + + output = output.slice(2); + + var result = []; + var method = json[index]; + for (var i = 0; i < method.outputs.length; i++) { + var padding = -1; + for (var j = 0; j < outputTypes.length && padding === -1; j++) { + padding = outputTypes[j].padding(method.outputs[i].type); + } + + if (padding === -1) { + // not found output parsing + continue; + } + var res = output.slice(0, padding); + var formatter = outputTypes[j - 1].format; + result.push(formatter ? formatter(res): res); + output = output.slice(padding); + } + + return result; +}; + +var inputParser = function (json) { + var parser = {}; + json.forEach(function (method) { + parser[method.name] = function () { + var params = Array.prototype.slice.call(arguments); + return toAbiInput(json, method.name, params); + }; + }); + + return parser; +}; + +var outputParser = function (json) { + var parser = {}; + json.forEach(function (method) { + parser[method.name] = function (output) { + return fromAbiOutput(json, method.name, output); + }; + }); + + return parser; +}; + +module.exports = { + inputParser: inputParser, + outputParser: outputParser +}; + + +},{}],2:[function(require,module,exports){ +/* + This file is part of ethereum.js. + + ethereum.js 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. + + ethereum.js 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 ethereum.js. If not, see . +*/ +/** @file autoprovider.js + * @authors: + * Marek Kotewicz + * Marian Oancea + * @date 2014 + */ + +/* + * @brief if qt object is available, uses QtProvider, + * if not tries to connect over websockets + * if it fails, it uses HttpRpcProvider + */ +if ("build" !== 'build') {/* + var WebSocket = require('ws'); // jshint ignore:line + var web3 = require('./main.js'); // jshint ignore:line +*/} + +var AutoProvider = function (userOptions) { + if (web3.haveProvider()) { + return; + } + + // before we determine what provider we are, we have to cache request + this.sendQueue = []; + this.onmessageQueue = []; + + if (navigator.qt) { + this.provider = new web3.providers.QtProvider(); + return; + } + + userOptions = userOptions || {}; + var options = { + httprpc: userOptions.httprpc || 'http://localhost:8080', + websockets: userOptions.websockets || 'ws://localhost:40404/eth' + }; + + var self = this; + var closeWithSuccess = function (success) { + ws.close(); + if (success) { + self.provider = new web3.providers.WebSocketProvider(options.websockets); + } else { + self.provider = new web3.providers.HttpRpcProvider(options.httprpc); + self.poll = self.provider.poll.bind(self.provider); + } + self.sendQueue.forEach(function (payload) { + self.provider(payload); + }); + self.onmessageQueue.forEach(function (handler) { + self.provider.onmessage = handler; + }); + }; + + var ws = new WebSocket(options.websockets); + + ws.onopen = function() { + closeWithSuccess(true); + }; + + ws.onerror = function() { + closeWithSuccess(false); + }; +}; + +AutoProvider.prototype.send = function (payload) { + if (this.provider) { + this.provider.send(payload); + return; + } + this.sendQueue.push(payload); +}; + +Object.defineProperty(AutoProvider.prototype, 'onmessage', { + set: function (handler) { + if (this.provider) { + this.provider.onmessage = handler; + return; + } + this.onmessageQueue.push(handler); + } +}); + +module.exports = AutoProvider; + +},{}],3:[function(require,module,exports){ +/* + This file is part of ethereum.js. + + ethereum.js 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. + + ethereum.js 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 ethereum.js. If not, see . +*/ +/** @file contract.js + * @authors: + * Marek Kotewicz + * @date 2014 + */ + +if ("build" !== 'build') {/* + var web3 = require('./web3'); // jshint ignore:line +*/} +var abi = require('./abi'); + +var contract = function (address, desc) { + var inputParser = abi.inputParser(desc); + var outputParser = abi.outputParser(desc); + + var contract = {}; + + desc.forEach(function (method) { + contract[method.name] = function () { + var params = Array.prototype.slice.call(arguments); + var parsed = inputParser[method.name].apply(null, params); + + var onSuccess = function (result) { + return outputParser[method.name](result); + }; + + return { + call: function (extra) { + extra = extra || {}; + extra.to = address; + extra.data = parsed; + return web3.eth.call(extra).then(onSuccess); + }, + transact: function (extra) { + extra = extra || {}; + extra.to = address; + extra.data = parsed; + return web3.eth.transact(extra).then(onSuccess); + } + }; + }; + }); + + return contract; +}; + +module.exports = contract; + +},{"./abi":1}],4:[function(require,module,exports){ +/* + This file is part of ethereum.js. + + ethereum.js 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. + + ethereum.js 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 ethereum.js. If not, see . +*/ +/** @file httprpc.js + * @authors: + * Marek Kotewicz + * Marian Oancea + * @date 2014 + */ + +if ("build" !== "build") {/* + var XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest; // jshint ignore:line +*/} + +var HttpRpcProvider = function (host) { + this.handlers = []; + this.host = host; +}; + +function formatJsonRpcObject(object) { + return { + jsonrpc: '2.0', + method: object.call, + params: object.args, + id: object._id + }; +} + +function formatJsonRpcMessage(message) { + var object = JSON.parse(message); + + return { + _id: object.id, + data: object.result, + error: object.error + }; +} + +HttpRpcProvider.prototype.sendRequest = function (payload, cb) { + var data = formatJsonRpcObject(payload); + + var request = new XMLHttpRequest(); + request.open("POST", this.host, true); + request.send(JSON.stringify(data)); + request.onreadystatechange = function () { + if (request.readyState === 4 && cb) { + cb(request); + } + }; +}; + +HttpRpcProvider.prototype.send = function (payload) { + var self = this; + this.sendRequest(payload, function (request) { + self.handlers.forEach(function (handler) { + handler.call(self, formatJsonRpcMessage(request.responseText)); + }); + }); +}; + +HttpRpcProvider.prototype.poll = function (payload, id) { + var self = this; + this.sendRequest(payload, function (request) { + var parsed = JSON.parse(request.responseText); + if (parsed.error || (parsed.result instanceof Array ? parsed.result.length === 0 : !parsed.result)) { + return; + } + self.handlers.forEach(function (handler) { + handler.call(self, {_event: payload.call, _id: id, data: parsed.result}); + }); + }); +}; + +Object.defineProperty(HttpRpcProvider.prototype, "onmessage", { + set: function (handler) { + this.handlers.push(handler); + } +}); + +module.exports = HttpRpcProvider; + +},{}],5:[function(require,module,exports){ +/* + This file is part of ethereum.js. + + ethereum.js 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. + + ethereum.js 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 ethereum.js. If not, see . +*/ +/** @file main.js + * @authors: + * Jeffrey Wilcke + * Marek Kotewicz + * Marian Oancea + * @date 2014 + */ + +function flattenPromise (obj) { + if (obj instanceof Promise) { + return Promise.resolve(obj); + } + + if (obj instanceof Array) { + return new Promise(function (resolve) { + var promises = obj.map(function (o) { + return flattenPromise(o); + }); + + return Promise.all(promises).then(function (res) { + for (var i = 0; i < obj.length; i++) { + obj[i] = res[i]; + } + resolve(obj); + }); + }); + } + + if (obj instanceof Object) { + return new Promise(function (resolve) { + var keys = Object.keys(obj); + var promises = keys.map(function (key) { + return flattenPromise(obj[key]); + }); + + return Promise.all(promises).then(function (res) { + for (var i = 0; i < keys.length; i++) { + obj[keys[i]] = res[i]; + } + resolve(obj); + }); + }); + } + + return Promise.resolve(obj); +} + +var ethMethods = function () { + var blockCall = function (args) { + return typeof args[0] === "string" ? "eth_blockByHash" : "eth_blockByNumber"; + }; + + var transactionCall = function (args) { + return typeof args[0] === "string" ? 'eth_transactionByHash' : 'eth_transactionByNumber'; + }; + + var uncleCall = function (args) { + return typeof args[0] === "string" ? 'eth_uncleByHash' : 'eth_uncleByNumber'; + }; + + var methods = [ + { name: 'balanceAt', call: 'eth_balanceAt' }, + { name: 'stateAt', call: 'eth_stateAt' }, + { name: 'storageAt', call: 'eth_storageAt' }, + { name: 'countAt', call: 'eth_countAt'}, + { name: 'codeAt', call: 'eth_codeAt' }, + { name: 'transact', call: 'eth_transact' }, + { name: 'call', call: 'eth_call' }, + { name: 'block', call: blockCall }, + { name: 'transaction', call: transactionCall }, + { name: 'uncle', call: uncleCall }, + { name: 'compilers', call: 'eth_compilers' }, + { name: 'lll', call: 'eth_lll' }, + { name: 'solidity', call: 'eth_solidity' }, + { name: 'serpent', call: 'eth_serpent' }, + { name: 'logs', call: 'eth_logs' } + ]; + return methods; +}; + +var ethProperties = function () { + return [ + { name: 'coinbase', getter: 'eth_coinbase', setter: 'eth_setCoinbase' }, + { name: 'listening', getter: 'eth_listening', setter: 'eth_setListening' }, + { name: 'mining', getter: 'eth_mining', setter: 'eth_setMining' }, + { name: 'gasPrice', getter: 'eth_gasPrice' }, + { name: 'account', getter: 'eth_account' }, + { name: 'accounts', getter: 'eth_accounts' }, + { name: 'peerCount', getter: 'eth_peerCount' }, + { name: 'defaultBlock', getter: 'eth_defaultBlock', setter: 'eth_setDefaultBlock' }, + { name: 'number', getter: 'eth_number'} + ]; +}; + +var dbMethods = function () { + return [ + { name: 'put', call: 'db_put' }, + { name: 'get', call: 'db_get' }, + { name: 'putString', call: 'db_putString' }, + { name: 'getString', call: 'db_getString' } + ]; +}; + +var shhMethods = function () { + return [ + { name: 'post', call: 'shh_post' }, + { name: 'newIdentity', call: 'shh_newIdentity' }, + { name: 'haveIdentity', call: 'shh_haveIdentity' }, + { name: 'newGroup', call: 'shh_newGroup' }, + { name: 'addToGroup', call: 'shh_addToGroup' } + ]; +}; + +var ethWatchMethods = function () { + var newFilter = function (args) { + return typeof args[0] === 'string' ? 'eth_newFilterString' : 'eth_newFilter'; + }; + + return [ + { name: 'newFilter', call: newFilter }, + { name: 'uninstallFilter', call: 'eth_uninstallFilter' }, + { name: 'getMessages', call: 'eth_filterLogs' } + ]; +}; + +var shhWatchMethods = function () { + return [ + { name: 'newFilter', call: 'shh_newFilter' }, + { name: 'uninstallFilter', call: 'shh_uninstallFilter' }, + { name: 'getMessage', call: 'shh_getMessages' } + ]; +}; + +var setupMethods = function (obj, methods) { + methods.forEach(function (method) { + obj[method.name] = function () { + return flattenPromise(Array.prototype.slice.call(arguments)).then(function (args) { + var call = typeof method.call === "function" ? method.call(args) : method.call; + return {call: call, args: args}; + }).then(function (request) { + return new Promise(function (resolve, reject) { + web3.provider.send(request, function (err, result) { + if (!err) { + resolve(result); + return; + } + reject(err); + }); + }); + }).catch(function(err) { + console.error(err); + }); + }; + }); +}; + +var setupProperties = function (obj, properties) { + properties.forEach(function (property) { + var proto = {}; + proto.get = function () { + return new Promise(function(resolve, reject) { + web3.provider.send({call: property.getter}, function(err, result) { + if (!err) { + resolve(result); + return; + } + reject(err); + }); + }); + }; + if (property.setter) { + proto.set = function (val) { + return flattenPromise([val]).then(function (args) { + return new Promise(function (resolve) { + web3.provider.send({call: property.setter, args: args}, function (err, result) { + if (!err) { + resolve(result); + return; + } + reject(err); + }); + }); + }).catch(function (err) { + console.error(err); + }); + }; + } + Object.defineProperty(obj, property.name, proto); + }); +}; + +var web3 = { + _callbacks: {}, + _events: {}, + providers: {}, + toHex: function(str) { + var hex = ""; + for(var i = 0; i < str.length; i++) { + var n = str.charCodeAt(i).toString(16); + hex += n.length < 2 ? '0' + n : n; + } + + return hex; + }, + + toAscii: function(hex) { + // Find termination + var str = ""; + var i = 0, l = hex.length; + if (hex.substring(0, 2) === '0x') + i = 2; + for(; i < l; i+=2) { + var code = hex.charCodeAt(i); + if(code === 0) { + break; + } + + str += String.fromCharCode(parseInt(hex.substr(i, 2), 16)); + } + + return str; + }, + + toDecimal: function (val) { + return parseInt(val, 16); + }, + + fromAscii: function(str, pad) { + pad = pad === undefined ? 32 : pad; + var hex = this.toHex(str); + while(hex.length < pad*2) + hex += "00"; + return "0x" + hex; + }, + + eth: { + prototype: Object(), // jshint ignore:line + watch: function (params) { + return new Filter(params, ethWatch); + } + }, + + db: { + prototype: Object() // jshint ignore:line + }, + + shh: { + prototype: Object(), // jshint ignore:line + watch: function (params) { + return new Filter(params, shhWatch); + } + }, + + on: function(event, id, cb) { + if(web3._events[event] === undefined) { + web3._events[event] = {}; + } + + web3._events[event][id] = cb; + return this; + }, + + off: function(event, id) { + if(web3._events[event] !== undefined) { + delete web3._events[event][id]; + } + + return this; + }, + + trigger: function(event, id, data) { + var callbacks = web3._events[event]; + if (!callbacks || !callbacks[id]) { + return; + } + var cb = callbacks[id]; + cb(data); + } +}; + +setupMethods(web3.eth, ethMethods()); +setupProperties(web3.eth, ethProperties()); +setupMethods(web3.db, dbMethods()); +setupMethods(web3.shh, shhMethods()); + +var ethWatch = { + changed: 'eth_changed' +}; +setupMethods(ethWatch, ethWatchMethods()); +var shhWatch = { + changed: 'shh_changed' +}; +setupMethods(shhWatch, shhWatchMethods()); + +var ProviderManager = function() { + this.queued = []; + this.polls = []; + this.ready = false; + this.provider = undefined; + this.id = 1; + + var self = this; + var poll = function () { + if (self.provider && self.provider.poll) { + self.polls.forEach(function (data) { + data.data._id = self.id; + self.id++; + self.provider.poll(data.data, data.id); + }); + } + setTimeout(poll, 12000); + }; + poll(); +}; + +ProviderManager.prototype.send = function(data, cb) { + data._id = this.id; + if (cb) { + web3._callbacks[data._id] = cb; + } + + data.args = data.args || []; + this.id++; + + if(this.provider !== undefined) { + this.provider.send(data); + } else { + console.warn("provider is not set"); + this.queued.push(data); + } +}; + +ProviderManager.prototype.set = function(provider) { + if(this.provider !== undefined && this.provider.unload !== undefined) { + this.provider.unload(); + } + + this.provider = provider; + this.ready = true; +}; + +ProviderManager.prototype.sendQueued = function() { + for(var i = 0; this.queued.length; i++) { + // Resend + this.send(this.queued[i]); + } +}; + +ProviderManager.prototype.installed = function() { + return this.provider !== undefined; +}; + +ProviderManager.prototype.startPolling = function (data, pollId) { + if (!this.provider || !this.provider.poll) { + return; + } + this.polls.push({data: data, id: pollId}); +}; + +ProviderManager.prototype.stopPolling = function (pollId) { + for (var i = this.polls.length; i--;) { + var poll = this.polls[i]; + if (poll.id === pollId) { + this.polls.splice(i, 1); + } + } +}; + +web3.provider = new ProviderManager(); + +web3.setProvider = function(provider) { + provider.onmessage = messageHandler; + web3.provider.set(provider); + web3.provider.sendQueued(); +}; + +web3.haveProvider = function() { + return !!web3.provider.provider; +}; + +var Filter = function(options, impl) { + this.impl = impl; + this.callbacks = []; + + var self = this; + this.promise = impl.newFilter(options); + this.promise.then(function (id) { + self.id = id; + web3.on(impl.changed, id, self.trigger.bind(self)); + web3.provider.startPolling({call: impl.changed, args: [id]}, id); + }); +}; + +Filter.prototype.arrived = function(callback) { + this.changed(callback); +}; + +Filter.prototype.changed = function(callback) { + var self = this; + this.promise.then(function(id) { + self.callbacks.push(callback); + }); +}; + +Filter.prototype.trigger = function(messages) { + for(var i = 0; i < this.callbacks.length; i++) { + this.callbacks[i].call(this, messages); + } +}; + +Filter.prototype.uninstall = function() { + var self = this; + this.promise.then(function (id) { + self.impl.uninstallFilter(id); + web3.provider.stopPolling(id); + web3.off(impl.changed, id); + }); +}; + +Filter.prototype.messages = function() { + var self = this; + return this.promise.then(function (id) { + return self.impl.getMessages(id); + }); +}; + +Filter.prototype.logs = function () { + return this.messages(); +}; + +function messageHandler(data) { + if(data._event !== undefined) { + web3.trigger(data._event, data._id, data.data); + return; + } + + if(data._id) { + var cb = web3._callbacks[data._id]; + if (cb) { + cb.call(this, data.error, data.data); + delete web3._callbacks[data._id]; + } + } +} + +module.exports = web3; + + +},{}],6:[function(require,module,exports){ +/* + This file is part of ethereum.js. + + ethereum.js 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. + + ethereum.js 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 ethereum.js. If not, see . +*/ +/** @file qt.js + * @authors: + * Jeffrey Wilcke + * Marek Kotewicz + * @date 2014 + */ + +var QtProvider = function() { + this.handlers = []; + + var self = this; + navigator.qt.onmessage = function (message) { + self.handlers.forEach(function (handler) { + handler.call(self, JSON.parse(message.data)); + }); + }; +}; + +QtProvider.prototype.send = function(payload) { + navigator.qt.postMessage(JSON.stringify(payload)); +}; + +Object.defineProperty(QtProvider.prototype, "onmessage", { + set: function(handler) { + this.handlers.push(handler); + } +}); + +module.exports = QtProvider; + +},{}],7:[function(require,module,exports){ +/* + This file is part of ethereum.js. + + ethereum.js 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. + + ethereum.js 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 ethereum.js. If not, see . +*/ +/** @file websocket.js + * @authors: + * Jeffrey Wilcke + * Marek Kotewicz + * Marian Oancea + * @date 2014 + */ + +if ("build" !== "build") {/* + var WebSocket = require('ws'); // jshint ignore:line +*/} + +var WebSocketProvider = function(host) { + // onmessage handlers + this.handlers = []; + // queue will be filled with messages if send is invoked before the ws is ready + this.queued = []; + this.ready = false; + + this.ws = new WebSocket(host); + + var self = this; + this.ws.onmessage = function(event) { + for(var i = 0; i < self.handlers.length; i++) { + self.handlers[i].call(self, JSON.parse(event.data), event); + } + }; + + this.ws.onopen = function() { + self.ready = true; + + for(var i = 0; i < self.queued.length; i++) { + // Resend + self.send(self.queued[i]); + } + }; +}; + +WebSocketProvider.prototype.send = function(payload) { + if(this.ready) { + var data = JSON.stringify(payload); + + this.ws.send(data); + } else { + this.queued.push(payload); + } +}; + +WebSocketProvider.prototype.onMessage = function(handler) { + this.handlers.push(handler); +}; + +WebSocketProvider.prototype.unload = function() { + this.ws.close(); +}; +Object.defineProperty(WebSocketProvider.prototype, "onmessage", { + set: function(provider) { this.onMessage(provider); } +}); + +module.exports = WebSocketProvider; + +},{}],"web3":[function(require,module,exports){ +var web3 = require('./lib/main'); +web3.providers.WebSocketProvider = require('./lib/websocket'); +web3.providers.HttpRpcProvider = require('./lib/httprpc'); +web3.providers.QtProvider = require('./lib/qt'); +web3.providers.AutoProvider = require('./lib/autoprovider'); +web3.contract = require('./lib/contract'); + +module.exports = web3; + +},{"./lib/autoprovider":2,"./lib/contract":3,"./lib/httprpc":4,"./lib/main":5,"./lib/qt":6,"./lib/websocket":7}]},{},[]) + + +//# sourceMappingURL=ethereum.js.map \ No newline at end of file diff --git a/libjsqrc/js.qrc b/libjsqrc/js.qrc index fbfef2d7b..56cab75f1 100644 --- a/libjsqrc/js.qrc +++ b/libjsqrc/js.qrc @@ -2,7 +2,6 @@ es6-promise-2.0.0.js setup.js - main.js - qt.js + ethereum.js diff --git a/libjsqrc/main.js b/libjsqrc/main.js deleted file mode 100644 index 09fe00105..000000000 --- a/libjsqrc/main.js +++ /dev/null @@ -1,467 +0,0 @@ -/* - This file is part of ethereum.js. - - ethereum.js 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. - - ethereum.js 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 ethereum.js. If not, see . -*/ -/** @file main.js - * @authors: - * Marek Kotewicz - * @date 2014 - */ - -(function(window) { - function isPromise(o) { - return o instanceof Promise - } - - function flattenPromise (obj) { - if (obj instanceof Promise) { - return Promise.resolve(obj); - } - - if (obj instanceof Array) { - return new Promise(function (resolve) { - var promises = obj.map(function (o) { - return flattenPromise(o); - }); - - return Promise.all(promises).then(function (res) { - for (var i = 0; i < obj.length; i++) { - obj[i] = res[i]; - } - resolve(obj); - }); - }); - } - - if (obj instanceof Object) { - return new Promise(function (resolve) { - var keys = Object.keys(obj); - var promises = keys.map(function (key) { - return flattenPromise(obj[key]); - }); - - return Promise.all(promises).then(function (res) { - for (var i = 0; i < keys.length; i++) { - obj[keys[i]] = res[i]; - } - resolve(obj); - }); - }); - } - - return Promise.resolve(obj); - }; - - var ethMethods = function () { - var blockCall = function (args) { - return typeof args[0] === "string" ? "eth_blockByHash" : "eth_blockByNumber"; - }; - - var transactionCall = function (args) { - return typeof args[0] === "string" ? 'eth_transactionByHash' : 'eth_transactionByNumber'; - }; - - var uncleCall = function (args) { - return typeof args[0] === "string" ? 'eth_uncleByHash' : 'eth_uncleByNumber'; - }; - - var methods = [ - { name: 'balanceAt', call: 'eth_balanceAt' }, - { name: 'stateAt', call: 'eth_stateAt' }, - { name: 'countAt', call: 'eth_countAt'}, - { name: 'codeAt', call: 'eth_codeAt' }, - { name: 'transact', call: 'eth_transact' }, - { name: 'call', call: 'eth_call' }, - { name: 'block', call: blockCall }, - { name: 'transaction', call: transactionCall }, - { name: 'uncle', call: uncleCall }, - { name: 'compile', call: 'eth_compile' }, - { name: 'lll', call: 'eth_lll' } - ]; - return methods; - }; - - var ethProperties = function () { - return [ - { name: 'coinbase', getter: 'eth_coinbase', setter: 'eth_setCoinbase' }, - { name: 'listening', getter: 'eth_listening', setter: 'eth_setListening' }, - { name: 'mining', getter: 'eth_mining', setter: 'eth_setMining' }, - { name: 'gasPrice', getter: 'eth_gasPrice' }, - { name: 'account', getter: 'eth_account' }, - { name: 'accounts', getter: 'eth_accounts' }, - { name: 'peerCount', getter: 'eth_peerCount' }, - { name: 'defaultBlock', getter: 'eth_defaultBlock', setter: 'eth_setDefaultBlock' }, - { name: 'number', getter: 'eth_number'} - ]; - }; - - var dbMethods = function () { - return [ - { name: 'put', call: 'db_put' }, - { name: 'get', call: 'db_get' }, - { name: 'putString', call: 'db_putString' }, - { name: 'getString', call: 'db_getString' } - ]; - }; - - var shhMethods = function () { - return [ - { name: 'post', call: 'shh_post' }, - { name: 'newIdentity', call: 'shh_newIdentity' }, - { name: 'haveIdentity', call: 'shh_haveIdentity' }, - { name: 'newGroup', call: 'shh_newGroup' }, - { name: 'addToGroup', call: 'shh_addToGroup' } - ]; - }; - - var ethWatchMethods = function () { - var newFilter = function (args) { - return typeof args[0] === 'string' ? 'eth_newFilterString' : 'eth_newFilter'; - }; - - return [ - { name: 'newFilter', call: newFilter }, - { name: 'uninstallFilter', call: 'eth_uninstallFilter' }, - { name: 'getMessages', call: 'eth_getMessages' } - ]; - }; - - var shhWatchMethods = function () { - return [ - { name: 'newFilter', call: 'shh_newFilter' }, - { name: 'uninstallFilter', call: 'shh_uninstallFilter' }, - { name: 'getMessage', call: 'shh_getMessages' } - ]; - }; - - var setupMethods = function (obj, methods) { - methods.forEach(function (method) { - obj[method.name] = function () { - return flattenPromise(Array.prototype.slice.call(arguments)).then(function (args) { - var call = typeof method.call === "function" ? method.call(args) : method.call; - return {call: call, args: args}; - }).then(function (request) { - return new Promise(function (resolve, reject) { - web3.provider.send(request, function (err, result) { - if (!err) { - resolve(result); - return; - } - reject(err); - }); - }); - }).catch(function(err) { - console.error(err); - }); - }; - }); - }; - - var setupProperties = function (obj, properties) { - properties.forEach(function (property) { - var proto = {}; - proto.get = function () { - return new Promise(function(resolve, reject) { - web3.provider.send({call: property.getter}, function(err, result) { - if (!err) { - resolve(result); - return; - } - reject(err); - }); - }); - }; - if (property.setter) { - proto.set = function (val) { - return flattenPromise([val]).then(function (args) { - return new Promise(function (resolve) { - web3.provider.send({call: property.setter, args: args}, function (err, result) { - if (!err) { - resolve(result); - return; - } - reject(err); - }); - }); - }).catch(function (err) { - console.error(err); - }); - } - } - Object.defineProperty(obj, property.name, proto); - }); - }; - - var web3 = { - _callbacks: {}, - _events: {}, - providers: {}, - toHex: function(str) { - var hex = ""; - for(var i = 0; i < str.length; i++) { - var n = str.charCodeAt(i).toString(16); - hex += n.length < 2 ? '0' + n : n; - } - - return hex; - }, - - toAscii: function(hex) { - // Find termination - var str = ""; - var i = 0, l = hex.length; - if (hex.substring(0, 2) == '0x') - i = 2; - for(; i < l; i+=2) { - var code = hex.charCodeAt(i) - if(code == 0) { - break; - } - - str += String.fromCharCode(parseInt(hex.substr(i, 2), 16)); - } - - return str; - }, - - toDecimal: function (val) { - return parseInt(val, 16); - }, - - fromAscii: function(str, pad) { - pad = pad === undefined ? 32 : pad; - var hex = this.toHex(str); - while(hex.length < pad*2) - hex += "00"; - return "0x" + hex; - }, - - eth: { - prototype: Object(), - watch: function (params) { - return new Filter(params, ethWatch); - }, - }, - - db: { - prototype: Object() - }, - - shh: { - prototype: Object(), - watch: function (params) { - return new Filter(params, shhWatch); - } - }, - - on: function(event, id, cb) { - if(web3._events[event] === undefined) { - web3._events[event] = {}; - } - - web3._events[event][id] = cb; - return this - }, - - off: function(event, id) { - if(web3._events[event] !== undefined) { - delete web3._events[event][id]; - } - - return this - }, - - trigger: function(event, id, data) { - var callbacks = web3._events[event]; - if (!callbacks || !callbacks[id]) { - return; - } - var cb = callbacks[id]; - cb(data); - }, - }; - - var eth = web3.eth; - setupMethods(eth, ethMethods()); - setupProperties(eth, ethProperties()); - setupMethods(web3.db, dbMethods()); - setupMethods(web3.shh, shhMethods()); - - var ethWatch = { - changed: 'eth_changed' - }; - setupMethods(ethWatch, ethWatchMethods()); - var shhWatch = { - changed: 'shh_changed' - }; - setupMethods(shhWatch, shhWatchMethods()); - - var ProviderManager = function() { - this.queued = []; - this.polls = []; - this.ready = false; - this.provider = undefined; - this.id = 1; - - var self = this; - var poll = function () { - if (self.provider && self.provider.poll) { - self.polls.forEach(function (data) { - data.data._id = self.id; - self.id++; - self.provider.poll(data.data, data.id); - }); - } - setTimeout(poll, 12000); - }; - poll(); - }; - - ProviderManager.prototype.send = function(data, cb) { - data._id = this.id; - if (cb) { - web3._callbacks[data._id] = cb; - } - - data.args = data.args || []; - this.id++; - - if(this.provider !== undefined) { - this.provider.send(data); - } else { - console.warn("provider is not set"); - this.queued.push(data); - } - }; - - ProviderManager.prototype.set = function(provider) { - if(this.provider !== undefined && this.provider.unload !== undefined) { - this.provider.unload(); - } - - this.provider = provider; - this.ready = true; - }; - - ProviderManager.prototype.sendQueued = function() { - for(var i = 0; this.queued.length; i++) { - // Resend - this.send(this.queued[i]); - } - }; - - ProviderManager.prototype.installed = function() { - return this.provider !== undefined; - }; - - ProviderManager.prototype.startPolling = function (data, pollId) { - if (!this.provider || !this.provider.poll) { - return; - } - this.polls.push({data: data, id: pollId}); - }; - - ProviderManager.prototype.stopPolling = function (pollId) { - for (var i = this.polls.length; i--;) { - var poll = this.polls[i]; - if (poll.id === pollId) { - this.polls.splice(i, 1); - } - } - }; - - web3.provider = new ProviderManager(); - - web3.setProvider = function(provider) { - provider.onmessage = messageHandler; - web3.provider.set(provider); - web3.provider.sendQueued(); - }; - - var Filter = function(options, impl) { - this.impl = impl; - this.callbacks = []; - - var self = this; - this.promise = impl.newFilter(options); - this.promise.then(function (id) { - self.id = id; - web3.on(impl.changed, id, self.trigger.bind(self)); - web3.provider.startPolling({call: impl.changed, args: [id]}, id); - }); - }; - - Filter.prototype.arrived = function(callback) { - this.changed(callback); - } - - Filter.prototype.changed = function(callback) { - var self = this; - this.promise.then(function(id) { - self.callbacks.push(callback); - }); - }; - - Filter.prototype.trigger = function(messages) { - if (!(messages instanceof Array) || messages.length) { - for(var i = 0; i < this.callbacks.length; i++) { - this.callbacks[i].call(this, messages); - } - } - }; - - Filter.prototype.uninstall = function() { - var self = this; - this.promise.then(function (id) { - self.impl.uninstallFilter(id); - web3.provider.stopPolling(id); - web3.off(impl.changed, id); - }); - }; - - Filter.prototype.messages = function() { - var self = this; - return this.promise.then(function (id) { - return self.impl.getMessages(id); - }); - }; - - function messageHandler(data) { - if(data._event !== undefined) { - web3.trigger(data._event, data._id, data.data); - return; - } - - if(data._id) { - var cb = web3._callbacks[data._id]; - if (cb) { - cb.call(this, data.error, data.data); - delete web3._callbacks[data._id]; - } - } - } - - /* - // Install default provider - if(!web3.provider.installed()) { - var sock = new web3.WebSocket("ws://localhost:40404/eth"); - - web3.setProvider(sock); - } - */ - - window.web3 = web3; - -})(this); diff --git a/libjsqrc/qt.js b/libjsqrc/qt.js deleted file mode 100644 index aedd34236..000000000 --- a/libjsqrc/qt.js +++ /dev/null @@ -1,49 +0,0 @@ -/* - This file is part of ethereum.js. - - ethereum.js 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. - - ethereum.js 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 ethereum.js. If not, see . -*/ -/** @file qt.js - * @authors: - * Marek Kotewicz - * @date 2014 - */ - -(function() { - var QtProvider = function() { - this.handlers = []; - - var self = this; - navigator.qt.onmessage = function (message) { - self.handlers.forEach(function (handler) { - handler.call(self, JSON.parse(message.data)); - }); - } - }; - - QtProvider.prototype.send = function(payload) { - navigator.qt.postMessage(JSON.stringify(payload)); - }; - - Object.defineProperty(QtProvider.prototype, "onmessage", { - set: function(handler) { - this.handlers.push(handler); - }, - }); - - if(typeof(web3) !== "undefined" && web3.providers !== undefined) { - web3.providers.QtProvider = QtProvider; - } -})(); - diff --git a/libjsqrc/setup.js b/libjsqrc/setup.js index 5142412a6..b83745c33 100644 --- a/libjsqrc/setup.js +++ b/libjsqrc/setup.js @@ -41,4 +41,6 @@ if (window.Promise === undefined) { window.Promise = ES6Promise.Promise; } +var web3 = require('web3'); web3.setProvider(new web3.providers.QtProvider()); + diff --git a/liblll/CMakeLists.txt b/liblll/CMakeLists.txt index 8b1581785..fb79d5873 100644 --- a/liblll/CMakeLists.txt +++ b/liblll/CMakeLists.txt @@ -1,48 +1,32 @@ cmake_policy(SET CMP0015 NEW) +# this policy was introduced in cmake 3.0 +# remove if, once 3.0 will be used on unix +if (${CMAKE_MAJOR_VERSION} GREATER 2) + # old policy do not use MACOSX_RPATH + cmake_policy(SET CMP0042 OLD) +endif() +set(CMAKE_AUTOMOC OFF) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DSTATICLIB") aux_source_directory(. SRC_LIST) +include_directories(${Boost_INCLUDE_DIRS}) +include_directories(..) + set(EXECUTABLE lll) file(GLOB HEADERS "*.h") + if(ETH_STATIC) add_library(${EXECUTABLE} STATIC ${SRC_LIST} ${HEADERS}) else() add_library(${EXECUTABLE} SHARED ${SRC_LIST} ${HEADERS}) endif() -include_directories(..) - target_link_libraries(${EXECUTABLE} evmcore) target_link_libraries(${EXECUTABLE} devcore) - -if("${TARGET_PLATFORM}" STREQUAL "w64") - target_link_libraries(${EXECUTABLE} boost_system-mt-s) - target_link_libraries(${EXECUTABLE} boost_thread_win32-mt-s) - target_link_libraries(${EXECUTABLE} iphlpapi) - target_link_libraries(${EXECUTABLE} ws2_32) - target_link_libraries(${EXECUTABLE} mswsock) - target_link_libraries(${EXECUTABLE} shlwapi) -elseif (APPLE) - # Latest mavericks boost libraries only come with -mt - target_link_libraries(${EXECUTABLE} boost_system-mt) - target_link_libraries(${EXECUTABLE} boost_thread-mt) - find_package(Threads REQUIRED) - target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT}) -elseif (UNIX) - target_link_libraries(${EXECUTABLE} ${Boost_SYSTEM_LIBRARY}) - target_link_libraries(${EXECUTABLE} ${Boost_THREAD_LIBRARY}) - target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT}) -else () - target_link_libraries(${EXECUTABLE} boost_system) - target_link_libraries(${EXECUTABLE} boost_thread) - find_package(Threads REQUIRED) - target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT}) -endif () - install( TARGETS ${EXECUTABLE} ARCHIVE DESTINATION lib LIBRARY DESTINATION lib ) install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} ) diff --git a/liblll/CompilerState.cpp b/liblll/CompilerState.cpp index c3dc2dda3..63351bc4c 100644 --- a/liblll/CompilerState.cpp +++ b/liblll/CompilerState.cpp @@ -72,6 +72,11 @@ void CompilerState::populateStandard() "(def 'regname (name) { [32]'register [64]name (call allgas namereg 0 32 64 0 0) })" "(def 'regcoin (name) { [32]name (call allgas coinreg 0 32 32 0 0) })" "(def 'regcoin (name denom) { [32]name [64]denom (call allgas coinreg 0 32 64 0 0) })" + "(def 'ecrecover (r s v hash) { [0] r [32] s [64] v [96] hash (msg allgas 1 0 0 128) })" + "(def 'sha256 (data datasize) (msg allgas 2 0 data datasize))" + "(def 'ripemd160 (data datasize) (msg allgas 3 0 data datasize))" + "(def 'sha256 (val) { [0]:val (sha256 0 32) })" + "(def 'ripemd160 (val) { [0]:val (ripemd160 0 32) })" "}"; CodeFragment::compile(s, *this); } diff --git a/libp2p/CMakeLists.txt b/libp2p/CMakeLists.txt index 9e20fd99f..6f3f6b712 100644 --- a/libp2p/CMakeLists.txt +++ b/libp2p/CMakeLists.txt @@ -1,62 +1,41 @@ cmake_policy(SET CMP0015 NEW) +# this policy was introduced in cmake 3.0 +# remove if, once 3.0 will be used on unix +if (${CMAKE_MAJOR_VERSION} GREATER 2) + # old policy do not use MACOSX_RPATH + cmake_policy(SET CMP0042 OLD) +endif() +set(CMAKE_AUTOMOC OFF) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DSTATICLIB") aux_source_directory(. SRC_LIST) +# we may not use it in libp2p, but one of our dependecies is including leveldb in header file +# and windows is failing to build without that +include_directories(${LEVELDB_INCLUDE_DIRS}) + +if (MINIUPNPC_FOUND) + include_directories(${MINIUPNPC_INCLUDE_DIRS}) +endif() +include_directories(..) + set(EXECUTABLE p2p) file(GLOB HEADERS "*.h") + if(ETH_STATIC) add_library(${EXECUTABLE} STATIC ${SRC_LIST} ${HEADERS}) else() add_library(${EXECUTABLE} SHARED ${SRC_LIST} ${HEADERS}) endif() -include_directories(..) +if (MINIUPNPC_FOUND) + target_link_libraries(${EXECUTABLE} ${MINIUPNPC_LIBRARIES}) +endif() target_link_libraries(${EXECUTABLE} devcrypto) target_link_libraries(${EXECUTABLE} devcore) -target_link_libraries(${EXECUTABLE} secp256k1) -if(MINIUPNPC_LS) -target_link_libraries(${EXECUTABLE} ${MINIUPNPC_LS}) -endif() -target_link_libraries(${EXECUTABLE} ${LEVELDB_LS}) -target_link_libraries(${EXECUTABLE} ${CRYPTOPP_LS}) -target_link_libraries(${EXECUTABLE} gmp) - -if("${TARGET_PLATFORM}" STREQUAL "w64") - target_link_libraries(${EXECUTABLE} boost_system-mt-s) - target_link_libraries(${EXECUTABLE} boost_regex-mt-s) - target_link_libraries(${EXECUTABLE} boost_filesystem-mt-s) - target_link_libraries(${EXECUTABLE} boost_thread_win32-mt-s) - target_link_libraries(${EXECUTABLE} iphlpapi) - target_link_libraries(${EXECUTABLE} ws2_32) - target_link_libraries(${EXECUTABLE} mswsock) - target_link_libraries(${EXECUTABLE} shlwapi) -elseif (APPLE) - # Latest mavericks boost libraries only come with -mt - target_link_libraries(${EXECUTABLE} boost_system-mt) - target_link_libraries(${EXECUTABLE} boost_regex-mt) - target_link_libraries(${EXECUTABLE} boost_filesystem-mt) - target_link_libraries(${EXECUTABLE} boost_thread-mt) - find_package(Threads REQUIRED) - target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT}) -elseif (UNIX) - target_link_libraries(${EXECUTABLE} ${Boost_SYSTEM_LIBRARY}) - target_link_libraries(${EXECUTABLE} ${Boost_REGEX_LIBRARY}) - target_link_libraries(${EXECUTABLE} ${Boost_FILESYSTEM_LIBRARY}) - target_link_libraries(${EXECUTABLE} ${Boost_THREAD_LIBRARY}) - target_link_libraries(${EXECUTABLE} ${Boost_DATE_TIME_LIBRARY}) - target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT}) -else () - target_link_libraries(${EXECUTABLE} boost_system) - target_link_libraries(${EXECUTABLE} boost_regex) - target_link_libraries(${EXECUTABLE} boost_filesystem) - target_link_libraries(${EXECUTABLE} boost_thread) - find_package(Threads REQUIRED) - target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT}) -endif () install( TARGETS ${EXECUTABLE} ARCHIVE DESTINATION lib LIBRARY DESTINATION lib ) install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} ) diff --git a/libp2p/Common.cpp b/libp2p/Common.cpp index 8a3b27ef0..e0f3b5629 100644 --- a/libp2p/Common.cpp +++ b/libp2p/Common.cpp @@ -53,6 +53,20 @@ bool p2p::isPrivateAddress(bi::address const& _addressToCheck) return false; } +// Helper function to determine if an address is localhost +bool p2p::isLocalHostAddress(bi::address const& _addressToCheck) +{ + // @todo: ivp6 link-local adresses (macos), ex: fe80::1%lo0 + static const set c_rejectAddresses = { + {bi::address_v4::from_string("127.0.0.1")}, + {bi::address_v4::from_string("0.0.0.0")}, + {bi::address_v6::from_string("::1")}, + {bi::address_v6::from_string("::")} + }; + + return find(c_rejectAddresses.begin(), c_rejectAddresses.end(), _addressToCheck) != c_rejectAddresses.end(); +} + std::string p2p::reasonOf(DisconnectReason _r) { switch (_r) diff --git a/libp2p/Common.h b/libp2p/Common.h index 0df7f14fe..d46c5eed1 100644 --- a/libp2p/Common.h +++ b/libp2p/Common.h @@ -47,6 +47,7 @@ namespace p2p using NodeId = h512; bool isPrivateAddress(bi::address const& _addressToCheck); +bool isLocalHostAddress(bi::address const& _addressToCheck); class UPnP; class Capability; @@ -56,7 +57,7 @@ class Session; struct NetWarn: public LogChannel { static const char* name() { return "!N!"; } static const int verbosity = 0; }; struct NetNote: public LogChannel { static const char* name() { return "*N*"; } static const int verbosity = 1; }; struct NetMessageSummary: public LogChannel { static const char* name() { return "-N-"; } static const int verbosity = 2; }; -struct NetConnect: public LogChannel { static const char* name() { return "+N+"; } static const int verbosity = 4; }; +struct NetConnect: public LogChannel { static const char* name() { return "+N+"; } static const int verbosity = 10; }; struct NetMessageDetail: public LogChannel { static const char* name() { return "=N="; } static const int verbosity = 5; }; struct NetTriviaSummary: public LogChannel { static const char* name() { return "-N-"; } static const int verbosity = 10; }; struct NetTriviaDetail: public LogChannel { static const char* name() { return "=N="; } static const int verbosity = 11; }; diff --git a/libp2p/Host.cpp b/libp2p/Host.cpp index bf8d96506..93a6ce672 100644 --- a/libp2p/Host.cpp +++ b/libp2p/Host.cpp @@ -15,25 +15,15 @@ along with cpp-ethereum. If not, see . */ /** @file Host.cpp - * @authors: - * Gav Wood - * Eric Lombrozo (Windows version of populateAddresses()) + * @author Alex Leverington + * @author Gav Wood * @date 2014 */ -#include "Host.h" - -#include -#ifdef _WIN32 -// winsock is already included -// #include -#else -#include -#endif - #include #include #include +#include #include #include #include @@ -42,31 +32,24 @@ #include "Common.h" #include "Capability.h" #include "UPnP.h" +#include "Host.h" using namespace std; using namespace dev; using namespace dev::p2p; -// Addresses we will skip during network interface discovery -// Use a vector as the list is small -// Why this and not names? -// Under MacOSX loopback (127.0.0.1) can be named lo0 and br0 are bridges (0.0.0.0) -static const set c_rejectAddresses = { - {bi::address_v4::from_string("127.0.0.1")}, - {bi::address_v6::from_string("::1")}, - {bi::address_v4::from_string("0.0.0.0")}, - {bi::address_v6::from_string("::")} -}; - Host::Host(std::string const& _clientVersion, NetworkPreferences const& _n, bool _start): - Worker("p2p"), + Worker("p2p", 0), m_clientVersion(_clientVersion), m_netPrefs(_n), - m_ioService(new ba::io_service), - m_acceptor(new bi::tcp::acceptor(*m_ioService)), - m_socket(new bi::tcp::socket(*m_ioService)), + m_ifAddresses(Network::getInterfaceAddresses()), + m_ioService(2), + m_acceptorV4(m_ioService), m_key(KeyPair::create()) { - populateAddresses(); + for (auto address: m_ifAddresses) + if (address.is_v4()) + clog(NetNote) << "IP Address: " << address << " = " << (isPrivateAddress(address) ? "[LOCAL]" : "[PEER]"); + clog(NetNote) << "Id:" << id().abridged(); if (_start) start(); @@ -74,87 +57,88 @@ Host::Host(std::string const& _clientVersion, NetworkPreferences const& _n, bool Host::~Host() { - quit(); + stop(); } void Host::start() { - // if there's no ioService, it means we've had quit() called - bomb out - we're not allowed in here. - if (!m_ioService) - return; + startWorking(); +} - if (isWorking()) - stop(); +void Host::stop() +{ + // called to force io_service to kill any remaining tasks it might have - + // such tasks may involve socket reads from Capabilities that maintain references + // to resources we're about to free. - for (unsigned i = 0; i < 2; ++i) { - bi::tcp::endpoint endpoint(bi::tcp::v4(), i ? 0 : m_netPrefs.listenPort); - try - { - m_acceptor->open(endpoint.protocol()); - m_acceptor->set_option(ba::socket_base::reuse_address(true)); - m_acceptor->bind(endpoint); - m_acceptor->listen(); - m_listenPort = i ? m_acceptor->local_endpoint().port() : m_netPrefs.listenPort; - break; - } - catch (...) - { - if (i) - { - cwarn << "Couldn't start accepting connections on host. Something very wrong with network?\n" << boost::current_exception_diagnostic_information(); - return; - } - m_acceptor->close(); - continue; - } + // Although m_run is set by stop() or start(), it effects m_runTimer so x_runTimer is used instead of a mutex for m_run. + // when m_run == false, run() will cause this::run() to stop() ioservice + Guard l(x_runTimer); + // ignore if already stopped/stopping + if (!m_run) + return; + m_run = false; } - - for (auto const& h: m_capabilities) - h.second->onStarting(); - - startWorking(); + + // wait for m_timer to reset (indicating network scheduler has stopped) + while (!!m_timer) + this_thread::sleep_for(chrono::milliseconds(50)); + + // stop worker thread + stopWorking(); } -void Host::stop() +void Host::doneWorking() { - // if there's no ioService, it means we've had quit() called - bomb out - we're not allowed in here. - if (!m_ioService) - return; - + // reset ioservice (allows manually polling network, below) + m_ioService.reset(); + + // shutdown acceptor + m_acceptorV4.cancel(); + if (m_acceptorV4.is_open()) + m_acceptorV4.close(); + + // There maybe an incoming connection which started but hasn't finished. + // Wait for acceptor to end itself instead of assuming it's complete. + // This helps ensure a peer isn't stopped at the same time it's starting + // and that socket for pending connection is closed. + while (m_accepting) + m_ioService.poll(); + + // stop capabilities (eth: stops syncing or block/tx broadcast) for (auto const& h: m_capabilities) h.second->onStopping(); - stopWorking(); - - if (m_acceptor->is_open()) - { - if (m_accepting) - m_acceptor->cancel(); - m_acceptor->close(); - m_accepting = false; - } - if (m_socket->is_open()) - m_socket->close(); - disconnectPeers(); - - if (!!m_ioService) + // disconnect peers + for (unsigned n = 0;; n = 0) { - m_ioService->stop(); - m_ioService->reset(); + { + RecursiveGuard l(x_peers); + for (auto i: m_peers) + if (auto p = i.second.lock()) + if (p->isOpen()) + { + p->disconnect(ClientQuit); + n++; + } + } + if (!n) + break; + + // poll so that peers send out disconnect packets + m_ioService.poll(); } -} - -void Host::quit() -{ - // called to force io_service to kill any remaining tasks it might have - - // such tasks may involve socket reads from Capabilities that maintain references - // to resources we're about to free. - stop(); - m_acceptor.reset(); - m_socket.reset(); + + // stop network (again; helpful to call before subsequent reset()) + m_ioService.stop(); + + // reset network (allows reusing ioservice in future) m_ioService.reset(); - // m_acceptor & m_socket are DANGEROUS now. + + // finally, clear out peers (in case they're lingering) + RecursiveGuard l(x_peers); + m_peers.clear(); } unsigned Host::protocolVersion() const @@ -183,33 +167,6 @@ void Host::registerPeer(std::shared_ptr _s, CapDescs const& _caps) } } -void Host::disconnectPeers() -{ - // if there's no ioService, it means we've had quit() called - bomb out - we're not allowed in here. - if (!m_ioService) - return; - - for (unsigned n = 0;; n = 0) - { - { - RecursiveGuard l(x_peers); - for (auto i: m_peers) - if (auto p = i.second.lock()) - { - p->disconnect(ClientQuit); - n++; - } - } - if (!n) - break; - m_ioService->poll(); - this_thread::sleep_for(chrono::milliseconds(100)); - } - - delete m_upnp; - m_upnp = nullptr; -} - void Host::seal(bytes& _b) { _b[0] = 0x22; @@ -223,170 +180,11 @@ void Host::seal(bytes& _b) _b[7] = len & 0xff; } -void Host::determinePublic(string const& _publicAddress, bool _upnp) -{ - // if there's no ioService, it means we've had quit() called - bomb out - we're not allowed in here. - if (!m_ioService) - return; - - if (_upnp) - try - { - m_upnp = new UPnP; - } - catch (NoUPnPDevice) {} // let m_upnp continue as null - we handle it properly. - - bi::tcp::resolver r(*m_ioService); - if (m_upnp && m_upnp->isValid() && m_peerAddresses.size()) - { - clog(NetNote) << "External addr:" << m_upnp->externalIP(); - int p; - for (auto const& addr : m_peerAddresses) - if ((p = m_upnp->addRedirect(addr.to_string().c_str(), m_listenPort))) - break; - if (p) - clog(NetNote) << "Punched through NAT and mapped local port" << m_listenPort << "onto external port" << p << "."; - else - { - // couldn't map - clog(NetWarn) << "Couldn't punch through NAT (or no NAT in place). Assuming" << m_listenPort << "is local & external port."; - p = m_listenPort; - } - - auto eip = m_upnp->externalIP(); - if (eip == string("0.0.0.0") && _publicAddress.empty()) - m_public = bi::tcp::endpoint(bi::address(), (unsigned short)p); - else - { - bi::address adr = adr = bi::address::from_string(eip); - try - { - adr = bi::address::from_string(_publicAddress); - } - catch (...) {} - m_public = bi::tcp::endpoint(adr, (unsigned short)p); - m_addresses.push_back(m_public.address()); - } - } - else - { - // No UPnP - fallback on given public address or, if empty, the assumed peer address. - bi::address adr = m_peerAddresses.size() ? m_peerAddresses[0] : bi::address(); - try - { - adr = bi::address::from_string(_publicAddress); - } - catch (...) {} - m_public = bi::tcp::endpoint(adr, m_listenPort); - m_addresses.push_back(adr); - } -} - -void Host::populateAddresses() -{ - // if there's no ioService, it means we've had quit() called - bomb out - we're not allowed in here. - if (!m_ioService) - return; - -#ifdef _WIN32 - WSAData wsaData; - if (WSAStartup(MAKEWORD(1, 1), &wsaData) != 0) - BOOST_THROW_EXCEPTION(NoNetworking()); - - char ac[80]; - if (gethostname(ac, sizeof(ac)) == SOCKET_ERROR) - { - clog(NetWarn) << "Error " << WSAGetLastError() << " when getting local host name."; - WSACleanup(); - BOOST_THROW_EXCEPTION(NoNetworking()); - } - - struct hostent* phe = gethostbyname(ac); - if (phe == 0) - { - clog(NetWarn) << "Bad host lookup."; - WSACleanup(); - BOOST_THROW_EXCEPTION(NoNetworking()); - } - - for (int i = 0; phe->h_addr_list[i] != 0; ++i) - { - struct in_addr addr; - memcpy(&addr, phe->h_addr_list[i], sizeof(struct in_addr)); - char *addrStr = inet_ntoa(addr); - bi::address ad(bi::address::from_string(addrStr)); - m_addresses.push_back(ad.to_v4()); - bool isLocal = std::find(c_rejectAddresses.begin(), c_rejectAddresses.end(), ad) != c_rejectAddresses.end(); - if (!isLocal) - m_peerAddresses.push_back(ad.to_v4()); - clog(NetNote) << "Address: " << ac << " = " << m_addresses.back() << (isLocal ? " [LOCAL]" : " [PEER]"); - } - - WSACleanup(); -#else - ifaddrs* ifaddr; - if (getifaddrs(&ifaddr) == -1) - BOOST_THROW_EXCEPTION(NoNetworking()); - - bi::tcp::resolver r(*m_ioService); - - for (ifaddrs* ifa = ifaddr; ifa; ifa = ifa->ifa_next) - { - if (!ifa->ifa_addr) - continue; - if (ifa->ifa_addr->sa_family == AF_INET) - { - char host[NI_MAXHOST]; - if (getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in), host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST)) - continue; - try - { - auto it = r.resolve({host, "30303"}); - bi::tcp::endpoint ep = it->endpoint(); - bi::address ad = ep.address(); - m_addresses.push_back(ad.to_v4()); - bool isLocal = std::find(c_rejectAddresses.begin(), c_rejectAddresses.end(), ad) != c_rejectAddresses.end(); - if (!isLocal) - m_peerAddresses.push_back(ad.to_v4()); - clog(NetNote) << "Address: " << host << " = " << m_addresses.back() << (isLocal ? " [LOCAL]" : " [PEER]"); - } - catch (...) - { - clog(NetNote) << "Couldn't resolve: " << host; - } - } - else if (ifa->ifa_addr->sa_family == AF_INET6) - { - char host[NI_MAXHOST]; - if (getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in6), host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST)) - continue; - try - { - auto it = r.resolve({host, "30303"}); - bi::tcp::endpoint ep = it->endpoint(); - bi::address ad = ep.address(); - m_addresses.push_back(ad.to_v6()); - bool isLocal = std::find(c_rejectAddresses.begin(), c_rejectAddresses.end(), ad) != c_rejectAddresses.end(); - if (!isLocal) - m_peerAddresses.push_back(ad); - clog(NetNote) << "Address: " << host << " = " << m_addresses.back() << (isLocal ? " [LOCAL]" : " [PEER]"); - } - catch (...) - { - clog(NetNote) << "Couldn't resolve: " << host; - } - } - } - - freeifaddrs(ifaddr); -#endif -} - shared_ptr Host::noteNode(NodeId _id, bi::tcp::endpoint _a, Origin _o, bool _ready, NodeId _oldId) { RecursiveGuard l(x_peers); - if (_a.port() < 30300 || _a.port() > 30303) - cwarn << "Wierd port being recorded!"; + if (_a.port() < 30300 || _a.port() > 30305) + cwarn << "Weird port being recorded: " << _a.port(); if (_a.port() >= /*49152*/32768) { @@ -459,18 +257,81 @@ Nodes Host::potentialPeers(RangeMask const& _known) return ret; } -void Host::ensureAccepting() +void Host::determinePublic(string const& _publicAddress, bool _upnp) { - // if there's no ioService, it means we've had quit() called - bomb out - we're not allowed in here. - if (!m_ioService) + m_peerAddresses.clear(); + + // no point continuing if there are no interface addresses or valid listen port + if (!m_ifAddresses.size() || m_listenPort < 1) return; - if (!m_accepting) + // populate interfaces we'll listen on (eth listens on all interfaces); ignores local + for (auto addr: m_ifAddresses) + if ((m_netPrefs.localNetworking || !isPrivateAddress(addr)) && !isLocalHostAddress(addr)) + m_peerAddresses.insert(addr); + + // if user supplied address is a public address then we use it + // if user supplied address is private, and localnetworking is enabled, we use it + bi::address reqpublicaddr(bi::address(_publicAddress.empty() ? bi::address() : bi::address::from_string(_publicAddress))); + bi::tcp::endpoint reqpublic(reqpublicaddr, m_listenPort); + bool isprivate = isPrivateAddress(reqpublicaddr); + bool ispublic = !isprivate && !isLocalHostAddress(reqpublicaddr); + if (!reqpublicaddr.is_unspecified() && (ispublic || (isprivate && m_netPrefs.localNetworking))) + { + if (!m_peerAddresses.count(reqpublicaddr)) + m_peerAddresses.insert(reqpublicaddr); + m_public = reqpublic; + return; + } + + // if address wasn't provided, then use first public ipv4 address found + for (auto addr: m_peerAddresses) + if (addr.is_v4() && !isPrivateAddress(addr)) + { + m_public = bi::tcp::endpoint(*m_peerAddresses.begin(), m_listenPort); + return; + } + + // or find address via upnp + if (_upnp) + { + bi::address upnpifaddr; + bi::tcp::endpoint upnpep = Network::traverseNAT(m_ifAddresses, m_listenPort, upnpifaddr); + if (!upnpep.address().is_unspecified() && !upnpifaddr.is_unspecified()) + { + if (!m_peerAddresses.count(upnpep.address())) + m_peerAddresses.insert(upnpep.address()); + m_public = upnpep; + return; + } + } + + // or if no address provided, use private ipv4 address if local networking is enabled + if (reqpublicaddr.is_unspecified()) + if (m_netPrefs.localNetworking) + for (auto addr: m_peerAddresses) + if (addr.is_v4() && isPrivateAddress(addr)) + { + m_public = bi::tcp::endpoint(addr, m_listenPort); + return; + } + + // otherwise address is unspecified + m_public = bi::tcp::endpoint(bi::address(), m_listenPort); +} + +void Host::runAcceptor() +{ + assert(m_listenPort > 0); + + if (m_run && !m_accepting) { clog(NetConnect) << "Listening on local port " << m_listenPort << " (public: " << m_public << ")"; m_accepting = true; - m_acceptor->async_accept(*m_socket, [=](boost::system::error_code ec) + m_socket.reset(new bi::tcp::socket(m_ioService)); + m_acceptorV4.async_accept(*m_socket, [=](boost::system::error_code ec) { + bool success = false; if (!ec) { try @@ -480,8 +341,9 @@ void Host::ensureAccepting() } catch (...){} bi::address remoteAddress = m_socket->remote_endpoint().address(); // Port defaults to 0 - we let the hello tell us which port the peer listens to - auto p = std::make_shared(this, std::move(*m_socket), bi::tcp::endpoint(remoteAddress, 0)); + auto p = std::make_shared(this, std::move(*m_socket.release()), bi::tcp::endpoint(remoteAddress, 0)); p->start(); + success = true; } catch (Exception const& _e) { @@ -492,9 +354,17 @@ void Host::ensureAccepting() clog(NetWarn) << "ERROR: " << _e.what(); } } + + if (!success && m_socket->is_open()) + { + boost::system::error_code ec; + m_socket->shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec); + m_socket->close(); + } + m_accepting = false; if (ec.value() < 1) - ensureAccepting(); + runAcceptor(); }); } } @@ -508,17 +378,16 @@ string Host::pocHost() void Host::connect(std::string const& _addr, unsigned short _port) noexcept { - // if there's no ioService, it means we've had quit() called - bomb out - we're not allowed in here. - if (!m_ioService) + if (!m_run) return; - for (int i = 0; i < 2; ++i) + for (auto first: {true, false}) { try { - if (i == 0) + if (first) { - bi::tcp::resolver r(*m_ioService); + bi::tcp::resolver r(m_ioService); connect(r.resolve({_addr, toString(_port)})->endpoint()); } else @@ -540,12 +409,11 @@ void Host::connect(std::string const& _addr, unsigned short _port) noexcept void Host::connect(bi::tcp::endpoint const& _ep) { - // if there's no ioService, it means we've had quit() called - bomb out - we're not allowed in here. - if (!m_ioService) + if (!m_run) return; clog(NetConnect) << "Attempting single-shot connection to " << _ep; - bi::tcp::socket* s = new bi::tcp::socket(*m_ioService); + bi::tcp::socket* s = new bi::tcp::socket(m_ioService); s->async_connect(_ep, [=](boost::system::error_code const& ec) { if (ec) @@ -562,33 +430,48 @@ void Host::connect(bi::tcp::endpoint const& _ep) void Host::connect(std::shared_ptr const& _n) { - // if there's no ioService, it means we've had quit() called - bomb out - we're not allowed in here. - if (!m_ioService) + if (!m_run) return; - + + // prevent concurrently connecting to a node; todo: better abstraction + Node *nptr = _n.get(); + { + Guard l(x_pendingNodeConns); + if (m_pendingNodeConns.count(nptr)) + return; + m_pendingNodeConns.insert(nptr); + } + clog(NetConnect) << "Attempting connection to node" << _n->id.abridged() << "@" << _n->address << "from" << id().abridged(); _n->lastAttempted = std::chrono::system_clock::now(); _n->failedAttempts++; m_ready -= _n->index; - bi::tcp::socket* s = new bi::tcp::socket(*m_ioService); - s->async_connect(_n->address, [=](boost::system::error_code const& ec) - { - if (ec) - { - clog(NetConnect) << "Connection refused to node" << _n->id.abridged() << "@" << _n->address << "(" << ec.message() << ")"; - _n->lastDisconnect = TCPError; - _n->lastAttempted = std::chrono::system_clock::now(); - m_ready += _n->index; - } - else + bi::tcp::socket* s = new bi::tcp::socket(m_ioService); + + auto n = node(_n->id); + if (n) + s->async_connect(_n->address, [=](boost::system::error_code const& ec) { - clog(NetConnect) << "Connected to" << _n->id.abridged() << "@" << _n->address; - _n->lastConnected = std::chrono::system_clock::now(); - auto p = make_shared(this, std::move(*s), node(_n->id), true); // true because we don't care about ids matched for now. Once we have permenant IDs this will matter a lot more and we can institute a safer mechanism. - p->start(); - } - delete s; - }); + if (ec) + { + clog(NetConnect) << "Connection refused to node" << _n->id.abridged() << "@" << _n->address << "(" << ec.message() << ")"; + _n->lastDisconnect = TCPError; + _n->lastAttempted = std::chrono::system_clock::now(); + m_ready += _n->index; + } + else + { + clog(NetConnect) << "Connected to" << _n->id.abridged() << "@" << _n->address; + _n->lastConnected = std::chrono::system_clock::now(); + auto p = make_shared(this, std::move(*s), n, true); // true because we don't care about ids matched for now. Once we have permenant IDs this will matter a lot more and we can institute a safer mechanism. + p->start(); + } + delete s; + Guard l(x_pendingNodeConns); + m_pendingNodeConns.erase(nptr); + }); + else + clog(NetWarn) << "Trying to connect to node not in node table."; } bool Host::havePeer(NodeId _id) const @@ -654,12 +537,9 @@ void Host::growPeers() return; } else - { - ensureAccepting(); for (auto const& i: m_peers) if (auto p = i.second.lock()) p->ensureNodesRequested(); - } } } @@ -700,8 +580,7 @@ void Host::prunePeers() PeerInfos Host::peers(bool _updatePing) const { - // if there's no ioService, it means we've had quit() called - bomb out - we're not allowed in here. - if (!m_ioService) + if (!m_run) return PeerInfos(); RecursiveGuard l(x_peers); @@ -718,35 +597,36 @@ PeerInfos Host::peers(bool _updatePing) const return ret; } -void Host::startedWorking() -{ - determinePublic(m_netPrefs.publicIP, m_netPrefs.upnp); - ensureAccepting(); - - if (!m_public.address().is_unspecified() && (m_nodes.empty() || m_nodes[m_nodesList[0]]->id != id())) - noteNode(id(), m_public, Origin::Perfect, false); - - clog(NetNote) << "Id:" << id().abridged(); -} - -void Host::doWork() +void Host::run(boost::system::error_code const&) { - // if there's no ioService, it means we've had quit() called - bomb out - we're not allowed in here. - if (asserts(!!m_ioService)) + if (!m_run) + { + // stopping io service allows running manual network operations for shutdown + // and also stops blocking worker thread, allowing worker thread to exit + m_ioService.stop(); + + // resetting timer signals network that nothing else can be scheduled to run + m_timer.reset(); return; + } - growPeers(); - prunePeers(); - + m_lastTick += c_timerInterval; + if (m_lastTick >= c_timerInterval * 10) + { + growPeers(); + prunePeers(); + m_lastTick = 0; + } + if (m_hadNewNodes) { for (auto p: m_peers) if (auto pp = p.second.lock()) pp->serviceNodesRequest(); - + m_hadNewNodes = false; } - + if (chrono::steady_clock::now() - m_lastPing > chrono::seconds(30)) // ping every 30s. { for (auto p: m_peers) @@ -755,8 +635,57 @@ void Host::doWork() pp->disconnect(PingTimeout); pingAll(); } + + auto runcb = [this](boost::system::error_code const& error) -> void { run(error); }; + m_timer->expires_from_now(boost::posix_time::milliseconds(c_timerInterval)); + m_timer->async_wait(runcb); +} + +void Host::startedWorking() +{ + asserts(!m_timer); + + { + // prevent m_run from being set to true at same time as set to false by stop() + // don't release mutex until m_timer is set so in case stop() is called at same + // time, stop will wait on m_timer and graceful network shutdown. + Guard l(x_runTimer); + // create deadline timer + m_timer.reset(new boost::asio::deadline_timer(m_ioService)); + m_run = true; + } + + // try to open acceptor (todo: ipv6) + m_listenPort = Network::listen4(m_acceptorV4, m_netPrefs.listenPort); + + // start capability threads + for (auto const& h: m_capabilities) + h.second->onStarting(); + + // determine public IP, but only if we're able to listen for connections + // todo: GUI when listen is unavailable in UI + if (m_listenPort) + { + determinePublic(m_netPrefs.publicIP, m_netPrefs.upnp); + + if (m_listenPort > 0) + runAcceptor(); + } + + // if m_public address is valid then add us to node list + // todo: abstract empty() and emplace logic + if (!m_public.address().is_unspecified() && (m_nodes.empty() || m_nodes[m_nodesList[0]]->id != id())) + noteNode(id(), m_public, Origin::Perfect, false); + + clog(NetNote) << "Id:" << id().abridged(); + + run(boost::system::error_code()); +} - m_ioService->poll(); +void Host::doWork() +{ + if (m_run) + m_ioService.run(); } void Host::pingAll() @@ -778,7 +707,7 @@ bytes Host::saveNodes() const { Node const& n = *(i.second); // TODO: PoC-7: Figure out why it ever shares these ports.//n.address.port() >= 30300 && n.address.port() <= 30305 && - if (!n.dead && n.address.port() > 0 && n.address.port() < /*49152*/32768 && n.id != id() && !isPrivateAddress(n.address.address())) + if (!n.dead && chrono::system_clock::now() - n.lastConnected < chrono::seconds(3600 * 48) && n.address.port() > 0 && n.address.port() < /*49152*/32768 && n.id != id() && !isPrivateAddress(n.address.address())) { nodes.appendList(10); if (n.address.address().is_v4()) @@ -786,8 +715,8 @@ bytes Host::saveNodes() const else nodes << n.address.address().to_v6().to_bytes(); nodes << n.address.port() << n.id << (int)n.idOrigin - << std::chrono::duration_cast(n.lastConnected.time_since_epoch()).count() - << std::chrono::duration_cast(n.lastAttempted.time_since_epoch()).count() + << chrono::duration_cast(n.lastConnected.time_since_epoch()).count() + << chrono::duration_cast(n.lastAttempted.time_since_epoch()).count() << n.failedAttempts << (unsigned)n.lastDisconnect << n.score << n.rating; count++; } diff --git a/libp2p/Host.h b/libp2p/Host.h index 7722905ab..a146d6a66 100644 --- a/libp2p/Host.h +++ b/libp2p/Host.h @@ -14,7 +14,8 @@ You should have received a copy of the GNU General Public License along with cpp-ethereum. If not, see . */ -/** @file EthereumHost.h +/** @file Host.h + * @author Alex Leverington * @author Gav Wood * @date 2014 */ @@ -34,9 +35,10 @@ #include #include #include "HostCapability.h" +#include "Network.h" #include "Common.h" namespace ba = boost::asio; -namespace bi = boost::asio::ip; +namespace bi = ba::ip; namespace dev { @@ -101,16 +103,6 @@ struct Node using Nodes = std::vector; -struct NetworkPreferences -{ - NetworkPreferences(unsigned short p = 30303, std::string i = std::string(), bool u = true, bool l = false): listenPort(p), publicIP(i), upnp(u), localNetworking(l) {} - - unsigned short listenPort = 30303; - std::string publicIP; - bool upnp = true; - bool localNetworking = false; -}; - /** * @brief The Host class * Capabilities should be registered prior to startNetwork, since m_capabilities is not thread-safe. @@ -120,17 +112,14 @@ class Host: public Worker friend class Session; friend class HostCapabilityFace; friend struct Node; - + public: /// Start server, listening for connections on the given port. Host(std::string const& _clientVersion, NetworkPreferences const& _n = NetworkPreferences(), bool _start = false); /// Will block on network process events. virtual ~Host(); - - /// Closes all peers. - void disconnectPeers(); - + /// Basic peer network protocol version. unsigned protocolVersion() const; @@ -147,7 +136,7 @@ public: void connect(bi::tcp::endpoint const& _ep); void connect(std::shared_ptr const& _n); - /// @returns true iff we have the a peer of the given id. + /// @returns true iff we have a peer of the given id. bool havePeer(NodeId _id) const; /// Set ideal number of peers. @@ -175,11 +164,15 @@ public: void setNetworkPreferences(NetworkPreferences const& _p) { auto had = isStarted(); if (had) stop(); m_netPrefs = _p; if (had) start(); } + /// Start network. @threadsafe void start(); + + /// Stop network. @threadsafe + /// Resets acceptor, socket, and IO service. Called by deallocator. void stop(); - bool isStarted() const { return isWorking(); } - - void quit(); + + /// @returns if network is running. + bool isStarted() const { return m_run; } NodeId id() const { return m_key.pub(); } @@ -188,38 +181,56 @@ public: std::shared_ptr node(NodeId _id) const { if (m_nodes.count(_id)) return m_nodes.at(_id); return std::shared_ptr(); } private: - void seal(bytes& _b); - void populateAddresses(); + /// Populate m_peerAddresses with available public addresses. void determinePublic(std::string const& _publicAddress, bool _upnp); - void ensureAccepting(); + + /// Called only from startedWorking(). + void runAcceptor(); + + void seal(bytes& _b); void growPeers(); void prunePeers(); + /// Called by Worker. Not thread-safe; to be called only by worker. virtual void startedWorking(); + /// Called by startedWorking. Not thread-safe; to be called only be Worker. + void run(boost::system::error_code const& error); ///< Run network. Called serially via ASIO deadline timer. Manages connection state transitions. - /// Conduct I/O, polling, syncing, whatever. - /// Ideally all time-consuming I/O is done in a background thread or otherwise asynchronously, but you get this call every 100ms or so anyway. - /// This won't touch alter the blockchain. + /// Run network. Not thread-safe; to be called only by worker. virtual void doWork(); + + /// Shutdown network. Not thread-safe; to be called only by worker. + virtual void doneWorking(); std::shared_ptr noteNode(NodeId _id, bi::tcp::endpoint _a, Origin _o, bool _ready, NodeId _oldId = NodeId()); Nodes potentialPeers(RangeMask const& _known); + bool m_run = false; ///< Whether network is running. + std::mutex x_runTimer; ///< Start/stop mutex. + std::string m_clientVersion; ///< Our version string. - NetworkPreferences m_netPrefs; ///< Network settings. + NetworkPreferences m_netPrefs; ///< Network settings. + + /// Interface addresses (private, public) + std::vector m_ifAddresses; ///< Interface addresses. - static const int NetworkStopped = -1; ///< The value meaning we're not actually listening. - int m_listenPort = NetworkStopped; ///< What port are we listening on? + int m_listenPort = -1; ///< What port are we listening on. -1 means binding failed or acceptor hasn't been initialized. - std::unique_ptr m_ioService; ///< IOService for network stuff. - std::unique_ptr m_acceptor; ///< Listening acceptor. - std::unique_ptr m_socket; ///< Listening socket. + ba::io_service m_ioService; ///< IOService for network stuff. + bi::tcp::acceptor m_acceptorV4; ///< Listening acceptor. + std::unique_ptr m_socket; ///< Listening socket. + + std::unique_ptr m_timer; ///< Timer which, when network is running, calls scheduler() every c_timerInterval ms. + static const unsigned c_timerInterval = 100; ///< Interval which m_timer is run when network is connected. + unsigned m_lastTick = 0; ///< Used by run() for scheduling; must not be mutated outside of run(). + + std::set m_pendingNodeConns; /// Used only by connect(Node&) to limit concurrently connecting to same node. See connect(shared_ptrconst&). + Mutex x_pendingNodeConns; - UPnP* m_upnp = nullptr; ///< UPnP helper. - bi::tcp::endpoint m_public; ///< Our public listening endpoint. - KeyPair m_key; ///< Our unique ID. + bi::tcp::endpoint m_public; ///< Our public listening endpoint. + KeyPair m_key; ///< Our unique ID. bool m_hadNewNodes = false; @@ -237,13 +248,11 @@ private: std::vector m_nodesList; RangeMask m_ready; ///< Indices into m_nodesList over to which nodes we are not currently connected, connecting or otherwise ignoring. - RangeMask m_private; ///< Indices into m_nodesList over to which nodes are private. - - unsigned m_idealPeerCount = 5; ///< Ideal number of peers to be connected to. + RangeMask m_private; ///< Indices into m_nodesList over to which nodes are private. - // Our addresses. - std::vector m_addresses; ///< Addresses for us. - std::vector m_peerAddresses; ///< Addresses that peers (can) know us by. + unsigned m_idealPeerCount = 5; ///< Ideal number of peers to be connected to. + + std::set m_peerAddresses; ///< Public addresses that peers (can) know us by. // Our capabilities. std::map> m_capabilities; ///< Each of the capabilities we support. diff --git a/libp2p/Network.cpp b/libp2p/Network.cpp new file mode 100644 index 000000000..8ca8dd135 --- /dev/null +++ b/libp2p/Network.cpp @@ -0,0 +1,187 @@ +/* + This file is part of cpp-ethereum. + + cpp-ethereum is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + cpp-ethereum is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with cpp-ethereum. If not, see . +*/ +/** @file Network.cpp + * @author Alex Leverington + * @author Gav Wood + * @author Eric Lombrozo (Windows version of getInterfaceAddresses()) + * @date 2014 + */ + +#include +#ifndef _WIN32 +#include +#endif + +#include +#include +#include +#include +#include "Common.h" +#include "UPnP.h" +#include "Network.h" + +using namespace std; +using namespace dev; +using namespace dev::p2p; + +std::vector Network::getInterfaceAddresses() +{ + std::vector addresses; + +#ifdef _WIN32 + WSAData wsaData; + if (WSAStartup(MAKEWORD(1, 1), &wsaData) != 0) + BOOST_THROW_EXCEPTION(NoNetworking()); + + char ac[80]; + if (gethostname(ac, sizeof(ac)) == SOCKET_ERROR) + { + clog(NetWarn) << "Error " << WSAGetLastError() << " when getting local host name."; + WSACleanup(); + BOOST_THROW_EXCEPTION(NoNetworking()); + } + + struct hostent* phe = gethostbyname(ac); + if (phe == 0) + { + clog(NetWarn) << "Bad host lookup."; + WSACleanup(); + BOOST_THROW_EXCEPTION(NoNetworking()); + } + + for (int i = 0; phe->h_addr_list[i] != 0; ++i) + { + struct in_addr addr; + memcpy(&addr, phe->h_addr_list[i], sizeof(struct in_addr)); + char *addrStr = inet_ntoa(addr); + bi::address address(bi::address::from_string(addrStr)); + if (!isLocalHostAddress(address)) + addresses.push_back(address.to_v4()); + } + + WSACleanup(); +#else + ifaddrs* ifaddr; + if (getifaddrs(&ifaddr) == -1) + BOOST_THROW_EXCEPTION(NoNetworking()); + + for (auto ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) + { + if (!ifa->ifa_addr || string(ifa->ifa_name) == "lo0") + continue; + + if (ifa->ifa_addr->sa_family == AF_INET) + { + in_addr addr = ((struct sockaddr_in *)ifa->ifa_addr)->sin_addr; + boost::asio::ip::address_v4 address(boost::asio::detail::socket_ops::network_to_host_long(addr.s_addr)); + if (!isLocalHostAddress(address)) + addresses.push_back(address); + } + else if (ifa->ifa_addr->sa_family == AF_INET6) + { + sockaddr_in6* sockaddr = ((struct sockaddr_in6 *)ifa->ifa_addr); + in6_addr addr = sockaddr->sin6_addr; + boost::asio::ip::address_v6::bytes_type bytes; + memcpy(&bytes[0], addr.s6_addr, 16); + boost::asio::ip::address_v6 address(bytes, sockaddr->sin6_scope_id); + if (!isLocalHostAddress(address)) + addresses.push_back(address); + } + } + + if (ifaddr!=NULL) + freeifaddrs(ifaddr); + +#endif + + return std::move(addresses); +} + +int Network::listen4(bi::tcp::acceptor& _acceptor, unsigned short _listenPort) +{ + int retport = -1; + for (unsigned i = 0; i < 2; ++i) + { + // try to connect w/listenPort, else attempt net-allocated port + bi::tcp::endpoint endpoint(bi::tcp::v4(), i ? 0 : _listenPort); + try + { + _acceptor.open(endpoint.protocol()); + _acceptor.set_option(ba::socket_base::reuse_address(true)); + _acceptor.bind(endpoint); + _acceptor.listen(); + retport = _acceptor.local_endpoint().port(); + break; + } + catch (...) + { + if (i) + { + // both attempts failed + cwarn << "Couldn't start accepting connections on host. Something very wrong with network?\n" << boost::current_exception_diagnostic_information(); + } + + // first attempt failed + _acceptor.close(); + continue; + } + } + return retport; +} + +bi::tcp::endpoint Network::traverseNAT(std::vector const& _ifAddresses, unsigned short _listenPort, bi::address& o_upnpifaddr) +{ + asserts(_listenPort != 0); + + UPnP* upnp = nullptr; + try + { + upnp = new UPnP; + } + // let m_upnp continue as null - we handle it properly. + catch (NoUPnPDevice) {} + + bi::tcp::endpoint upnpep; + if (upnp && upnp->isValid()) + { + bi::address paddr; + int extPort = 0; + for (auto const& addr: _ifAddresses) + if (addr.is_v4() && isPrivateAddress(addr) && (extPort = upnp->addRedirect(addr.to_string().c_str(), _listenPort))) + { + paddr = addr; + break; + } + + auto eip = upnp->externalIP(); + bi::address eipaddr(bi::address::from_string(eip)); + if (extPort && eip != string("0.0.0.0") && !isPrivateAddress(eipaddr)) + { + clog(NetNote) << "Punched through NAT and mapped local port" << _listenPort << "onto external port" << extPort << "."; + clog(NetNote) << "External addr:" << eip; + o_upnpifaddr = paddr; + upnpep = bi::tcp::endpoint(eipaddr, (unsigned short)extPort); + } + else + clog(NetWarn) << "Couldn't punch through NAT (or no NAT in place)."; + + if (upnp) + delete upnp; + } + + return upnpep; +} diff --git a/libp2p/Network.h b/libp2p/Network.h new file mode 100644 index 000000000..944d390c8 --- /dev/null +++ b/libp2p/Network.h @@ -0,0 +1,63 @@ +/* + This file is part of cpp-ethereum. + + cpp-ethereum is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + cpp-ethereum is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with cpp-ethereum. If not, see . +*/ +/** @file Network.h + * @author Alex Leverington + * @author Gav Wood + * @date 2014 + */ + +#pragma once + +#include +namespace ba = boost::asio; +namespace bi = ba::ip; + +namespace dev +{ + +namespace p2p +{ + +struct NetworkPreferences +{ + NetworkPreferences(unsigned short p = 30303, std::string i = std::string(), bool u = true, bool l = false): listenPort(p), publicIP(i), upnp(u), localNetworking(l) {} + + unsigned short listenPort = 30303; + std::string publicIP; + bool upnp = true; + bool localNetworking = false; +}; + +/** + * @brief Network Class + * Static network operations and interface(s). + */ +class Network +{ +public: + /// @returns public and private interface addresses + static std::vector getInterfaceAddresses(); + + /// Try to bind and listen on _listenPort, else attempt net-allocated port. + static int listen4(bi::tcp::acceptor& _acceptor, unsigned short _listenPort); + + /// Return public endpoint of upnp interface. If successful o_upnpifaddr will be a private interface address and endpoint will contain public address and port. + static bi::tcp::endpoint traverseNAT(std::vector const& _ifAddresses, unsigned short _listenPort, bi::address& o_upnpifaddr); +}; + +} +} diff --git a/libp2p/Session.cpp b/libp2p/Session.cpp index c4385df5f..cb0a60a92 100644 --- a/libp2p/Session.cpp +++ b/libp2p/Session.cpp @@ -75,7 +75,11 @@ Session::~Session() try { if (m_socket.is_open()) + { + boost::system::error_code ec; + m_socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec); m_socket.close(); + } } catch (...){} } @@ -344,7 +348,7 @@ bool Session::interpret(RLP const& _r) // goto CONTINUE; // Wierd port. // Avoid our random other addresses that they might end up giving us. - for (auto i: m_server->m_addresses) + for (auto i: m_server->m_peerAddresses) if (ep.address() == i && ep.port() == m_server->listenPort()) goto CONTINUE; @@ -479,6 +483,8 @@ void Session::drop(DisconnectReason _reason) try { clogS(NetConnect) << "Closing " << m_socket.remote_endpoint() << "(" << reasonOf(_reason) << ")"; + boost::system::error_code ec; + m_socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec); m_socket.close(); } catch (...) {} diff --git a/libp2p/_libp2p.cpp b/libp2p/_libp2p.cpp deleted file mode 100644 index 440ba362b..000000000 --- a/libp2p/_libp2p.cpp +++ /dev/null @@ -1,9 +0,0 @@ -#ifdef _MSC_VER -#include "All.h" -#include "Capability.cpp" -#include "Common.cpp" -#include "Host.cpp" -#include "HostCapability.cpp" -#include "Session.cpp" -#include "UPnP.cpp" -#endif diff --git a/libpyserpent/CMakeLists.txt b/libpyserpent/CMakeLists.txt deleted file mode 100644 index e6f32ec81..000000000 --- a/libpyserpent/CMakeLists.txt +++ /dev/null @@ -1,42 +0,0 @@ -cmake_policy(SET CMP0015 NEW) - -aux_source_directory(. SRC_LIST) - -set(EXECUTABLE pyserpent) - -# set(CMAKE_INSTALL_PREFIX ../lib) -add_library(${EXECUTABLE} SHARED ${SRC_LIST}) - -file(GLOB HEADERS "*.h") - -include_directories(..) - -target_link_libraries(${EXECUTABLE} serpent) -target_link_libraries(${EXECUTABLE} lll) -target_link_libraries(${EXECUTABLE} evmcore) -target_link_libraries(${EXECUTABLE} devcore) -target_link_libraries(${EXECUTABLE} ${PYTHON_LS}) - -if("${TARGET_PLATFORM}" STREQUAL "w64") - target_link_libraries(${EXECUTABLE} boost_thread_win32-mt-s) - target_link_libraries(${EXECUTABLE} iphlpapi) - target_link_libraries(${EXECUTABLE} ws2_32) - target_link_libraries(${EXECUTABLE} mswsock) - target_link_libraries(${EXECUTABLE} shlwapi) -elseif (APPLE) - # Latest mavericks boost libraries only come with -mt - target_link_libraries(${EXECUTABLE} boost_thread-mt) - find_package(Threads REQUIRED) - target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT}) -elseif (UNIX) - target_link_libraries(${EXECUTABLE} ${Boost_THREAD_LIBRARY}) - target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT}) -else () - target_link_libraries(${EXECUTABLE} boost_thread) - find_package(Threads REQUIRED) - target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT}) -endif () - -install( TARGETS ${EXECUTABLE} ARCHIVE DESTINATION lib LIBRARY DESTINATION lib ) -install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} ) - diff --git a/libpyserpent/pyserpent.cpp b/libpyserpent/pyserpent.cpp deleted file mode 100644 index ff8813fcf..000000000 --- a/libpyserpent/pyserpent.cpp +++ /dev/null @@ -1,173 +0,0 @@ -#include -#include "structmember.h" - -#include -#include -#include -#include - -#define PYMETHOD(name, FROM, method, TO) \ - static PyObject * name(PyObject *, PyObject *args) { \ - try { \ - FROM(med) \ - return TO(method(med)); \ - } \ - catch (std::string e) { \ - PyErr_SetString(PyExc_Exception, e.c_str()); \ - return NULL; \ - } \ - } - -#define FROMSTR(v) \ - const char *command; \ - int len; \ - if (!PyArg_ParseTuple(args, "s#", &command, &len)) \ - return NULL; \ - std::string v = std::string(command, len); \ - -#define FROMNODE(v) \ - PyObject *node; \ - if (!PyArg_ParseTuple(args, "O", &node)) \ - return NULL; \ - Node v = cppifyNode(node); - -#define FROMLIST(v) \ - PyObject *node; \ - if (!PyArg_ParseTuple(args, "O", &node)) \ - return NULL; \ - std::vector v = cppifyNodeList(node); - -// Convert metadata into python wrapper form [file, ln, ch] -PyObject* pyifyMetadata(Metadata m) { - PyObject* a = PyList_New(0); - PyList_Append(a, Py_BuildValue("s#", m.file.c_str(), m.file.length())); - PyList_Append(a, Py_BuildValue("i", m.ln)); - PyList_Append(a, Py_BuildValue("i", m.ch)); - return a; -} - -// Convert node into python wrapper form -// [token=0/astnode=1, val, metadata, args] -PyObject* pyifyNode(Node n) { - PyObject* a = PyList_New(0); - PyList_Append(a, Py_BuildValue("i", n.type == ASTNODE)); - PyList_Append(a, Py_BuildValue("s#", n.val.c_str(), n.val.length())); - PyList_Append(a, pyifyMetadata(n.metadata)); - for (unsigned i = 0; i < n.args.size(); i++) - PyList_Append(a, pyifyNode(n.args[i])); - return a; -} - -// Convert string into python wrapper form -PyObject* pyifyString(std::string s) { - return Py_BuildValue("s#", s.c_str(), s.length()); -} - -// Convert list of nodes into python wrapper form -PyObject* pyifyNodeList(std::vector n) { - PyObject* a = PyList_New(0); - for (unsigned i = 0; i < n.size(); i++) - PyList_Append(a, pyifyNode(n[i])); - return a; -} - -// Convert pyobject int into normal form -int cppifyInt(PyObject* o) { - int out; - if (!PyArg_Parse(o, "i", &out)) - err("Argument should be integer", Metadata()); - return out; -} - -// Convert pyobject string into normal form -std::string cppifyString(PyObject* o) { - const char *command; - if (!PyArg_Parse(o, "s", &command)) - err("Argument should be string", Metadata()); - return std::string(command); -} - -// Convert metadata from python wrapper form -Metadata cppifyMetadata(PyObject* o) { - std::string file = cppifyString(PyList_GetItem(o, 0)); - int ln = cppifyInt(PyList_GetItem(o, 1)); - int ch = cppifyInt(PyList_GetItem(o, 2)); - return Metadata(file, ln, ch); -} - -// Convert node from python wrapper form -Node cppifyNode(PyObject* o) { - Node n; - int isAstNode = cppifyInt(PyList_GetItem(o, 0)); - n.type = isAstNode ? ASTNODE : TOKEN; - n.val = cppifyString(PyList_GetItem(o, 1)); - n.metadata = cppifyMetadata(PyList_GetItem(o, 2)); - std::vector args; - for (int i = 3; i < PyList_Size(o); i++) { - args.push_back(cppifyNode(PyList_GetItem(o, i))); - } - n.args = args; - return n; -} - -//Convert list of nodes into normal form -std::vector cppifyNodeList(PyObject* o) { - std::vector out; - for (int i = 0; i < PyList_Size(o); i++) { - out.push_back(cppifyNode(PyList_GetItem(o,i))); - } - return out; -} - -PYMETHOD(ps_compile, FROMSTR, compile, pyifyString) -PYMETHOD(ps_compile_chunk, FROMSTR, compileChunk, pyifyString) -PYMETHOD(ps_compile_to_lll, FROMSTR, compileToLLL, pyifyNode) -PYMETHOD(ps_compile_chunk_to_lll, FROMSTR, compileChunkToLLL, pyifyNode) -PYMETHOD(ps_compile_lll, FROMNODE, compileLLL, pyifyString) -PYMETHOD(ps_parse, FROMSTR, parseSerpent, pyifyNode) -PYMETHOD(ps_rewrite, FROMNODE, rewrite, pyifyNode) -PYMETHOD(ps_rewrite_chunk, FROMNODE, rewriteChunk, pyifyNode) -PYMETHOD(ps_pretty_compile, FROMSTR, prettyCompile, pyifyNodeList) -PYMETHOD(ps_pretty_compile_chunk, FROMSTR, prettyCompileChunk, pyifyNodeList) -PYMETHOD(ps_pretty_compile_lll, FROMNODE, prettyCompileLLL, pyifyNodeList) -PYMETHOD(ps_serialize, FROMLIST, serialize, pyifyString) -PYMETHOD(ps_deserialize, FROMSTR, deserialize, pyifyNodeList) -PYMETHOD(ps_parse_lll, FROMSTR, parseLLL, pyifyNode) - - -static PyMethodDef PyextMethods[] = { - {"compile", ps_compile, METH_VARARGS, - "Compile code."}, - {"compile_chunk", ps_compile_chunk, METH_VARARGS, - "Compile code chunk (no wrappers)."}, - {"compile_to_lll", ps_compile_to_lll, METH_VARARGS, - "Compile code to LLL."}, - {"compile_chunk_to_lll", ps_compile_chunk_to_lll, METH_VARARGS, - "Compile code chunk to LLL (no wrappers)."}, - {"compile_lll", ps_compile_lll, METH_VARARGS, - "Compile LLL to EVM."}, - {"parse", ps_parse, METH_VARARGS, - "Parse serpent"}, - {"rewrite", ps_rewrite, METH_VARARGS, - "Rewrite parsed serpent to LLL"}, - {"rewrite_chunk", ps_rewrite_chunk, METH_VARARGS, - "Rewrite parsed serpent to LLL (no wrappers)"}, - {"pretty_compile", ps_pretty_compile, METH_VARARGS, - "Compile to EVM opcodes"}, - {"pretty_compile_chunk", ps_pretty_compile_chunk, METH_VARARGS, - "Compile chunk to EVM opcodes (no wrappers)"}, - {"pretty_compile_lll", ps_pretty_compile_lll, METH_VARARGS, - "Compile LLL to EVM opcodes"}, - {"serialize", ps_serialize, METH_VARARGS, - "Convert EVM opcodes to bin"}, - {"deserialize", ps_deserialize, METH_VARARGS, - "Convert EVM bin to opcodes"}, - {"parse_lll", ps_parse_lll, METH_VARARGS, - "Parse LLL"}, - {NULL, NULL, 0, NULL} /* Sentinel */ -}; - -PyMODINIT_FUNC initserpent_pyext(void) -{ - Py_InitModule( "serpent_pyext", PyextMethods ); -} diff --git a/libqethereum/CMakeLists.txt b/libqethereum/CMakeLists.txt index ba7cd3b67..683bfec56 100644 --- a/libqethereum/CMakeLists.txt +++ b/libqethereum/CMakeLists.txt @@ -1,110 +1,41 @@ cmake_policy(SET CMP0015 NEW) - -if ("${TARGET_PLATFORM}" STREQUAL "w64") - cmake_policy(SET CMP0020 NEW) -endif () - +# let cmake autolink dependencies on windows +cmake_policy(SET CMP0020 NEW) +# this policy was introduced in cmake 3.0 +# remove if, once 3.0 will be used on unix +if (${CMAKE_MAJOR_VERSION} GREATER 2) + # old policy do not use MACOSX_RPATH + cmake_policy(SET CMP0042 OLD) + cmake_policy(SET CMP0043 OLD) +endif() set(CMAKE_INCLUDE_CURRENT_DIR ON) aux_source_directory(. SRC_LIST) +include_directories(${JSON_RPC_CPP_INCLUDE_DIRS}) include_directories(..) -link_directories(../libethereum) - -# Find Qt5 for Apple and update src_list for windows -if (APPLE) - # homebrew defaults to qt4 and installs qt5 as 'keg-only' - # which places it into /usr/local/opt insteadof /usr/local. - - set(CMAKE_PREFIX_PATH /usr/local/opt/qt5) - include_directories(/usr/local/opt/qt5/include /usr/local/include) -elseif ("${TARGET_PLATFORM}" STREQUAL "w64") - set(SRC_LIST ${SRC_LIST} ../windows/qt_plugin_import.cpp) -elseif (UNIX) - set(CMAKE_PREFIX_PATH ${CMAKE_PREFIX_PATH} ";$ENV{QTDIR}/lib/cmake") -endif () - -find_package(Qt5Gui REQUIRED) -find_package(Qt5Quick REQUIRED) -find_package(Qt5Qml REQUIRED) -find_package(Qt5Network REQUIRED) -find_package(Qt5Widgets REQUIRED) -find_package(Qt5WebKit REQUIRED) -find_package(Qt5WebKitWidgets REQUIRED) set(EXECUTABLE qethereum) -# Set name of binary and add_executable() -if (APPLE) - set(CMAKE_INSTALL_PREFIX ./) - set(BIN_INSTALL_DIR ".") - set(DOC_INSTALL_DIR ".") - - set(PROJECT_VERSION "${ETH_VERSION}") - set(MACOSX_BUNDLE_INFO_STRING "${PROJECT_NAME} ${PROJECT_VERSION}") - set(MACOSX_BUNDLE_BUNDLE_VERSION "${PROJECT_NAME} ${PROJECT_VERSION}") - set(MACOSX_BUNDLE_LONG_VERSION_STRING "${PROJECT_NAME} ${PROJECT_VERSION}") - set(MACOSX_BUNDLE_SHORT_VERSION_STRING "${PROJECT_VERSION}") - set(MACOSX_BUNDLE_COPYRIGHT "${PROJECT_COPYRIGHT_YEAR} ${PROJECT_VENDOR}") - set(MACOSX_BUNDLE_GUI_IDENTIFIER "${PROJECT_DOMAIN_SECOND}.${PROJECT_DOMAIN_FIRST}") - set(MACOSX_BUNDLE_BUNDLE_NAME ${EXECUTABLE}) - include(BundleUtilities) -endif () file(GLOB HEADERS "*.h") + if(ETH_STATIC) add_library(${EXECUTABLE} STATIC ${RESOURCE_ADDED} ${SRC_LIST} ${HEADERS}) else() add_library(${EXECUTABLE} SHARED ${RESOURCE_ADDED} ${SRC_LIST} ${HEADERS}) endif() -include_directories(/) -qt5_use_modules(${EXECUTABLE} Core Gui WebKit WebKitWidgets Widgets Network Quick Qml) -target_link_libraries(${EXECUTABLE} ethereum secp256k1 ${CRYPTOPP_LS} ${JSONRPC_LS}) - -if (APPLE) - if (${ADDFRAMEWORKS}) - set_target_properties(${EXECUTABLE} PROPERTIES MACOSX_BUNDLE_INFO_PLIST "${CMAKE_CURRENT_SOURCE_DIR}/EthereumMacOSXBundleInfo.plist.in") - endif () - - SET_SOURCE_FILES_PROPERTIES(${EXECUTABLE} PROPERTIES MACOSX_PACKAGE_LOCATION MacOS) - - # This is a workaround for when the build-type defaults to Debug, and when a multi-config generator like xcode is used, where the type - # will not be set but defaults to release. - set(generator_lowercase "${CMAKE_GENERATOR}") - string(TOLOWER "${CMAKE_GENERATOR}" generator_lowercase) - if ("${generator_lowercase}" STREQUAL "xcode") - # TODO: Not sure how to resolve this. Possibly \${TARGET_BUILD_DIR} - set(binary_build_dir "${CMAKE_CURRENT_BINARY_DIR}/Debug") - else () - set(binary_build_dir "${CMAKE_CURRENT_BINARY_DIR}") - endif () - - set(APPS ${binary_build_dir}/${EXECUTABLE}) - - if (${ADDFRAMEWORKS}) - add_custom_target(addframeworks ALL - COMMAND /usr/local/opt/qt5/bin/macdeployqt ${binary_build_dir}/${EXECUTABLE} - WORKING_DIRECTORY ${CMAKE_RUNTIME_OUTPUT_DIRECTORY} - DEPENDS ${PROJECT_NAME} - ) - endif () - -elseif ("${TARGET_PLATFORM}" STREQUAL "w64") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fno-keep-inline-dllexport -static-libgcc -static-libstdc++ -static") - set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,-s -Wl,-subsystem,windows -mthreads -L/usr/x86_64-w64-mingw32/plugins/platforms") - target_link_libraries(${EXECUTABLE} gcc) - target_link_libraries(${EXECUTABLE} mingw32 qtmain mswsock iphlpapi qwindows shlwapi Qt5PlatformSupport gdi32 comdlg32 oleaut32 imm32 winmm ole32 uuid ws2_32) - target_link_libraries(${EXECUTABLE} boost_system-mt-s) - target_link_libraries(${EXECUTABLE} boost_filesystem-mt-s) - target_link_libraries(${EXECUTABLE} boost_thread_win32-mt-s) - target_link_libraries(${EXECUTABLE} Qt5PlatformSupport) - set(CMAKE_SHARED_LIBRARY_LINK_CXX_FLAGS) -elseif (UNIX) -else () - target_link_libraries(${EXECUTABLE} boost_system) - target_link_libraries(${EXECUTABLE} boost_filesystem) - find_package(Threads REQUIRED) - target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT}) - install( TARGETS ${EXECUTABLE} ARCHIVE DESTINATION lib LIBRARY DESTINATION lib ) -endif () - +target_link_libraries(${EXECUTABLE} Qt5::Core) +target_link_libraries(${EXECUTABLE} Qt5::Gui) +target_link_libraries(${EXECUTABLE} Qt5::WebKit) +target_link_libraries(${EXECUTABLE} Qt5::WebKitWidgets) +target_link_libraries(${EXECUTABLE} Qt5::Widgets) +target_link_libraries(${EXECUTABLE} Qt5::Network) +target_link_libraries(${EXECUTABLE} Qt5::Quick) +target_link_libraries(${EXECUTABLE} Qt5::Qml) +target_link_libraries(${EXECUTABLE} ${JSON_RPC_CPP_SERVER_LIBRARIES}) +target_link_libraries(${EXECUTABLE} ethereum) +target_link_libraries(${EXECUTABLE} secp256k1) + +install( TARGETS ${EXECUTABLE} ARCHIVE DESTINATION lib LIBRARY DESTINATION lib ) +install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} ) diff --git a/libqethereum/QEthereum.cpp b/libqethereum/QEthereum.cpp index 5e5253829..daf773a22 100644 --- a/libqethereum/QEthereum.cpp +++ b/libqethereum/QEthereum.cpp @@ -227,11 +227,3 @@ void QWebThreeConnector::onProcessData(QString const& _json, QString const& _add OnRequest(_json.toStdString(), (void*)&_addInfo); } -// extra bits needed to link on VS -#ifdef _MSC_VER - -// include moc file, ofuscated to hide from automoc -#include\ -"moc_QEthereum.cpp" - -#endif diff --git a/libqethereum/QEthereum.h b/libqethereum/QEthereum.h index 4f276b7e1..657986b36 100644 --- a/libqethereum/QEthereum.h +++ b/libqethereum/QEthereum.h @@ -25,7 +25,7 @@ #include #include -#include +#include class QWebThree: public QObject { @@ -83,9 +83,9 @@ private: { \ _frame->disconnect(); \ _frame->addToJavaScriptWindowObject("_web3", qweb, QWebFrame::ScriptOwnership); \ + _frame->addToJavaScriptWindowObject("env", _env, QWebFrame::QtOwnership); \ _frame->evaluateJavaScript(contentsOfQResource(":/js/es6-promise-2.0.0.js")); \ - _frame->evaluateJavaScript(contentsOfQResource(":/js/main.js")); \ - _frame->evaluateJavaScript(contentsOfQResource(":/js/qt.js")); \ + _frame->evaluateJavaScript(contentsOfQResource(":/js/ethereum.js")); \ _frame->evaluateJavaScript(contentsOfQResource(":/js/setup.js")); \ } diff --git a/libqethereum/QmlEthereum.cpp b/libqethereum/QmlEthereum.cpp deleted file mode 100644 index b1b926f42..000000000 --- a/libqethereum/QmlEthereum.cpp +++ /dev/null @@ -1,188 +0,0 @@ -#if ETH_QTQML -#include -#endif -#include -#include -#include -#include -#include -#include -#include -#include "QmlEthereum.h" -using namespace std; - -// types -using dev::bytes; -using dev::bytesConstRef; -using dev::h160; -using dev::h256; -using dev::u160; -using dev::u256; -using dev::u256s; -using dev::RLP; -using dev::Address; -using dev::eth::BlockInfo; -using dev::eth::Client; -using dev::eth::Instruction; -using dev::KeyPair; -using dev::eth::NodeMode; -using dev::Secret; -using dev::eth::Transaction; -using dev::p2p::PeerInfo; - -// functions -using dev::toHex; -using dev::fromHex; -using dev::right160; -using dev::simpleDebugOut; -using dev::toLog2; -using dev::toString; -using dev::eth::disassemble; -using dev::eth::formatBalance; -using dev::eth::units; - -// vars -using dev::g_logPost; -using dev::g_logVerbosity; - -// Horrible global for the mainwindow. Needed for the QmlEthereums to find the Main window which acts as multiplexer for now. -// Can get rid of this once we've sorted out ITC for signalling & multiplexed querying. -dev::eth::Client* g_qmlClient; -QObject* g_qmlMain; -#if 0 -QmlAccount::QmlAccount(QObject*) -{ -} - -QmlAccount::~QmlAccount() -{ -} - -void QmlAccount::setEthereum(QmlEthereum* _eth) -{ - if (m_eth == _eth) - return; -// if (m_eth) -// disconnect(m_eth, SIGNAL(changed()), this, SIGNAL(changed())); - m_eth = _eth; -// if (m_eth) -// connect(m_eth, SIGNAL(changed()), this, SIGNAL(changed())); - ethChanged(); -// changed(); -} - -dev::u256 QmlAccount::balance() const -{ - if (m_eth) - return m_eth->balanceAt(m_address); - return u256(0); -} - -double QmlAccount::txCount() const -{ - if (m_eth) - return m_eth->txCountAt(m_address); - return 0; -} - -bool QmlAccount::isContract() const -{ - if (m_eth) - return m_eth->isContractAt(m_address); - return 0; -} - -QmlEthereum::QmlEthereum(QObject* _p): QObject(_p) -{ -// connect(g_qmlMain, SIGNAL(changed()), SIGNAL(changed())); -} - -QmlEthereum::~QmlEthereum() -{ -} - -Client* QmlEthereum::client() const -{ - return g_qmlClient; -} - -Address QmlEthereum::coinbase() const -{ - return client()->address(); -} - -void QmlEthereum::setCoinbase(Address _a) -{ - if (client()->address() != _a) - { - client()->setAddress(_a); -// changed(); - } -} - -u256 QmlEthereum::balanceAt(Address _a) const -{ - return client()->postState().balance(_a); -} - -bool QmlEthereum::isContractAt(Address _a) const -{ - return client()->postState().addressHasCode(_a); -} - -bool QmlEthereum::isMining() const -{ - return client()->isMining(); -} - -bool QmlEthereum::isListening() const -{ - return client()->haveNetwork(); -} - -void QmlEthereum::setMining(bool _l) -{ - if (_l) - client()->startMining(); - else - client()->stopMining(); -} - -void QmlEthereum::setListening(bool _l) -{ - if (_l) - client()->startNetwork(); - else - client()->stopNetwork(); -} - -double QmlEthereum::txCountAt(Address _a) const -{ - return (double)client()->postState().transactionsFrom(_a); -} - -unsigned QmlEthereum::peerCount() const -{ - return (unsigned)client()->peerCount(); -} - -void QmlEthereum::transact(Secret _secret, u256 _amount, u256 _gasPrice, u256 _gas, QByteArray _init) -{ - client()->transact(_secret, _amount, bytes(_init.data(), _init.data() + _init.size()), _gas, _gasPrice); -} - -void QmlEthereum::transact(Secret _secret, Address _dest, u256 _amount, u256 _gasPrice, u256 _gas, QByteArray _data) -{ - client()->transact(_secret, _amount, _dest, bytes(_data.data(), _data.data() + _data.size()), _gas, _gasPrice); -} - -#endif - -// extra bits needed to link on VS -#ifdef _MSC_VER - -// include moc file, ofuscated to hide from automoc -#include\ -"moc_QmlEthereum.cpp" - -#endif diff --git a/libqethereum/QmlEthereum.h b/libqethereum/QmlEthereum.h deleted file mode 100644 index d242540a1..000000000 --- a/libqethereum/QmlEthereum.h +++ /dev/null @@ -1,283 +0,0 @@ -#pragma once - -#include -#if ETH_QTQML -#include -#endif -#include -#include - -namespace dev { namespace eth { -class Client; -class State; -}} - -class QQmlEngine; -class QmlAccount; -class QmlEthereum; - -extern dev::eth::Client* g_qmlClient; -extern QObject* g_qmlMain; - -Q_DECLARE_METATYPE(dev::u256) -Q_DECLARE_METATYPE(dev::Address) -Q_DECLARE_METATYPE(dev::Secret) -Q_DECLARE_METATYPE(dev::KeyPair) -//Q_DECLARE_METATYPE(QmlAccount*) -//Q_DECLARE_METATYPE(QmlEthereum*) - -class QmlU256Helper: public QObject -{ - Q_OBJECT - -public: - QmlU256Helper(QObject* _p = nullptr): QObject(_p) {} - - Q_INVOKABLE dev::u256 add(dev::u256 _a, dev::u256 _b) const { return _a + _b; } - Q_INVOKABLE dev::u256 sub(dev::u256 _a, dev::u256 _b) const { return _a - _b; } - Q_INVOKABLE dev::u256 mul(dev::u256 _a, int _b) const { return _a * _b; } - Q_INVOKABLE dev::u256 mul(int _a, dev::u256 _b) const { return _a * _b; } - Q_INVOKABLE dev::u256 div(dev::u256 _a, int _b) const { return _a / _b; } - - Q_INVOKABLE dev::u256 wei(double _s) const { return (dev::u256)_s; } - Q_INVOKABLE dev::u256 szabo(double _s) const { return (dev::u256)(_s * (double)dev::eth::szabo); } - Q_INVOKABLE dev::u256 finney(double _s) const { return (dev::u256)(_s * (double)dev::eth::finney); } - Q_INVOKABLE dev::u256 ether(double _s) const { return (dev::u256)(_s * (double)dev::eth::ether); } - Q_INVOKABLE dev::u256 wei(unsigned _s) const { return (dev::u256)_s; } - Q_INVOKABLE dev::u256 szabo(unsigned _s) const { return (dev::u256)(_s * dev::eth::szabo); } - Q_INVOKABLE dev::u256 finney(unsigned _s) const { return (dev::u256)(_s * dev::eth::finney); } - Q_INVOKABLE dev::u256 ether(unsigned _s) const { return (dev::u256)(_s * dev::eth::ether); } - Q_INVOKABLE double toWei(dev::u256 _t) const { return (double)_t; } - Q_INVOKABLE double toSzabo(dev::u256 _t) const { return toWei(_t) / (double)dev::eth::szabo; } - Q_INVOKABLE double toFinney(dev::u256 _t) const { return toWei(_t) / (double)dev::eth::finney; } - Q_INVOKABLE double toEther(dev::u256 _t) const { return toWei(_t) / (double)dev::eth::ether; } - - Q_INVOKABLE double value(dev::u256 _t) const { return (double)_t; } - - Q_INVOKABLE QString stringOf(dev::u256 _t) const { return QString::fromStdString(dev::eth::formatBalance(_t)); } -}; - -class QmlKeyHelper: public QObject -{ - Q_OBJECT - -public: - QmlKeyHelper(QObject* _p = nullptr): QObject(_p) {} - - Q_INVOKABLE dev::KeyPair create() const { return dev::KeyPair::create(); } - Q_INVOKABLE dev::Address address(dev::KeyPair _p) const { return _p.address(); } - Q_INVOKABLE dev::Secret secret(dev::KeyPair _p) const { return _p.secret(); } - Q_INVOKABLE dev::KeyPair keypair(dev::Secret _k) const { return dev::KeyPair(_k); } - - Q_INVOKABLE bool isNull(dev::Address _a) const { return !_a; } - - Q_INVOKABLE dev::Address addressOf(QString _s) const { return dev::Address(_s.toStdString()); } - Q_INVOKABLE QString stringOf(dev::Address _a) const { return QString::fromStdString(dev::toHex(_a.asArray())); } - Q_INVOKABLE QString toAbridged(dev::Address _a) const { return QString::fromStdString(_a.abridged()); } -}; -#if 0 -class QmlAccount: public QObject -{ - Q_OBJECT - -public: - QmlAccount(QObject* _p = nullptr); - virtual ~QmlAccount(); - - Q_INVOKABLE QmlEthereum* ethereum() const { return m_eth; } - Q_INVOKABLE dev::u256 balance() const; - Q_INVOKABLE double txCount() const; - Q_INVOKABLE bool isContract() const; - Q_INVOKABLE dev::Address address() const { return m_address; } - - // TODO: past transactions models. - -public slots: - void setEthereum(QmlEthereum* _eth); - void setAddress(dev::Address _a) { m_address = _a; } - -signals: - void changed(); - void ethChanged(); - -private: - QmlEthereum* m_eth = nullptr; - dev::Address m_address; - - Q_PROPERTY(dev::u256 balance READ balance NOTIFY changed STORED false) - Q_PROPERTY(double txCount READ txCount NOTIFY changed STORED false) - Q_PROPERTY(bool isContract READ isContract NOTIFY changed STORED false) - Q_PROPERTY(dev::Address address READ address WRITE setAddress NOTIFY changed) - Q_PROPERTY(QmlEthereum* ethereum READ ethereum WRITE setEthereum NOTIFY ethChanged) -}; - -class QmlEthereum: public QObject -{ - Q_OBJECT - -public: - QmlEthereum(QObject* _p = nullptr); - virtual ~QmlEthereum(); - - dev::eth::Client* client() const; - - static QObject* constructU256Helper(QQmlEngine*, QJSEngine*) { return new QmlU256Helper; } - static QObject* constructKeyHelper(QQmlEngine*, QJSEngine*) { return new QmlKeyHelper; } - - Q_INVOKABLE dev::Address coinbase() const; - - Q_INVOKABLE bool isListening() const; - Q_INVOKABLE bool isMining() const; - - Q_INVOKABLE dev::u256 balanceAt(dev::Address _a) const; - Q_INVOKABLE double txCountAt(dev::Address _a) const; - Q_INVOKABLE bool isContractAt(dev::Address _a) const; - - Q_INVOKABLE unsigned peerCount() const; - - Q_INVOKABLE QmlEthereum* self() { return this; } - -public slots: - void transact(dev::Secret _secret, dev::Address _dest, dev::u256 _amount, dev::u256 _gasPrice, dev::u256 _gas, QByteArray _data); - void transact(dev::Secret _secret, dev::u256 _amount, dev::u256 _gasPrice, dev::u256 _gas, QByteArray _init); - void setCoinbase(dev::Address); - void setMining(bool _l); - - void setListening(bool _l); - -signals: - void coinbaseChanged(); -// void netChanged(); -// void miningChanged(); - -private: - Q_PROPERTY(dev::Address coinbase READ coinbase WRITE setCoinbase NOTIFY coinbaseChanged) - Q_PROPERTY(bool listening READ isListening WRITE setListening) - Q_PROPERTY(bool mining READ isMining WRITE setMining) -}; -#endif -#if 0 -template T to(QVariant const& _s) { if (_s.type() != QVariant::String) return T(); auto s = _s.toString().toLatin1(); assert(s.size() == sizeof(T)); return *(T*)s.data(); } -template QVariant toQJS(T const& _s) { QLatin1String ret((char*)&_s, sizeof(T)); assert(QVariant(QString(ret)).toString().toLatin1().size() == sizeof(T)); assert(*(T*)(QVariant(QString(ret)).toString().toLatin1().data()) == _s); return QVariant(QString(ret)); } - -class U256Helper: public QObject -{ - Q_OBJECT - -public: - U256Helper(QObject* _p = nullptr): QObject(_p) {} - - static dev::u256 in(QVariant const& _s) { return to(_s); } - static QVariant out(dev::u256 const& _s) { return toQJS(_s); } - - Q_INVOKABLE QVariant add(QVariant _a, QVariant _b) const { return out(in(_a) + in(_b)); } - Q_INVOKABLE QVariant sub(QVariant _a, QVariant _b) const { return out(in(_a) - in(_b)); } - Q_INVOKABLE QVariant mul(QVariant _a, int _b) const { return out(in(_a) * in(_b)); } - Q_INVOKABLE QVariant mul(int _a, QVariant _b) const { return out(in(_a) * in(_b)); } - Q_INVOKABLE QVariant div(QVariant _a, int _b) const { return out(in(_a) / in(_b)); } - - Q_INVOKABLE QVariant wei(double _s) const { return out(dev::u256(_s)); } - Q_INVOKABLE QVariant szabo(double _s) const { return out(dev::u256(_s * (double)dev::eth::szabo)); } - Q_INVOKABLE QVariant finney(double _s) const { return out(dev::u256(_s * (double)dev::eth::finney)); } - Q_INVOKABLE QVariant ether(double _s) const { return out(dev::u256(_s * (double)dev::eth::ether)); } - Q_INVOKABLE QVariant wei(unsigned _s) const { return value(_s); } - Q_INVOKABLE QVariant szabo(unsigned _s) const { return out(dev::u256(_s) * dev::eth::szabo); } - Q_INVOKABLE QVariant finney(unsigned _s) const { return out(dev::u256(_s) * dev::eth::finney); } - Q_INVOKABLE QVariant ether(unsigned _s) const { return out(dev::u256(_s) * dev::eth::ether); } - Q_INVOKABLE double toWei(QVariant _t) const { return toValue(_t); } - Q_INVOKABLE double toSzabo(QVariant _t) const { return toWei(_t) / (double)dev::eth::szabo; } - Q_INVOKABLE double toFinney(QVariant _t) const { return toWei(_t) / (double)dev::eth::finney; } - Q_INVOKABLE double toEther(QVariant _t) const { return toWei(_t) / (double)dev::eth::ether; } - - Q_INVOKABLE QVariant value(unsigned _s) const { return out(dev::u256(_s)); } - Q_INVOKABLE double toValue(QVariant _t) const { return (double)in(_t); } - - Q_INVOKABLE QString ethOf(QVariant _t) const { return QString::fromStdString(dev::eth::formatBalance(in(_t))); } - Q_INVOKABLE QString stringOf(QVariant _t) const { return QString::fromStdString(dev::eth::toString(in(_t))); } - - Q_INVOKABLE QByteArray bytesOf(QVariant _t) const { dev::h256 b = in(_t); return QByteArray((char const*)&b, sizeof(dev::h256)); } - Q_INVOKABLE QVariant fromHex(QString _s) const { return out((dev::u256)dev::h256(_s.toStdString())); } - - Q_INVOKABLE QVariant fromAddress(QVariant/*dev::Address*/ _a) const { return out((dev::eth::u160)to(_a)); } - Q_INVOKABLE QVariant toAddress(QVariant/*dev::Address*/ _a) const { return toQJS((dev::eth::u160)in(_a)); } - - Q_INVOKABLE bool isNull(QVariant/*dev::Address*/ _a) const { return !in(_a); } -}; - -class KeyHelper: public QObject -{ - Q_OBJECT - -public: - KeyHelper(QObject* _p = nullptr): QObject(_p) {} - - static dev::Address in(QVariant const& _s) { return to(_s); } - static QVariant out(dev::Address const& _s) { return toQJS(_s); } - - Q_INVOKABLE QVariant/*dev::KeyPair*/ create() const { return toQJS(dev::KeyPair::create()); } - Q_INVOKABLE QVariant/*dev::Address*/ address(QVariant/*dev::KeyPair*/ _p) const { return out(to(_p).address()); } - Q_INVOKABLE QVariant/*dev::Secret*/ secret(QVariant/*dev::KeyPair*/ _p) const { return toQJS(to(_p).secret()); } - Q_INVOKABLE QVariant/*dev::KeyPair*/ keypair(QVariant/*dev::Secret*/ _k) const { return toQJS(dev::KeyPair(to(_k))); } - - Q_INVOKABLE bool isNull(QVariant/*dev::Address*/ _a) const { return !in(_a); } - - Q_INVOKABLE QVariant/*dev::Address*/ addressOf(QString _s) const { return out(dev::Address(_s.toStdString())); } - Q_INVOKABLE QString stringOf(QVariant/*dev::Address*/ _a) const { return QString::fromStdString(dev::eth::toHex(in(_a).asArray())); } - Q_INVOKABLE QString toAbridged(QVariant/*dev::Address*/ _a) const { return QString::fromStdString(in(_a).abridged()); } - -}; - -class BytesHelper: public QObject -{ - Q_OBJECT - -public: - BytesHelper(QObject* _p = nullptr): QObject(_p) {} - - Q_INVOKABLE QByteArray concat(QVariant _v, QVariant _w) const - { - QByteArray ba; - if (_v.type() == QVariant::ByteArray) - ba = _v.toByteArray(); - else - ba = _v.toString().toLatin1(); - QByteArray ba2; - if (_w.type() == QVariant::ByteArray) - ba2 = _w.toByteArray(); - else - ba2 = _w.toString().toLatin1(); - ba.append(ba2); - return QByteArray(ba); - } - Q_INVOKABLE QByteArray concat(QByteArray _v, QByteArray _w) const - { - _v.append(_w); - return _v; - } - Q_INVOKABLE QByteArray fromString(QString _s) const - { - return _s.toLatin1(); - } - Q_INVOKABLE QByteArray fromString(QString _s, unsigned _padding) const - { - QByteArray b = _s.toLatin1(); - for (unsigned i = b.size(); i < _padding; ++i) - b.append((char)0); - b.resize(_padding); - return b; - } - Q_INVOKABLE QString toString(QByteArray _b) const - { - while (_b.size() && !_b[_b.size() - 1]) - _b.resize(_b.size() - 1); - return QString::fromLatin1(_b); - } - Q_INVOKABLE QVariant u256of(QByteArray _s) const - { - while (_s.size() < 32) - _s.append((char)0); - dev::h256 ret((uint8_t const*)_s.data(), dev::h256::ConstructFromPointer); - return toQJS(ret); - } -}; -#endif diff --git a/libserpent/CMakeLists.txt b/libserpent/CMakeLists.txt index c2fe89cc0..1c5b8e147 100644 --- a/libserpent/CMakeLists.txt +++ b/libserpent/CMakeLists.txt @@ -1,45 +1,32 @@ cmake_policy(SET CMP0015 NEW) +# this policy was introduced in cmake 3.0 +# remove if, once 3.0 will be used on unix +if (${CMAKE_MAJOR_VERSION} GREATER 2) + # old policy do not use MACOSX_RPATH + cmake_policy(SET CMP0042 OLD) +endif() +set(CMAKE_AUTOMOC OFF) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DSTATICLIB") aux_source_directory(. SRC_LIST) +include_directories(..) + set(EXECUTABLE serpent) file(GLOB HEADERS "*.h") + if(ETH_STATIC) add_library(${EXECUTABLE} STATIC ${SRC_LIST} ${HEADERS}) else() add_library(${EXECUTABLE} SHARED ${SRC_LIST} ${HEADERS}) endif() -include_directories(..) - target_link_libraries(${EXECUTABLE} lll) target_link_libraries(${EXECUTABLE} evmcore) target_link_libraries(${EXECUTABLE} devcore) -if("${TARGET_PLATFORM}" STREQUAL "w64") - target_link_libraries(${EXECUTABLE} boost_thread_win32-mt-s) - target_link_libraries(${EXECUTABLE} iphlpapi) - target_link_libraries(${EXECUTABLE} ws2_32) - target_link_libraries(${EXECUTABLE} mswsock) - target_link_libraries(${EXECUTABLE} shlwapi) -elseif (APPLE) - # Latest mavericks boost libraries only come with -mt - target_link_libraries(${EXECUTABLE} boost_thread-mt) - find_package(Threads REQUIRED) - target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT}) -elseif (UNIX) - target_link_libraries(${EXECUTABLE} ${Boost_THREAD_LIBRARY}) - target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT}) -else () - target_link_libraries(${EXECUTABLE} boost_thread) - find_package(Threads REQUIRED) - target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT}) -endif () - install( TARGETS ${EXECUTABLE} ARCHIVE DESTINATION lib LIBRARY DESTINATION lib ) install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} ) -#install( FILES ${CMAKE_CURRENT_BINARY_DIR}/libserpent.so DESTINATION lib ) diff --git a/libserpent/compiler.cpp b/libserpent/compiler.cpp index 623ab3950..30628fbc9 100644 --- a/libserpent/compiler.cpp +++ b/libserpent/compiler.cpp @@ -131,8 +131,7 @@ programData opcodeify(Node node, } // Declare variable else { - Node nodelist[] = { }; - return pd(aux, multiToken(nodelist, 0, m), 0); + return pd(aux, multiToken(nullptr, 0, m), 0); } } // Define functions (TODO: eventually move to rewriter.cpp, keep diff --git a/libserpent/rewriter.cpp b/libserpent/rewriter.cpp index 3042eeb45..443457acf 100644 --- a/libserpent/rewriter.cpp +++ b/libserpent/rewriter.cpp @@ -2,6 +2,7 @@ #include #include #include +#include #include "util.h" #include "lllparser.h" #include "bignum.h" diff --git a/libserpent/util.cpp b/libserpent/util.cpp index 39eeb20be..fbce5e8b5 100644 --- a/libserpent/util.cpp +++ b/libserpent/util.cpp @@ -2,6 +2,7 @@ #include #include #include +#include #include "util.h" #include "bignum.h" #include diff --git a/libsolidity/AST.cpp b/libsolidity/AST.cpp index 565560adc..8174d138a 100644 --- a/libsolidity/AST.cpp +++ b/libsolidity/AST.cpp @@ -25,6 +25,7 @@ #include #include #include +#include using namespace std; @@ -33,234 +34,61 @@ namespace dev namespace solidity { -void ContractDefinition::accept(ASTVisitor& _visitor) +TypeError ASTNode::createTypeError(string const& _description) const { - if (_visitor.visit(*this)) - { - listAccept(m_definedStructs, _visitor); - listAccept(m_stateVariables, _visitor); - listAccept(m_definedFunctions, _visitor); - } - _visitor.endVisit(*this); -} - -void StructDefinition::accept(ASTVisitor& _visitor) -{ - if (_visitor.visit(*this)) - listAccept(m_members, _visitor); - _visitor.endVisit(*this); -} - -void ParameterList::accept(ASTVisitor& _visitor) -{ - if (_visitor.visit(*this)) - listAccept(m_parameters, _visitor); - _visitor.endVisit(*this); -} - -void FunctionDefinition::accept(ASTVisitor& _visitor) -{ - if (_visitor.visit(*this)) - { - m_parameters->accept(_visitor); - if (m_returnParameters) - m_returnParameters->accept(_visitor); - m_body->accept(_visitor); - } - _visitor.endVisit(*this); -} - -void VariableDeclaration::accept(ASTVisitor& _visitor) -{ - if (_visitor.visit(*this)) - if (m_typeName) - m_typeName->accept(_visitor); - _visitor.endVisit(*this); -} - -void TypeName::accept(ASTVisitor& _visitor) -{ - _visitor.visit(*this); - _visitor.endVisit(*this); -} - -void ElementaryTypeName::accept(ASTVisitor& _visitor) -{ - _visitor.visit(*this); - _visitor.endVisit(*this); -} - -void UserDefinedTypeName::accept(ASTVisitor& _visitor) -{ - _visitor.visit(*this); - _visitor.endVisit(*this); -} - -void Mapping::accept(ASTVisitor& _visitor) -{ - if (_visitor.visit(*this)) - { - m_keyType->accept(_visitor); - m_valueType->accept(_visitor); - } - _visitor.endVisit(*this); -} - -void Statement::accept(ASTVisitor& _visitor) -{ - _visitor.visit(*this); - _visitor.endVisit(*this); -} - -void Block::accept(ASTVisitor& _visitor) -{ - if (_visitor.visit(*this)) - listAccept(m_statements, _visitor); - _visitor.endVisit(*this); -} - -void IfStatement::accept(ASTVisitor& _visitor) -{ - if (_visitor.visit(*this)) - { - m_condition->accept(_visitor); - m_trueBody->accept(_visitor); - if (m_falseBody) - m_falseBody->accept(_visitor); - } - _visitor.endVisit(*this); -} - -void BreakableStatement::accept(ASTVisitor& _visitor) -{ - _visitor.visit(*this); - _visitor.endVisit(*this); -} - -void WhileStatement::accept(ASTVisitor& _visitor) -{ - if (_visitor.visit(*this)) - { - m_condition->accept(_visitor); - m_body->accept(_visitor); - } - _visitor.endVisit(*this); -} - -void Continue::accept(ASTVisitor& _visitor) -{ - _visitor.visit(*this); - _visitor.endVisit(*this); -} - -void Break::accept(ASTVisitor& _visitor) -{ - _visitor.visit(*this); - _visitor.endVisit(*this); -} - -void Return::accept(ASTVisitor& _visitor) -{ - if (_visitor.visit(*this)) - if (m_expression) - m_expression->accept(_visitor); - _visitor.endVisit(*this); -} - -void ExpressionStatement::accept(ASTVisitor& _visitor) -{ - if (_visitor.visit(*this)) - if (m_expression) - m_expression->accept(_visitor); - _visitor.endVisit(*this); -} - -void VariableDefinition::accept(ASTVisitor& _visitor) -{ - if (_visitor.visit(*this)) - { - m_variable->accept(_visitor); - if (m_value) - m_value->accept(_visitor); - } - _visitor.endVisit(*this); -} - -void Assignment::accept(ASTVisitor& _visitor) -{ - if (_visitor.visit(*this)) - { - m_leftHandSide->accept(_visitor); - m_rightHandSide->accept(_visitor); - } - _visitor.endVisit(*this); -} - -void UnaryOperation::accept(ASTVisitor& _visitor) -{ - if (_visitor.visit(*this)) - m_subExpression->accept(_visitor); - _visitor.endVisit(*this); + return TypeError() << errinfo_sourceLocation(getLocation()) << errinfo_comment(_description); } -void BinaryOperation::accept(ASTVisitor& _visitor) +vector ContractDefinition::getInterfaceFunctions() const { - if (_visitor.visit(*this)) + vector exportedFunctions; + for (ASTPointer const& f: m_definedFunctions) + if (f->isPublic() && f->getName() != getName()) + exportedFunctions.push_back(f.get()); + auto compareNames = [](FunctionDefinition const* _a, FunctionDefinition const* _b) { - m_left->accept(_visitor); - m_right->accept(_visitor); - } - _visitor.endVisit(*this); -} + return _a->getName().compare(_b->getName()) < 0; + }; -void FunctionCall::accept(ASTVisitor& _visitor) -{ - if (_visitor.visit(*this)) - { - m_expression->accept(_visitor); - listAccept(m_arguments, _visitor); - } - _visitor.endVisit(*this); + sort(exportedFunctions.begin(), exportedFunctions.end(), compareNames); + return exportedFunctions; } -void MemberAccess::accept(ASTVisitor& _visitor) +void StructDefinition::checkMemberTypes() const { - if (_visitor.visit(*this)) - m_expression->accept(_visitor); - _visitor.endVisit(*this); + for (ASTPointer const& member: getMembers()) + if (!member->getType()->canBeStored()) + BOOST_THROW_EXCEPTION(member->createTypeError("Type cannot be used in struct.")); } -void IndexAccess::accept(ASTVisitor& _visitor) +void StructDefinition::checkRecursion() const { - if (_visitor.visit(*this)) + set definitionsSeen; + vector queue = {this}; + while (!queue.empty()) { - m_base->accept(_visitor); - m_index->accept(_visitor); + StructDefinition const* def = queue.back(); + queue.pop_back(); + if (definitionsSeen.count(def)) + BOOST_THROW_EXCEPTION(ParserError() << errinfo_sourceLocation(def->getLocation()) + << errinfo_comment("Recursive struct definition.")); + definitionsSeen.insert(def); + for (ASTPointer const& member: def->getMembers()) + if (member->getType()->getCategory() == Type::Category::STRUCT) + { + UserDefinedTypeName const& typeName = dynamic_cast(*member->getTypeName()); + queue.push_back(&dynamic_cast(*typeName.getReferencedDeclaration())); + } } - _visitor.endVisit(*this); } -void Identifier::accept(ASTVisitor& _visitor) +void FunctionDefinition::checkTypeRequirements() { - _visitor.visit(*this); - _visitor.endVisit(*this); -} + for (ASTPointer const& var: getParameters() + getReturnParameters()) + if (!var->getType()->canLiveOutsideStorage()) + BOOST_THROW_EXCEPTION(var->createTypeError("Type is required to live outside storage.")); -void ElementaryTypeNameExpression::accept(ASTVisitor& _visitor) -{ - _visitor.visit(*this); - _visitor.endVisit(*this); -} - -void Literal::accept(ASTVisitor& _visitor) -{ - _visitor.visit(*this); - _visitor.endVisit(*this); -} - -TypeError ASTNode::createTypeError(string const& _description) -{ - return TypeError() << errinfo_sourceLocation(getLocation()) << errinfo_comment(_description); + m_body->checkTypeRequirements(); } void Block::checkTypeRequirements() @@ -300,7 +128,7 @@ void Return::checkTypeRequirements() void VariableDefinition::checkTypeRequirements() { // Variables can be declared without type (with "var"), in which case the first assignment - // setsthe type. + // sets the type. // Note that assignments before the first declaration are legal because of the special scoping // rules inherited from JavaScript. if (m_value) @@ -319,8 +147,10 @@ void VariableDefinition::checkTypeRequirements() void Assignment::checkTypeRequirements() { m_leftHandSide->checkTypeRequirements(); - if (!m_leftHandSide->isLvalue()) - BOOST_THROW_EXCEPTION(createTypeError("Expression has to be an lvalue.")); + m_leftHandSide->requireLValue(); + //@todo later, assignments to structs might be possible, but not to mappings + if (!m_leftHandSide->getType()->isValueType() && !m_leftHandSide->isLocalLValue()) + BOOST_THROW_EXCEPTION(createTypeError("Assignment to non-local non-value lvalue.")); m_rightHandSide->expectType(*m_leftHandSide->getType()); m_type = m_leftHandSide->getType(); if (m_assigmentOperator != Token::ASSIGN) @@ -344,13 +174,19 @@ void Expression::expectType(Type const& _expectedType) + _expectedType.toString() + ".")); } +void Expression::requireLValue() +{ + if (!isLValue()) + BOOST_THROW_EXCEPTION(createTypeError("Expression has to be an lvalue.")); + m_lvalueRequested = true; +} + void UnaryOperation::checkTypeRequirements() { // INC, DEC, ADD, SUB, NOT, BIT_NOT, DELETE m_subExpression->checkTypeRequirements(); if (m_operator == Token::Value::INC || m_operator == Token::Value::DEC || m_operator == Token::Value::DELETE) - if (!m_subExpression->isLvalue()) - BOOST_THROW_EXCEPTION(createTypeError("Expression has to be an lvalue.")); + m_subExpression->requireLValue(); m_type = m_subExpression->getType(); if (!m_type->acceptsUnaryOperator(m_operator)) BOOST_THROW_EXCEPTION(createTypeError("Unary operator not compatible with type.")); @@ -404,19 +240,19 @@ void FunctionCall::checkTypeRequirements() //@todo would be nice to create a struct type from the arguments // and then ask if that is implicitly convertible to the struct represented by the // function parameters - FunctionDefinition const& fun = dynamic_cast(*expressionType).getFunction(); - vector> const& parameters = fun.getParameters(); - if (parameters.size() != m_arguments.size()) + FunctionType const& functionType = dynamic_cast(*expressionType); + TypePointers const& parameterTypes = functionType.getParameterTypes(); + if (parameterTypes.size() != m_arguments.size()) BOOST_THROW_EXCEPTION(createTypeError("Wrong argument count for function call.")); for (size_t i = 0; i < m_arguments.size(); ++i) - if (!m_arguments[i]->getType()->isImplicitlyConvertibleTo(*parameters[i]->getType())) + if (!m_arguments[i]->getType()->isImplicitlyConvertibleTo(*parameterTypes[i])) BOOST_THROW_EXCEPTION(createTypeError("Invalid type for argument in function call.")); // @todo actually the return type should be an anonymous struct, // but we change it to the type of the first return value until we have structs - if (fun.getReturnParameters().empty()) + if (functionType.getReturnParameterTypes().empty()) m_type = make_shared(); else - m_type = fun.getReturnParameters().front()->getType(); + m_type = functionType.getReturnParameterTypes().front(); } } @@ -427,14 +263,25 @@ bool FunctionCall::isTypeConversion() const void MemberAccess::checkTypeRequirements() { - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Member access not yet implemented.")); - // m_type = ; + m_expression->checkTypeRequirements(); + Type const& type = *m_expression->getType(); + m_type = type.getMemberType(*m_memberName); + if (!m_type) + BOOST_THROW_EXCEPTION(createTypeError("Member \"" + *m_memberName + "\" not found in " + type.toString())); + //@todo later, this will not always be STORAGE + m_lvalue = type.getCategory() == Type::Category::STRUCT ? LValueType::STORAGE : LValueType::NONE; } void IndexAccess::checkTypeRequirements() { - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Index access not yet implemented.")); - // m_type = ; + m_base->checkTypeRequirements(); + if (m_base->getType()->getCategory() != Type::Category::MAPPING) + BOOST_THROW_EXCEPTION(m_base->createTypeError("Indexed expression has to be a mapping (is " + + m_base->getType()->toString() + ")")); + MappingType const& type = dynamic_cast(*m_base->getType()); + m_index->expectType(*type.getKeyType()); + m_type = type.getValueType(); + m_lvalue = LValueType::STORAGE; } void Identifier::checkTypeRequirements() @@ -442,36 +289,42 @@ void Identifier::checkTypeRequirements() if (asserts(m_referencedDeclaration)) BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Identifier not resolved.")); - VariableDeclaration* variable = dynamic_cast(m_referencedDeclaration); + VariableDeclaration const* variable = dynamic_cast(m_referencedDeclaration); if (variable) { if (!variable->getType()) BOOST_THROW_EXCEPTION(createTypeError("Variable referenced before type could be determined.")); m_type = variable->getType(); - m_isLvalue = true; + m_lvalue = variable->isLocalVariable() ? LValueType::LOCAL : LValueType::STORAGE; return; } //@todo can we unify these with TypeName::toType()? - StructDefinition* structDef = dynamic_cast(m_referencedDeclaration); + StructDefinition const* structDef = dynamic_cast(m_referencedDeclaration); if (structDef) { // note that we do not have a struct type here - m_type = make_shared(make_shared(*structDef)); + m_type = make_shared(make_shared(*structDef)); return; } - FunctionDefinition* functionDef = dynamic_cast(m_referencedDeclaration); + FunctionDefinition const* functionDef = dynamic_cast(m_referencedDeclaration); if (functionDef) { // a function reference is not a TypeType, because calling a TypeType converts to the type. // Calling a function (e.g. function(12), otherContract.function(34)) does not do a type // conversion. - m_type = make_shared(*functionDef); + m_type = make_shared(*functionDef); return; } - ContractDefinition* contractDef = dynamic_cast(m_referencedDeclaration); + ContractDefinition const* contractDef = dynamic_cast(m_referencedDeclaration); if (contractDef) { - m_type = make_shared(make_shared(*contractDef)); + m_type = make_shared(make_shared(*contractDef)); + return; + } + MagicVariableDeclaration const* magicVariable = dynamic_cast(m_referencedDeclaration); + if (magicVariable) + { + m_type = magicVariable->getType(); return; } BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Declaration reference of unknown/forbidden type.")); @@ -479,7 +332,7 @@ void Identifier::checkTypeRequirements() void ElementaryTypeNameExpression::checkTypeRequirements() { - m_type = make_shared(Type::fromElementaryTypeName(m_typeToken)); + m_type = make_shared(Type::fromElementaryTypeName(m_typeToken)); } void Literal::checkTypeRequirements() diff --git a/libsolidity/AST.h b/libsolidity/AST.h index 19328e5f7..19c4b4275 100644 --- a/libsolidity/AST.h +++ b/libsolidity/AST.h @@ -39,6 +39,7 @@ namespace solidity { class ASTVisitor; +class ASTConstVisitor; /** @@ -54,19 +55,26 @@ public: virtual ~ASTNode() {} virtual void accept(ASTVisitor& _visitor) = 0; + virtual void accept(ASTConstVisitor& _visitor) const = 0; template static void listAccept(std::vector>& _list, ASTVisitor& _visitor) { for (ASTPointer& element: _list) element->accept(_visitor); } + template + static void listAccept(std::vector> const& _list, ASTConstVisitor& _visitor) + { + for (ASTPointer const& element: _list) + element->accept(_visitor); + } /// Returns the source code location of this node. Location const& getLocation() const { return m_location; } /// Creates a @ref TypeError exception and decorates it with the location of the node and /// the given description - TypeError createTypeError(std::string const& _description); + TypeError createTypeError(std::string const& _description) const; ///@{ ///@name equality operators @@ -79,6 +87,44 @@ private: Location m_location; }; +/** + * Source unit containing import directives and contract definitions. + */ +class SourceUnit: public ASTNode +{ +public: + SourceUnit(Location const& _location, std::vector> const& _nodes): + ASTNode(_location), m_nodes(_nodes) {} + + virtual void accept(ASTVisitor& _visitor) override; + virtual void accept(ASTConstVisitor& _visitor) const override; + + std::vector> getNodes() const { return m_nodes; } + +private: + std::vector> m_nodes; +}; + +/** + * Import directive for referencing other files / source objects. + * Example: import "abc.sol" + * Source objects are identified by a string which can be a file name but does not have to be. + */ +class ImportDirective: public ASTNode +{ +public: + ImportDirective(Location const& _location, ASTPointer const& _identifier): + ASTNode(_location), m_identifier(_identifier) {} + + virtual void accept(ASTVisitor& _visitor) override; + virtual void accept(ASTConstVisitor& _visitor) const override; + + ASTString const& getIdentifier() const { return *m_identifier; } + +private: + ASTPointer m_identifier; +}; + /** * Abstract AST class for a declaration (contract, function, struct, variable). */ @@ -86,13 +132,18 @@ class Declaration: public ASTNode { public: Declaration(Location const& _location, ASTPointer const& _name): - ASTNode(_location), m_name(_name) {} + ASTNode(_location), m_name(_name), m_scope(nullptr) {} - /// Returns the declared name. + /// @returns the declared name. ASTString const& getName() const { return *m_name; } + /// @returns the scope this declaration resides in. Can be nullptr if it is the global scope. + /// Available only after name and type resolution step. + Declaration const* getScope() const { return m_scope; } + void setScope(Declaration const* _scope) { m_scope = _scope; } private: ASTPointer m_name; + Declaration const* m_scope; }; /** @@ -105,25 +156,36 @@ class ContractDefinition: public Declaration public: ContractDefinition(Location const& _location, ASTPointer const& _name, + ASTPointer const& _documentation, std::vector> const& _definedStructs, std::vector> const& _stateVariables, std::vector> const& _definedFunctions): Declaration(_location, _name), m_definedStructs(_definedStructs), m_stateVariables(_stateVariables), - m_definedFunctions(_definedFunctions) + m_definedFunctions(_definedFunctions), + m_documentation(_documentation) {} virtual void accept(ASTVisitor& _visitor) override; + virtual void accept(ASTConstVisitor& _visitor) const override; std::vector> const& getDefinedStructs() const { return m_definedStructs; } std::vector> const& getStateVariables() const { return m_stateVariables; } std::vector> const& getDefinedFunctions() const { return m_definedFunctions; } + /// @return A shared pointer of an ASTString. + /// Can contain a nullptr in which case indicates absence of documentation + ASTPointer const& getDocumentation() const { return m_documentation; } + + /// Returns the functions that make up the calling interface in the intended order. + std::vector getInterfaceFunctions() const; + private: std::vector> m_definedStructs; std::vector> m_stateVariables; std::vector> m_definedFunctions; + ASTPointer m_documentation; }; class StructDefinition: public Declaration @@ -134,17 +196,25 @@ public: std::vector> const& _members): Declaration(_location, _name), m_members(_members) {} virtual void accept(ASTVisitor& _visitor) override; + virtual void accept(ASTConstVisitor& _visitor) const override; std::vector> const& getMembers() const { return m_members; } + /// Checks that the members do not include any recursive structs and have valid types + /// (e.g. no functions). + void checkValidityOfMembers() const; + private: + void checkMemberTypes() const; + void checkRecursion() const; + std::vector> m_members; }; /** * Parameter list, used as function parameter list and return list. * None of the parameters is allowed to contain mappings (not even recursively - * inside structs), but (@todo) this is not yet enforced. + * inside structs). */ class ParameterList: public ASTNode { @@ -153,6 +223,7 @@ public: std::vector> const& _parameters): ASTNode(_location), m_parameters(_parameters) {} virtual void accept(ASTVisitor& _visitor) override; + virtual void accept(ASTConstVisitor& _visitor) const override; std::vector> const& getParameters() const { return m_parameters; } @@ -163,33 +234,48 @@ private: class FunctionDefinition: public Declaration { public: - FunctionDefinition(Location const& _location, ASTPointer const& _name, bool _isPublic, - ASTPointer const& _parameters, - bool _isDeclaredConst, - ASTPointer const& _returnParameters, - ASTPointer const& _body): - Declaration(_location, _name), m_isPublic(_isPublic), m_parameters(_parameters), - m_isDeclaredConst(_isDeclaredConst), m_returnParameters(_returnParameters), - m_body(_body) {} + FunctionDefinition(Location const& _location, ASTPointer const& _name, + bool _isPublic, + ASTPointer const& _documentation, + ASTPointer const& _parameters, + bool _isDeclaredConst, + ASTPointer const& _returnParameters, + ASTPointer const& _body): + Declaration(_location, _name), m_isPublic(_isPublic), + m_parameters(_parameters), + m_isDeclaredConst(_isDeclaredConst), + m_returnParameters(_returnParameters), + m_body(_body), + m_documentation(_documentation) + {} + virtual void accept(ASTVisitor& _visitor) override; + virtual void accept(ASTConstVisitor& _visitor) const override; bool isPublic() const { return m_isPublic; } bool isDeclaredConst() const { return m_isDeclaredConst; } std::vector> const& getParameters() const { return m_parameters->getParameters(); } - ParameterList& getParameterList() { return *m_parameters; } + ParameterList const& getParameterList() const { return *m_parameters; } std::vector> const& getReturnParameters() const { return m_returnParameters->getParameters(); } ASTPointer const& getReturnParameterList() const { return m_returnParameters; } - Block& getBody() { return *m_body; } + Block const& getBody() const { return *m_body; } + /// @return A shared pointer of an ASTString. + /// Can contain a nullptr in which case indicates absence of documentation + ASTPointer const& getDocumentation() const { return m_documentation; } void addLocalVariable(VariableDeclaration const& _localVariable) { m_localVariables.push_back(&_localVariable); } std::vector const& getLocalVariables() const { return m_localVariables; } + /// Checks that all parameters have allowed types and calls checkTypeRequirements on the body. + void checkTypeRequirements(); + private: bool m_isPublic; ASTPointer m_parameters; bool m_isDeclaredConst; ASTPointer m_returnParameters; ASTPointer m_body; + ASTPointer m_documentation; std::vector m_localVariables; }; @@ -205,21 +291,43 @@ public: ASTPointer const& _name): Declaration(_location, _name), m_typeName(_type) {} virtual void accept(ASTVisitor& _visitor) override; + virtual void accept(ASTConstVisitor& _visitor) const override; - bool isTypeGivenExplicitly() const { return bool(m_typeName); } - TypeName* getTypeName() const { return m_typeName.get(); } + TypeName const* getTypeName() const { return m_typeName.get(); } /// Returns the declared or inferred type. Can be an empty pointer if no type was explicitly /// declared and there is no assignment to the variable that fixes the type. std::shared_ptr const& getType() const { return m_type; } void setType(std::shared_ptr const& _type) { m_type = _type; } + bool isLocalVariable() const { return !!dynamic_cast(getScope()); } + private: ASTPointer m_typeName; ///< can be empty ("var") std::shared_ptr m_type; ///< derived type, initially empty }; +/** + * Pseudo AST node that is used as declaration for "this", "msg", "tx", "block" and the global + * functions when such an identifier is encountered. Will never have a valid location in the source code. + */ +class MagicVariableDeclaration: public Declaration +{ +public: + MagicVariableDeclaration(ASTString const& _name, std::shared_ptr const& _type): + Declaration(Location(), std::make_shared(_name)), m_type(_type) {} + virtual void accept(ASTVisitor&) override { BOOST_THROW_EXCEPTION(InternalCompilerError() + << errinfo_comment("MagicVariableDeclaration used inside real AST.")); } + virtual void accept(ASTConstVisitor&) const override { BOOST_THROW_EXCEPTION(InternalCompilerError() + << errinfo_comment("MagicVariableDeclaration used inside real AST.")); } + + std::shared_ptr const& getType() const { return m_type; } + +private: + std::shared_ptr m_type; +}; + /// Types /// @{ @@ -231,10 +339,12 @@ class TypeName: public ASTNode public: explicit TypeName(Location const& _location): ASTNode(_location) {} virtual void accept(ASTVisitor& _visitor) override; + virtual void accept(ASTConstVisitor& _visitor) const override; /// Retrieve the element of the type hierarchy this node refers to. Can return an empty shared /// pointer until the types have been resolved using the @ref NameAndTypeResolver. - virtual std::shared_ptr toType() = 0; + /// If it returns an empty shared pointer after that, this indicates that the type was not found. + virtual std::shared_ptr toType() const = 0; }; /** @@ -250,7 +360,8 @@ public: if (asserts(Token::isElementaryTypeName(_type))) BOOST_THROW_EXCEPTION(InternalCompilerError()); } virtual void accept(ASTVisitor& _visitor) override; - virtual std::shared_ptr toType() override { return Type::fromElementaryTypeName(m_type); } + virtual void accept(ASTConstVisitor& _visitor) const override; + virtual std::shared_ptr toType() const override { return Type::fromElementaryTypeName(m_type); } Token::Value getTypeName() const { return m_type; } @@ -259,25 +370,25 @@ private: }; /** - * Name referring to a user-defined type (i.e. a struct). - * @todo some changes are necessary if this is also used to refer to contract types later + * Name referring to a user-defined type (i.e. a struct, contract, etc.). */ class UserDefinedTypeName: public TypeName { public: UserDefinedTypeName(Location const& _location, ASTPointer const& _name): - TypeName(_location), m_name(_name) {} + TypeName(_location), m_name(_name), m_referencedDeclaration(nullptr) {} virtual void accept(ASTVisitor& _visitor) override; - virtual std::shared_ptr toType() override { return Type::fromUserDefinedTypeName(*this); } + virtual void accept(ASTConstVisitor& _visitor) const override; + virtual std::shared_ptr toType() const override { return Type::fromUserDefinedTypeName(*this); } ASTString const& getName() const { return *m_name; } - void setReferencedStruct(StructDefinition& _referencedStruct) { m_referencedStruct = &_referencedStruct; } - StructDefinition const* getReferencedStruct() const { return m_referencedStruct; } + void setReferencedDeclaration(Declaration const& _referencedDeclaration) { m_referencedDeclaration = &_referencedDeclaration; } + Declaration const* getReferencedDeclaration() const { return m_referencedDeclaration; } private: ASTPointer m_name; - StructDefinition* m_referencedStruct; + Declaration const* m_referencedDeclaration; }; /** @@ -290,7 +401,11 @@ public: ASTPointer const& _valueType): TypeName(_location), m_keyType(_keyType), m_valueType(_valueType) {} virtual void accept(ASTVisitor& _visitor) override; - virtual std::shared_ptr toType() override { return Type::fromMapping(*this); } + virtual void accept(ASTConstVisitor& _visitor) const override; + virtual std::shared_ptr toType() const override { return Type::fromMapping(*this); } + + ElementaryTypeName const& getKeyType() const { return *m_keyType; } + TypeName const& getValueType() const { return *m_valueType; } private: ASTPointer m_keyType; @@ -310,7 +425,6 @@ class Statement: public ASTNode { public: explicit Statement(Location const& _location): ASTNode(_location) {} - virtual void accept(ASTVisitor& _visitor) override; /// Check all type requirements, throws exception if some requirement is not met. /// This includes checking that operators are applicable to their arguments but also that @@ -327,6 +441,7 @@ public: Block(Location const& _location, std::vector> const& _statements): Statement(_location), m_statements(_statements) {} virtual void accept(ASTVisitor& _visitor) override; + virtual void accept(ASTConstVisitor& _visitor) const override; virtual void checkTypeRequirements() override; @@ -346,12 +461,13 @@ public: Statement(_location), m_condition(_condition), m_trueBody(_trueBody), m_falseBody(_falseBody) {} virtual void accept(ASTVisitor& _visitor) override; + virtual void accept(ASTConstVisitor& _visitor) const override; virtual void checkTypeRequirements() override; - Expression& getCondition() const { return *m_condition; } - Statement& getTrueStatement() const { return *m_trueBody; } + Expression const& getCondition() const { return *m_condition; } + Statement const& getTrueStatement() const { return *m_trueBody; } /// @returns the "else" part of the if statement or nullptr if there is no "else" part. - Statement* getFalseStatement() const { return m_falseBody.get(); } + Statement const* getFalseStatement() const { return m_falseBody.get(); } private: ASTPointer m_condition; @@ -360,14 +476,12 @@ private: }; /** - * Statement in which a break statement is legal. - * @todo actually check this requirement. + * Statement in which a break statement is legal (abstract class). */ class BreakableStatement: public Statement { public: BreakableStatement(Location const& _location): Statement(_location) {} - virtual void accept(ASTVisitor& _visitor) override; }; class WhileStatement: public BreakableStatement @@ -377,10 +491,11 @@ public: ASTPointer const& _body): BreakableStatement(_location), m_condition(_condition), m_body(_body) {} virtual void accept(ASTVisitor& _visitor) override; + virtual void accept(ASTConstVisitor& _visitor) const override; virtual void checkTypeRequirements() override; - Expression& getCondition() const { return *m_condition; } - Statement& getBody() const { return *m_body; } + Expression const& getCondition() const { return *m_condition; } + Statement const& getBody() const { return *m_body; } private: ASTPointer m_condition; @@ -392,6 +507,7 @@ class Continue: public Statement public: Continue(Location const& _location): Statement(_location) {} virtual void accept(ASTVisitor& _visitor) override; + virtual void accept(ASTConstVisitor& _visitor) const override; virtual void checkTypeRequirements() override {} }; @@ -400,6 +516,7 @@ class Break: public Statement public: Break(Location const& _location): Statement(_location) {} virtual void accept(ASTVisitor& _visitor) override; + virtual void accept(ASTConstVisitor& _visitor) const override; virtual void checkTypeRequirements() override {} }; @@ -407,8 +524,9 @@ class Return: public Statement { public: Return(Location const& _location, ASTPointer _expression): - Statement(_location), m_expression(_expression) {} + Statement(_location), m_expression(_expression), m_returnParameters(nullptr) {} virtual void accept(ASTVisitor& _visitor) override; + virtual void accept(ASTConstVisitor& _visitor) const override; virtual void checkTypeRequirements() override; void setFunctionReturnParameters(ParameterList& _parameters) { m_returnParameters = &_parameters; } @@ -418,7 +536,7 @@ public: BOOST_THROW_EXCEPTION(InternalCompilerError()); return *m_returnParameters; } - Expression* getExpression() const { return m_expression.get(); } + Expression const* getExpression() const { return m_expression.get(); } private: ASTPointer m_expression; ///< value to return, optional @@ -439,10 +557,11 @@ public: ASTPointer _value): Statement(_location), m_variable(_variable), m_value(_value) {} virtual void accept(ASTVisitor& _visitor) override; + virtual void accept(ASTConstVisitor& _visitor) const override; virtual void checkTypeRequirements() override; VariableDeclaration const& getDeclaration() const { return *m_variable; } - Expression* getExpression() const { return m_value.get(); } + Expression const* getExpression() const { return m_value.get(); } private: ASTPointer m_variable; @@ -458,9 +577,10 @@ public: ExpressionStatement(Location const& _location, ASTPointer _expression): Statement(_location), m_expression(_expression) {} virtual void accept(ASTVisitor& _visitor) override; + virtual void accept(ASTConstVisitor& _visitor) const override; virtual void checkTypeRequirements() override; - Expression& getExpression() const { return *m_expression; } + Expression const& getExpression() const { return *m_expression; } private: ASTPointer m_expression; @@ -478,23 +598,35 @@ private: */ class Expression: public ASTNode { +protected: + enum class LValueType { NONE, LOCAL, STORAGE }; + public: - Expression(Location const& _location): ASTNode(_location), m_isLvalue(false) {} + Expression(Location const& _location): ASTNode(_location), m_lvalue(LValueType::NONE), m_lvalueRequested(false) {} virtual void checkTypeRequirements() = 0; std::shared_ptr const& getType() const { return m_type; } - bool isLvalue() const { return m_isLvalue; } + bool isLValue() const { return m_lvalue != LValueType::NONE; } + bool isLocalLValue() const { return m_lvalue == LValueType::LOCAL; } /// Helper function, infer the type via @ref checkTypeRequirements and then check that it /// is implicitly convertible to @a _expectedType. If not, throw exception. void expectType(Type const& _expectedType); + /// Checks that this expression is an lvalue and also registers that an address and + /// not a value is generated during compilation. Can be called after checkTypeRequirements() + /// by an enclosing expression. + void requireLValue(); + /// Returns true if @a requireLValue was previously called on this expression. + bool lvalueRequested() const { return m_lvalueRequested; } protected: //! Inferred type of the expression, only filled after a call to checkTypeRequirements(). std::shared_ptr m_type; - //! Whether or not this expression is an lvalue, i.e. something that can be assigned to. - //! This is set during calls to @a checkTypeRequirements() - bool m_isLvalue; + //! If this expression is an lvalue (i.e. something that can be assigned to) and is stored + //! locally or in storage. This is set during calls to @a checkTypeRequirements() + LValueType m_lvalue; + //! Whether the outer expression requested the address (true) or the value (false) of this expression. + bool m_lvalueRequested; }; /// Assignment, can also be a compound assignment. @@ -510,11 +642,12 @@ public: if (asserts(Token::isAssignmentOp(_assignmentOperator))) BOOST_THROW_EXCEPTION(InternalCompilerError()); } virtual void accept(ASTVisitor& _visitor) override; + virtual void accept(ASTConstVisitor& _visitor) const override; virtual void checkTypeRequirements() override; - Expression& getLeftHandSide() const { return *m_leftHandSide; } + Expression const& getLeftHandSide() const { return *m_leftHandSide; } Token::Value getAssignmentOperator() const { return m_assigmentOperator; } - Expression& getRightHandSide() const { return *m_rightHandSide; } + Expression const& getRightHandSide() const { return *m_rightHandSide; } private: ASTPointer m_leftHandSide; @@ -537,10 +670,12 @@ public: if (asserts(Token::isUnaryOp(_operator))) BOOST_THROW_EXCEPTION(InternalCompilerError()); } virtual void accept(ASTVisitor& _visitor) override; + virtual void accept(ASTConstVisitor& _visitor) const override; virtual void checkTypeRequirements() override; Token::Value getOperator() const { return m_operator; } bool isPrefixOperation() const { return m_isPrefix; } + Expression const& getSubExpression() const { return *m_subExpression; } private: Token::Value m_operator; @@ -562,10 +697,11 @@ public: if (asserts(Token::isBinaryOp(_operator) || Token::isCompareOp(_operator))) BOOST_THROW_EXCEPTION(InternalCompilerError()); } virtual void accept(ASTVisitor& _visitor) override; + virtual void accept(ASTConstVisitor& _visitor) const override; virtual void checkTypeRequirements() override; - Expression& getLeftExpression() const { return *m_left; } - Expression& getRightExpression() const { return *m_right; } + Expression const& getLeftExpression() const { return *m_left; } + Expression const& getRightExpression() const { return *m_right; } Token::Value getOperator() const { return m_operator; } Type const& getCommonType() const { return *m_commonType; } @@ -589,10 +725,11 @@ public: std::vector> const& _arguments): Expression(_location), m_expression(_expression), m_arguments(_arguments) {} virtual void accept(ASTVisitor& _visitor) override; + virtual void accept(ASTConstVisitor& _visitor) const override; virtual void checkTypeRequirements() override; - Expression& getExpression() const { return *m_expression; } - std::vector> const& getArguments() const { return m_arguments; } + Expression const& getExpression() const { return *m_expression; } + std::vector> getArguments() const { return {m_arguments.begin(), m_arguments.end()}; } /// Returns true if this is not an actual function call, but an explicit type conversion /// or constructor call. @@ -613,6 +750,8 @@ public: ASTPointer const& _memberName): Expression(_location), m_expression(_expression), m_memberName(_memberName) {} virtual void accept(ASTVisitor& _visitor) override; + virtual void accept(ASTConstVisitor& _visitor) const override; + Expression const& getExpression() const { return *m_expression; } ASTString const& getMemberName() const { return *m_memberName; } virtual void checkTypeRequirements() override; @@ -631,8 +770,12 @@ public: ASTPointer const& _index): Expression(_location), m_base(_base), m_index(_index) {} virtual void accept(ASTVisitor& _visitor) override; + virtual void accept(ASTConstVisitor& _visitor) const override; virtual void checkTypeRequirements() override; + Expression const& getBaseExpression() const { return *m_base; } + Expression const& getIndexExpression() const { return *m_index; } + private: ASTPointer m_base; ASTPointer m_index; @@ -655,20 +798,21 @@ class Identifier: public PrimaryExpression { public: Identifier(Location const& _location, ASTPointer const& _name): - PrimaryExpression(_location), m_name(_name) {} + PrimaryExpression(_location), m_name(_name), m_referencedDeclaration(nullptr) {} virtual void accept(ASTVisitor& _visitor) override; + virtual void accept(ASTConstVisitor& _visitor) const override; virtual void checkTypeRequirements() override; ASTString const& getName() const { return *m_name; } - void setReferencedDeclaration(Declaration& _referencedDeclaration) { m_referencedDeclaration = &_referencedDeclaration; } - Declaration* getReferencedDeclaration() { return m_referencedDeclaration; } + void setReferencedDeclaration(Declaration const& _referencedDeclaration) { m_referencedDeclaration = &_referencedDeclaration; } + Declaration const* getReferencedDeclaration() const { return m_referencedDeclaration; } private: ASTPointer m_name; /// Declaration the name refers to. - Declaration* m_referencedDeclaration; + Declaration const* m_referencedDeclaration; }; /** @@ -685,6 +829,7 @@ public: if (asserts(Token::isElementaryTypeName(_typeToken))) BOOST_THROW_EXCEPTION(InternalCompilerError()); } virtual void accept(ASTVisitor& _visitor) override; + virtual void accept(ASTConstVisitor& _visitor) const override; virtual void checkTypeRequirements() override; Token::Value getTypeToken() const { return m_typeToken; } @@ -702,6 +847,7 @@ public: Literal(Location const& _location, Token::Value _token, ASTPointer const& _value): PrimaryExpression(_location), m_token(_token), m_value(_value) {} virtual void accept(ASTVisitor& _visitor) override; + virtual void accept(ASTConstVisitor& _visitor) const override; virtual void checkTypeRequirements() override; Token::Value getToken() const { return m_token; } diff --git a/libsolidity/ASTForward.h b/libsolidity/ASTForward.h index 2b0bd8869..8b4bac1ce 100644 --- a/libsolidity/ASTForward.h +++ b/libsolidity/ASTForward.h @@ -34,12 +34,15 @@ namespace solidity { class ASTNode; +class SourceUnit; +class ImportDirective; class Declaration; class ContractDefinition; class StructDefinition; class ParameterList; class FunctionDefinition; class VariableDeclaration; +class MagicVariableDeclaration; class TypeName; class ElementaryTypeName; class UserDefinedTypeName; diff --git a/libsolidity/ASTPrinter.cpp b/libsolidity/ASTPrinter.cpp index eb9d92f08..eddb51340 100644 --- a/libsolidity/ASTPrinter.cpp +++ b/libsolidity/ASTPrinter.cpp @@ -30,8 +30,8 @@ namespace dev namespace solidity { -ASTPrinter::ASTPrinter(ASTPointer const& _ast, string const& _source): - m_indentation(0), m_source(_source), m_ast(_ast) +ASTPrinter::ASTPrinter(ASTNode const& _ast, string const& _source): + m_indentation(0), m_source(_source), m_ast(&_ast) { } @@ -43,28 +43,35 @@ void ASTPrinter::print(ostream& _stream) } -bool ASTPrinter::visit(ContractDefinition& _node) +bool ASTPrinter::visit(ImportDirective const& _node) +{ + writeLine("ImportDirective \"" + _node.getIdentifier() + "\""); + printSourcePart(_node); + return goDeeper(); +} + +bool ASTPrinter::visit(ContractDefinition const& _node) { writeLine("ContractDefinition \"" + _node.getName() + "\""); printSourcePart(_node); return goDeeper(); } -bool ASTPrinter::visit(StructDefinition& _node) +bool ASTPrinter::visit(StructDefinition const& _node) { writeLine("StructDefinition \"" + _node.getName() + "\""); printSourcePart(_node); return goDeeper(); } -bool ASTPrinter::visit(ParameterList& _node) +bool ASTPrinter::visit(ParameterList const& _node) { writeLine("ParameterList"); printSourcePart(_node); return goDeeper(); } -bool ASTPrinter::visit(FunctionDefinition& _node) +bool ASTPrinter::visit(FunctionDefinition const& _node) { writeLine("FunctionDefinition \"" + _node.getName() + "\"" + (_node.isPublic() ? " - public" : "") + @@ -73,112 +80,112 @@ bool ASTPrinter::visit(FunctionDefinition& _node) return goDeeper(); } -bool ASTPrinter::visit(VariableDeclaration& _node) +bool ASTPrinter::visit(VariableDeclaration const& _node) { writeLine("VariableDeclaration \"" + _node.getName() + "\""); printSourcePart(_node); return goDeeper(); } -bool ASTPrinter::visit(TypeName& _node) +bool ASTPrinter::visit(TypeName const& _node) { writeLine("TypeName"); printSourcePart(_node); return goDeeper(); } -bool ASTPrinter::visit(ElementaryTypeName& _node) +bool ASTPrinter::visit(ElementaryTypeName const& _node) { writeLine(string("ElementaryTypeName ") + Token::toString(_node.getTypeName())); printSourcePart(_node); return goDeeper(); } -bool ASTPrinter::visit(UserDefinedTypeName& _node) +bool ASTPrinter::visit(UserDefinedTypeName const& _node) { writeLine("UserDefinedTypeName \"" + _node.getName() + "\""); printSourcePart(_node); return goDeeper(); } -bool ASTPrinter::visit(Mapping& _node) +bool ASTPrinter::visit(Mapping const& _node) { writeLine("Mapping"); printSourcePart(_node); return goDeeper(); } -bool ASTPrinter::visit(Statement& _node) +bool ASTPrinter::visit(Statement const& _node) { writeLine("Statement"); printSourcePart(_node); return goDeeper(); } -bool ASTPrinter::visit(Block& _node) +bool ASTPrinter::visit(Block const& _node) { writeLine("Block"); printSourcePart(_node); return goDeeper(); } -bool ASTPrinter::visit(IfStatement& _node) +bool ASTPrinter::visit(IfStatement const& _node) { writeLine("IfStatement"); printSourcePart(_node); return goDeeper(); } -bool ASTPrinter::visit(BreakableStatement& _node) +bool ASTPrinter::visit(BreakableStatement const& _node) { writeLine("BreakableStatement"); printSourcePart(_node); return goDeeper(); } -bool ASTPrinter::visit(WhileStatement& _node) +bool ASTPrinter::visit(WhileStatement const& _node) { writeLine("WhileStatement"); printSourcePart(_node); return goDeeper(); } -bool ASTPrinter::visit(Continue& _node) +bool ASTPrinter::visit(Continue const& _node) { writeLine("Continue"); printSourcePart(_node); return goDeeper(); } -bool ASTPrinter::visit(Break& _node) +bool ASTPrinter::visit(Break const& _node) { writeLine("Break"); printSourcePart(_node); return goDeeper(); } -bool ASTPrinter::visit(Return& _node) +bool ASTPrinter::visit(Return const& _node) { writeLine("Return"); printSourcePart(_node); return goDeeper(); } -bool ASTPrinter::visit(VariableDefinition& _node) +bool ASTPrinter::visit(VariableDefinition const& _node) { writeLine("VariableDefinition"); printSourcePart(_node); return goDeeper(); } -bool ASTPrinter::visit(ExpressionStatement& _node) +bool ASTPrinter::visit(ExpressionStatement const& _node) { writeLine("ExpressionStatement"); printSourcePart(_node); return goDeeper(); } -bool ASTPrinter::visit(Expression& _node) +bool ASTPrinter::visit(Expression const& _node) { writeLine("Expression"); printType(_node); @@ -186,7 +193,7 @@ bool ASTPrinter::visit(Expression& _node) return goDeeper(); } -bool ASTPrinter::visit(Assignment& _node) +bool ASTPrinter::visit(Assignment const& _node) { writeLine(string("Assignment using operator ") + Token::toString(_node.getAssignmentOperator())); printType(_node); @@ -194,7 +201,7 @@ bool ASTPrinter::visit(Assignment& _node) return goDeeper(); } -bool ASTPrinter::visit(UnaryOperation& _node) +bool ASTPrinter::visit(UnaryOperation const& _node) { writeLine(string("UnaryOperation (") + (_node.isPrefixOperation() ? "prefix" : "postfix") + ") " + Token::toString(_node.getOperator())); @@ -203,7 +210,7 @@ bool ASTPrinter::visit(UnaryOperation& _node) return goDeeper(); } -bool ASTPrinter::visit(BinaryOperation& _node) +bool ASTPrinter::visit(BinaryOperation const& _node) { writeLine(string("BinaryOperation using operator ") + Token::toString(_node.getOperator())); printType(_node); @@ -211,7 +218,7 @@ bool ASTPrinter::visit(BinaryOperation& _node) return goDeeper(); } -bool ASTPrinter::visit(FunctionCall& _node) +bool ASTPrinter::visit(FunctionCall const& _node) { writeLine("FunctionCall"); printType(_node); @@ -219,7 +226,7 @@ bool ASTPrinter::visit(FunctionCall& _node) return goDeeper(); } -bool ASTPrinter::visit(MemberAccess& _node) +bool ASTPrinter::visit(MemberAccess const& _node) { writeLine("MemberAccess to member " + _node.getMemberName()); printType(_node); @@ -227,7 +234,7 @@ bool ASTPrinter::visit(MemberAccess& _node) return goDeeper(); } -bool ASTPrinter::visit(IndexAccess& _node) +bool ASTPrinter::visit(IndexAccess const& _node) { writeLine("IndexAccess"); printType(_node); @@ -235,7 +242,7 @@ bool ASTPrinter::visit(IndexAccess& _node) return goDeeper(); } -bool ASTPrinter::visit(PrimaryExpression& _node) +bool ASTPrinter::visit(PrimaryExpression const& _node) { writeLine("PrimaryExpression"); printType(_node); @@ -243,7 +250,7 @@ bool ASTPrinter::visit(PrimaryExpression& _node) return goDeeper(); } -bool ASTPrinter::visit(Identifier& _node) +bool ASTPrinter::visit(Identifier const& _node) { writeLine(string("Identifier ") + _node.getName()); printType(_node); @@ -251,7 +258,7 @@ bool ASTPrinter::visit(Identifier& _node) return goDeeper(); } -bool ASTPrinter::visit(ElementaryTypeNameExpression& _node) +bool ASTPrinter::visit(ElementaryTypeNameExpression const& _node) { writeLine(string("ElementaryTypeNameExpression ") + Token::toString(_node.getTypeToken())); printType(_node); @@ -259,7 +266,7 @@ bool ASTPrinter::visit(ElementaryTypeNameExpression& _node) return goDeeper(); } -bool ASTPrinter::visit(Literal& _node) +bool ASTPrinter::visit(Literal const& _node) { char const* tokenString = Token::toString(_node.getToken()); if (!tokenString) @@ -270,157 +277,157 @@ bool ASTPrinter::visit(Literal& _node) return goDeeper(); } -void ASTPrinter::endVisit(ASTNode&) +void ASTPrinter::endVisit(ImportDirective const&) { m_indentation--; } -void ASTPrinter::endVisit(ContractDefinition&) +void ASTPrinter::endVisit(ContractDefinition const&) { m_indentation--; } -void ASTPrinter::endVisit(StructDefinition&) +void ASTPrinter::endVisit(StructDefinition const&) { m_indentation--; } -void ASTPrinter::endVisit(ParameterList&) +void ASTPrinter::endVisit(ParameterList const&) { m_indentation--; } -void ASTPrinter::endVisit(FunctionDefinition&) +void ASTPrinter::endVisit(FunctionDefinition const&) { m_indentation--; } -void ASTPrinter::endVisit(VariableDeclaration&) +void ASTPrinter::endVisit(VariableDeclaration const&) { m_indentation--; } -void ASTPrinter::endVisit(TypeName&) +void ASTPrinter::endVisit(TypeName const&) { m_indentation--; } -void ASTPrinter::endVisit(ElementaryTypeName&) +void ASTPrinter::endVisit(ElementaryTypeName const&) { m_indentation--; } -void ASTPrinter::endVisit(UserDefinedTypeName&) +void ASTPrinter::endVisit(UserDefinedTypeName const&) { m_indentation--; } -void ASTPrinter::endVisit(Mapping&) +void ASTPrinter::endVisit(Mapping const&) { m_indentation--; } -void ASTPrinter::endVisit(Statement&) +void ASTPrinter::endVisit(Statement const&) { m_indentation--; } -void ASTPrinter::endVisit(Block&) +void ASTPrinter::endVisit(Block const&) { m_indentation--; } -void ASTPrinter::endVisit(IfStatement&) +void ASTPrinter::endVisit(IfStatement const&) { m_indentation--; } -void ASTPrinter::endVisit(BreakableStatement&) +void ASTPrinter::endVisit(BreakableStatement const&) { m_indentation--; } -void ASTPrinter::endVisit(WhileStatement&) +void ASTPrinter::endVisit(WhileStatement const&) { m_indentation--; } -void ASTPrinter::endVisit(Continue&) +void ASTPrinter::endVisit(Continue const&) { m_indentation--; } -void ASTPrinter::endVisit(Break&) +void ASTPrinter::endVisit(Break const&) { m_indentation--; } -void ASTPrinter::endVisit(Return&) +void ASTPrinter::endVisit(Return const&) { m_indentation--; } -void ASTPrinter::endVisit(VariableDefinition&) +void ASTPrinter::endVisit(VariableDefinition const&) { m_indentation--; } -void ASTPrinter::endVisit(ExpressionStatement&) +void ASTPrinter::endVisit(ExpressionStatement const&) { m_indentation--; } -void ASTPrinter::endVisit(Expression&) +void ASTPrinter::endVisit(Expression const&) { m_indentation--; } -void ASTPrinter::endVisit(Assignment&) +void ASTPrinter::endVisit(Assignment const&) { m_indentation--; } -void ASTPrinter::endVisit(UnaryOperation&) +void ASTPrinter::endVisit(UnaryOperation const&) { m_indentation--; } -void ASTPrinter::endVisit(BinaryOperation&) +void ASTPrinter::endVisit(BinaryOperation const&) { m_indentation--; } -void ASTPrinter::endVisit(FunctionCall&) +void ASTPrinter::endVisit(FunctionCall const&) { m_indentation--; } -void ASTPrinter::endVisit(MemberAccess&) +void ASTPrinter::endVisit(MemberAccess const&) { m_indentation--; } -void ASTPrinter::endVisit(IndexAccess&) +void ASTPrinter::endVisit(IndexAccess const&) { m_indentation--; } -void ASTPrinter::endVisit(PrimaryExpression&) +void ASTPrinter::endVisit(PrimaryExpression const&) { m_indentation--; } -void ASTPrinter::endVisit(Identifier&) +void ASTPrinter::endVisit(Identifier const&) { m_indentation--; } -void ASTPrinter::endVisit(ElementaryTypeNameExpression&) +void ASTPrinter::endVisit(ElementaryTypeNameExpression const&) { m_indentation--; } -void ASTPrinter::endVisit(Literal&) +void ASTPrinter::endVisit(Literal const&) { m_indentation--; } @@ -430,8 +437,8 @@ void ASTPrinter::printSourcePart(ASTNode const& _node) if (!m_source.empty()) { Location const& location(_node.getLocation()); - *m_ostream << getIndentation() << " Source: |" - << m_source.substr(location.start, location.end - location.start) << "|" << endl; + *m_ostream << getIndentation() << " Source: " + << escaped(m_source.substr(location.start, location.end - location.start), false) << endl; } } diff --git a/libsolidity/ASTPrinter.h b/libsolidity/ASTPrinter.h index e87b2ba3b..5a9187154 100644 --- a/libsolidity/ASTPrinter.h +++ b/libsolidity/ASTPrinter.h @@ -33,77 +33,78 @@ namespace solidity /** * Pretty-printer for the abstract syntax tree (the "pretty" is arguable) for debugging purposes. */ -class ASTPrinter: public ASTVisitor +class ASTPrinter: public ASTConstVisitor { public: /// Create a printer for the given abstract syntax tree. If the source is specified, /// the corresponding parts of the source are printed with each node. - ASTPrinter(ASTPointer const& _ast, std::string const& _source = std::string()); + ASTPrinter(ASTNode const& _ast, std::string const& _source = std::string()); /// Output the string representation of the AST to _stream. void print(std::ostream& _stream); - bool visit(ContractDefinition& _node) override; - bool visit(StructDefinition& _node) override; - bool visit(ParameterList& _node) override; - bool visit(FunctionDefinition& _node) override; - bool visit(VariableDeclaration& _node) override; - bool visit(TypeName& _node) override; - bool visit(ElementaryTypeName& _node) override; - bool visit(UserDefinedTypeName& _node) override; - bool visit(Mapping& _node) override; - bool visit(Statement& _node) override; - bool visit(Block& _node) override; - bool visit(IfStatement& _node) override; - bool visit(BreakableStatement& _node) override; - bool visit(WhileStatement& _node) override; - bool visit(Continue& _node) override; - bool visit(Break& _node) override; - bool visit(Return& _node) override; - bool visit(VariableDefinition& _node) override; - bool visit(ExpressionStatement& _node) override; - bool visit(Expression& _node) override; - bool visit(Assignment& _node) override; - bool visit(UnaryOperation& _node) override; - bool visit(BinaryOperation& _node) override; - bool visit(FunctionCall& _node) override; - bool visit(MemberAccess& _node) override; - bool visit(IndexAccess& _node) override; - bool visit(PrimaryExpression& _node) override; - bool visit(Identifier& _node) override; - bool visit(ElementaryTypeNameExpression& _node) override; - bool visit(Literal& _node) override; + bool visit(ImportDirective const& _node) override; + bool visit(ContractDefinition const& _node) override; + bool visit(StructDefinition const& _node) override; + bool visit(ParameterList const& _node) override; + bool visit(FunctionDefinition const& _node) override; + bool visit(VariableDeclaration const& _node) override; + bool visit(TypeName const& _node) override; + bool visit(ElementaryTypeName const& _node) override; + bool visit(UserDefinedTypeName const& _node) override; + bool visit(Mapping const& _node) override; + bool visit(Statement const& _node) override; + bool visit(Block const& _node) override; + bool visit(IfStatement const& _node) override; + bool visit(BreakableStatement const& _node) override; + bool visit(WhileStatement const& _node) override; + bool visit(Continue const& _node) override; + bool visit(Break const& _node) override; + bool visit(Return const& _node) override; + bool visit(VariableDefinition const& _node) override; + bool visit(ExpressionStatement const& _node) override; + bool visit(Expression const& _node) override; + bool visit(Assignment const& _node) override; + bool visit(UnaryOperation const& _node) override; + bool visit(BinaryOperation const& _node) override; + bool visit(FunctionCall const& _node) override; + bool visit(MemberAccess const& _node) override; + bool visit(IndexAccess const& _node) override; + bool visit(PrimaryExpression const& _node) override; + bool visit(Identifier const& _node) override; + bool visit(ElementaryTypeNameExpression const& _node) override; + bool visit(Literal const& _node) override; - void endVisit(ASTNode& _node) override; - void endVisit(ContractDefinition&) override; - void endVisit(StructDefinition&) override; - void endVisit(ParameterList&) override; - void endVisit(FunctionDefinition&) override; - void endVisit(VariableDeclaration&) override; - void endVisit(TypeName&) override; - void endVisit(ElementaryTypeName&) override; - void endVisit(UserDefinedTypeName&) override; - void endVisit(Mapping&) override; - void endVisit(Statement&) override; - void endVisit(Block&) override; - void endVisit(IfStatement&) override; - void endVisit(BreakableStatement&) override; - void endVisit(WhileStatement&) override; - void endVisit(Continue&) override; - void endVisit(Break&) override; - void endVisit(Return&) override; - void endVisit(VariableDefinition&) override; - void endVisit(ExpressionStatement&) override; - void endVisit(Expression&) override; - void endVisit(Assignment&) override; - void endVisit(UnaryOperation&) override; - void endVisit(BinaryOperation&) override; - void endVisit(FunctionCall&) override; - void endVisit(MemberAccess&) override; - void endVisit(IndexAccess&) override; - void endVisit(PrimaryExpression&) override; - void endVisit(Identifier&) override; - void endVisit(ElementaryTypeNameExpression&) override; - void endVisit(Literal&) override; + void endVisit(ImportDirective const&) override; + void endVisit(ContractDefinition const&) override; + void endVisit(StructDefinition const&) override; + void endVisit(ParameterList const&) override; + void endVisit(FunctionDefinition const&) override; + void endVisit(VariableDeclaration const&) override; + void endVisit(TypeName const&) override; + void endVisit(ElementaryTypeName const&) override; + void endVisit(UserDefinedTypeName const&) override; + void endVisit(Mapping const&) override; + void endVisit(Statement const&) override; + void endVisit(Block const&) override; + void endVisit(IfStatement const&) override; + void endVisit(BreakableStatement const&) override; + void endVisit(WhileStatement const&) override; + void endVisit(Continue const&) override; + void endVisit(Break const&) override; + void endVisit(Return const&) override; + void endVisit(VariableDefinition const&) override; + void endVisit(ExpressionStatement const&) override; + void endVisit(Expression const&) override; + void endVisit(Assignment const&) override; + void endVisit(UnaryOperation const&) override; + void endVisit(BinaryOperation const&) override; + void endVisit(FunctionCall const&) override; + void endVisit(MemberAccess const&) override; + void endVisit(IndexAccess const&) override; + void endVisit(PrimaryExpression const&) override; + void endVisit(Identifier const&) override; + void endVisit(ElementaryTypeNameExpression const&) override; + void endVisit(Literal const&) override; private: void printSourcePart(ASTNode const& _node); @@ -114,7 +115,7 @@ private: int m_indentation; std::string m_source; - ASTPointer m_ast; + ASTNode const* m_ast; std::ostream* m_ostream; }; diff --git a/libsolidity/ASTVisitor.h b/libsolidity/ASTVisitor.h index 6e579f358..4e1a49458 100644 --- a/libsolidity/ASTVisitor.h +++ b/libsolidity/ASTVisitor.h @@ -42,6 +42,8 @@ class ASTVisitor { public: virtual bool visit(ASTNode&) { return true; } + virtual bool visit(SourceUnit&) { return true; } + virtual bool visit(ImportDirective&) { return true; } virtual bool visit(ContractDefinition&) { return true; } virtual bool visit(StructDefinition&) { return true; } virtual bool visit(ParameterList&) { return true; } @@ -74,6 +76,8 @@ public: virtual bool visit(Literal&) { return true; } virtual void endVisit(ASTNode&) { } + virtual void endVisit(SourceUnit&) { } + virtual void endVisit(ImportDirective&) { } virtual void endVisit(ContractDefinition&) { } virtual void endVisit(StructDefinition&) { } virtual void endVisit(ParameterList&) { } @@ -106,5 +110,77 @@ public: virtual void endVisit(Literal&) { } }; +class ASTConstVisitor +{ +public: + virtual bool visit(ASTNode const&) { return true; } + virtual bool visit(SourceUnit const&) { return true; } + virtual bool visit(ImportDirective const&) { return true; } + virtual bool visit(ContractDefinition const&) { return true; } + virtual bool visit(StructDefinition const&) { return true; } + virtual bool visit(ParameterList const&) { return true; } + virtual bool visit(FunctionDefinition const&) { return true; } + virtual bool visit(VariableDeclaration const&) { return true; } + virtual bool visit(TypeName const&) { return true; } + virtual bool visit(ElementaryTypeName const&) { return true; } + virtual bool visit(UserDefinedTypeName const&) { return true; } + virtual bool visit(Mapping const&) { return true; } + virtual bool visit(Statement const&) { return true; } + virtual bool visit(Block const&) { return true; } + virtual bool visit(IfStatement const&) { return true; } + virtual bool visit(BreakableStatement const&) { return true; } + virtual bool visit(WhileStatement const&) { return true; } + virtual bool visit(Continue const&) { return true; } + virtual bool visit(Break const&) { return true; } + virtual bool visit(Return const&) { return true; } + virtual bool visit(VariableDefinition const&) { return true; } + virtual bool visit(ExpressionStatement const&) { return true; } + virtual bool visit(Expression const&) { return true; } + virtual bool visit(Assignment const&) { return true; } + virtual bool visit(UnaryOperation const&) { return true; } + virtual bool visit(BinaryOperation const&) { return true; } + virtual bool visit(FunctionCall const&) { return true; } + virtual bool visit(MemberAccess const&) { return true; } + virtual bool visit(IndexAccess const&) { return true; } + virtual bool visit(PrimaryExpression const&) { return true; } + virtual bool visit(Identifier const&) { return true; } + virtual bool visit(ElementaryTypeNameExpression const&) { return true; } + virtual bool visit(Literal const&) { return true; } + + virtual void endVisit(ASTNode const&) { } + virtual void endVisit(SourceUnit const&) { } + virtual void endVisit(ImportDirective const&) { } + virtual void endVisit(ContractDefinition const&) { } + virtual void endVisit(StructDefinition const&) { } + virtual void endVisit(ParameterList const&) { } + virtual void endVisit(FunctionDefinition const&) { } + virtual void endVisit(VariableDeclaration const&) { } + virtual void endVisit(TypeName const&) { } + virtual void endVisit(ElementaryTypeName const&) { } + virtual void endVisit(UserDefinedTypeName const&) { } + virtual void endVisit(Mapping const&) { } + virtual void endVisit(Statement const&) { } + virtual void endVisit(Block const&) { } + virtual void endVisit(IfStatement const&) { } + virtual void endVisit(BreakableStatement const&) { } + virtual void endVisit(WhileStatement const&) { } + virtual void endVisit(Continue const&) { } + virtual void endVisit(Break const&) { } + virtual void endVisit(Return const&) { } + virtual void endVisit(VariableDefinition const&) { } + virtual void endVisit(ExpressionStatement const&) { } + virtual void endVisit(Expression const&) { } + virtual void endVisit(Assignment const&) { } + virtual void endVisit(UnaryOperation const&) { } + virtual void endVisit(BinaryOperation const&) { } + virtual void endVisit(FunctionCall const&) { } + virtual void endVisit(MemberAccess const&) { } + virtual void endVisit(IndexAccess const&) { } + virtual void endVisit(PrimaryExpression const&) { } + virtual void endVisit(Identifier const&) { } + virtual void endVisit(ElementaryTypeNameExpression const&) { } + virtual void endVisit(Literal const&) { } +}; + } } diff --git a/libsolidity/AST_accept.h b/libsolidity/AST_accept.h new file mode 100644 index 000000000..173273c6d --- /dev/null +++ b/libsolidity/AST_accept.h @@ -0,0 +1,493 @@ +/* + This file is part of cpp-ethereum. + + cpp-ethereum is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + cpp-ethereum is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with cpp-ethereum. If not, see . +*/ +/** + * @author Christian + * @date 2014 + * Implementation of the accept functions of AST nodes, included by AST.cpp to not clutter that + * file with these mechanical implementations. + */ + +#pragma once + +#include +#include + +namespace dev +{ +namespace solidity +{ + +void SourceUnit::accept(ASTVisitor& _visitor) +{ + if (_visitor.visit(*this)) + listAccept(m_nodes, _visitor); + _visitor.endVisit(*this); +} + +void SourceUnit::accept(ASTConstVisitor& _visitor) const +{ + if (_visitor.visit(*this)) + listAccept(m_nodes, _visitor); + _visitor.endVisit(*this); +} + +void ImportDirective::accept(ASTVisitor& _visitor) +{ + _visitor.visit(*this); + _visitor.endVisit(*this); +} + +void ImportDirective::accept(ASTConstVisitor& _visitor) const +{ + _visitor.visit(*this); + _visitor.endVisit(*this); +} + +void ContractDefinition::accept(ASTVisitor& _visitor) +{ + if (_visitor.visit(*this)) + { + listAccept(m_definedStructs, _visitor); + listAccept(m_stateVariables, _visitor); + listAccept(m_definedFunctions, _visitor); + } + _visitor.endVisit(*this); +} + +void ContractDefinition::accept(ASTConstVisitor& _visitor) const +{ + if (_visitor.visit(*this)) + { + listAccept(m_definedStructs, _visitor); + listAccept(m_stateVariables, _visitor); + listAccept(m_definedFunctions, _visitor); + } + _visitor.endVisit(*this); +} + +void StructDefinition::accept(ASTVisitor& _visitor) +{ + if (_visitor.visit(*this)) + listAccept(m_members, _visitor); + _visitor.endVisit(*this); +} + +void StructDefinition::accept(ASTConstVisitor& _visitor) const +{ + if (_visitor.visit(*this)) + listAccept(m_members, _visitor); + _visitor.endVisit(*this); +} + +void StructDefinition::checkValidityOfMembers() const +{ + checkMemberTypes(); + checkRecursion(); +} + +void ParameterList::accept(ASTVisitor& _visitor) +{ + if (_visitor.visit(*this)) + listAccept(m_parameters, _visitor); + _visitor.endVisit(*this); +} + +void ParameterList::accept(ASTConstVisitor& _visitor) const +{ + if (_visitor.visit(*this)) + listAccept(m_parameters, _visitor); + _visitor.endVisit(*this); +} + +void FunctionDefinition::accept(ASTVisitor& _visitor) +{ + if (_visitor.visit(*this)) + { + m_parameters->accept(_visitor); + if (m_returnParameters) + m_returnParameters->accept(_visitor); + m_body->accept(_visitor); + } + _visitor.endVisit(*this); +} + +void FunctionDefinition::accept(ASTConstVisitor& _visitor) const +{ + if (_visitor.visit(*this)) + { + m_parameters->accept(_visitor); + if (m_returnParameters) + m_returnParameters->accept(_visitor); + m_body->accept(_visitor); + } + _visitor.endVisit(*this); +} + +void VariableDeclaration::accept(ASTVisitor& _visitor) +{ + if (_visitor.visit(*this)) + if (m_typeName) + m_typeName->accept(_visitor); + _visitor.endVisit(*this); +} + +void VariableDeclaration::accept(ASTConstVisitor& _visitor) const +{ + if (_visitor.visit(*this)) + if (m_typeName) + m_typeName->accept(_visitor); + _visitor.endVisit(*this); +} + +void TypeName::accept(ASTVisitor& _visitor) +{ + _visitor.visit(*this); + _visitor.endVisit(*this); +} + +void TypeName::accept(ASTConstVisitor& _visitor) const +{ + _visitor.visit(*this); + _visitor.endVisit(*this); +} + +void ElementaryTypeName::accept(ASTVisitor& _visitor) +{ + _visitor.visit(*this); + _visitor.endVisit(*this); +} + +void ElementaryTypeName::accept(ASTConstVisitor& _visitor) const +{ + _visitor.visit(*this); + _visitor.endVisit(*this); +} + +void UserDefinedTypeName::accept(ASTVisitor& _visitor) +{ + _visitor.visit(*this); + _visitor.endVisit(*this); +} + +void UserDefinedTypeName::accept(ASTConstVisitor& _visitor) const +{ + _visitor.visit(*this); + _visitor.endVisit(*this); +} + +void Mapping::accept(ASTVisitor& _visitor) +{ + if (_visitor.visit(*this)) + { + m_keyType->accept(_visitor); + m_valueType->accept(_visitor); + } + _visitor.endVisit(*this); +} + +void Mapping::accept(ASTConstVisitor& _visitor) const +{ + if (_visitor.visit(*this)) + { + m_keyType->accept(_visitor); + m_valueType->accept(_visitor); + } + _visitor.endVisit(*this); +} + +void Block::accept(ASTVisitor& _visitor) +{ + if (_visitor.visit(*this)) + listAccept(m_statements, _visitor); + _visitor.endVisit(*this); +} + +void Block::accept(ASTConstVisitor& _visitor) const +{ + if (_visitor.visit(*this)) + listAccept(m_statements, _visitor); + _visitor.endVisit(*this); +} + +void IfStatement::accept(ASTVisitor& _visitor) +{ + if (_visitor.visit(*this)) + { + m_condition->accept(_visitor); + m_trueBody->accept(_visitor); + if (m_falseBody) + m_falseBody->accept(_visitor); + } + _visitor.endVisit(*this); +} + +void IfStatement::accept(ASTConstVisitor& _visitor) const +{ + if (_visitor.visit(*this)) + { + m_condition->accept(_visitor); + m_trueBody->accept(_visitor); + if (m_falseBody) + m_falseBody->accept(_visitor); + } + _visitor.endVisit(*this); +} + +void WhileStatement::accept(ASTVisitor& _visitor) +{ + if (_visitor.visit(*this)) + { + m_condition->accept(_visitor); + m_body->accept(_visitor); + } + _visitor.endVisit(*this); +} + +void WhileStatement::accept(ASTConstVisitor& _visitor) const +{ + if (_visitor.visit(*this)) + { + m_condition->accept(_visitor); + m_body->accept(_visitor); + } + _visitor.endVisit(*this); +} + +void Continue::accept(ASTVisitor& _visitor) +{ + _visitor.visit(*this); + _visitor.endVisit(*this); +} + +void Continue::accept(ASTConstVisitor& _visitor) const +{ + _visitor.visit(*this); + _visitor.endVisit(*this); +} + +void Break::accept(ASTVisitor& _visitor) +{ + _visitor.visit(*this); + _visitor.endVisit(*this); +} + +void Break::accept(ASTConstVisitor& _visitor) const +{ + _visitor.visit(*this); + _visitor.endVisit(*this); +} + +void Return::accept(ASTVisitor& _visitor) +{ + if (_visitor.visit(*this)) + if (m_expression) + m_expression->accept(_visitor); + _visitor.endVisit(*this); +} + +void Return::accept(ASTConstVisitor& _visitor) const +{ + if (_visitor.visit(*this)) + if (m_expression) + m_expression->accept(_visitor); + _visitor.endVisit(*this); +} + +void ExpressionStatement::accept(ASTVisitor& _visitor) +{ + if (_visitor.visit(*this)) + if (m_expression) + m_expression->accept(_visitor); + _visitor.endVisit(*this); +} + +void ExpressionStatement::accept(ASTConstVisitor& _visitor) const +{ + if (_visitor.visit(*this)) + if (m_expression) + m_expression->accept(_visitor); + _visitor.endVisit(*this); +} + +void VariableDefinition::accept(ASTVisitor& _visitor) +{ + if (_visitor.visit(*this)) + { + m_variable->accept(_visitor); + if (m_value) + m_value->accept(_visitor); + } + _visitor.endVisit(*this); +} + +void VariableDefinition::accept(ASTConstVisitor& _visitor) const +{ + if (_visitor.visit(*this)) + { + m_variable->accept(_visitor); + if (m_value) + m_value->accept(_visitor); + } + _visitor.endVisit(*this); +} + +void Assignment::accept(ASTVisitor& _visitor) +{ + if (_visitor.visit(*this)) + { + m_leftHandSide->accept(_visitor); + m_rightHandSide->accept(_visitor); + } + _visitor.endVisit(*this); +} + +void Assignment::accept(ASTConstVisitor& _visitor) const +{ + if (_visitor.visit(*this)) + { + m_leftHandSide->accept(_visitor); + m_rightHandSide->accept(_visitor); + } + _visitor.endVisit(*this); +} + +void UnaryOperation::accept(ASTVisitor& _visitor) +{ + if (_visitor.visit(*this)) + m_subExpression->accept(_visitor); + _visitor.endVisit(*this); +} + +void UnaryOperation::accept(ASTConstVisitor& _visitor) const +{ + if (_visitor.visit(*this)) + m_subExpression->accept(_visitor); + _visitor.endVisit(*this); +} + +void BinaryOperation::accept(ASTVisitor& _visitor) +{ + if (_visitor.visit(*this)) + { + m_left->accept(_visitor); + m_right->accept(_visitor); + } + _visitor.endVisit(*this); +} + +void BinaryOperation::accept(ASTConstVisitor& _visitor) const +{ + if (_visitor.visit(*this)) + { + m_left->accept(_visitor); + m_right->accept(_visitor); + } + _visitor.endVisit(*this); +} + +void FunctionCall::accept(ASTVisitor& _visitor) +{ + if (_visitor.visit(*this)) + { + m_expression->accept(_visitor); + listAccept(m_arguments, _visitor); + } + _visitor.endVisit(*this); +} + +void FunctionCall::accept(ASTConstVisitor& _visitor) const +{ + if (_visitor.visit(*this)) + { + m_expression->accept(_visitor); + listAccept(m_arguments, _visitor); + } + _visitor.endVisit(*this); +} + +void MemberAccess::accept(ASTVisitor& _visitor) +{ + if (_visitor.visit(*this)) + m_expression->accept(_visitor); + _visitor.endVisit(*this); +} + +void MemberAccess::accept(ASTConstVisitor& _visitor) const +{ + if (_visitor.visit(*this)) + m_expression->accept(_visitor); + _visitor.endVisit(*this); +} + +void IndexAccess::accept(ASTVisitor& _visitor) +{ + if (_visitor.visit(*this)) + { + m_base->accept(_visitor); + m_index->accept(_visitor); + } + _visitor.endVisit(*this); +} + +void IndexAccess::accept(ASTConstVisitor& _visitor) const +{ + if (_visitor.visit(*this)) + { + m_base->accept(_visitor); + m_index->accept(_visitor); + } + _visitor.endVisit(*this); +} + +void Identifier::accept(ASTVisitor& _visitor) +{ + _visitor.visit(*this); + _visitor.endVisit(*this); +} + +void Identifier::accept(ASTConstVisitor& _visitor) const +{ + _visitor.visit(*this); + _visitor.endVisit(*this); +} + +void ElementaryTypeNameExpression::accept(ASTVisitor& _visitor) +{ + _visitor.visit(*this); + _visitor.endVisit(*this); +} + +void ElementaryTypeNameExpression::accept(ASTConstVisitor& _visitor) const +{ + _visitor.visit(*this); + _visitor.endVisit(*this); +} + +void Literal::accept(ASTVisitor& _visitor) +{ + _visitor.visit(*this); + _visitor.endVisit(*this); +} + +void Literal::accept(ASTConstVisitor& _visitor) const +{ + _visitor.visit(*this); + _visitor.endVisit(*this); +} + +} +} diff --git a/libsolidity/BaseTypes.h b/libsolidity/BaseTypes.h index d1ffd7bbc..a8fd77c86 100644 --- a/libsolidity/BaseTypes.h +++ b/libsolidity/BaseTypes.h @@ -22,6 +22,8 @@ #pragma once +#include +#include #include namespace dev @@ -35,19 +37,19 @@ namespace solidity */ struct Location { - Location(int _start, int _end): start(_start), end(_end) { } + Location(int _start, int _end, std::shared_ptr _sourceName): + start(_start), end(_end), sourceName(_sourceName) { } Location(): start(-1), end(-1) { } - bool IsValid() const { return start >= 0 && end >= start; } - int start; int end; + std::shared_ptr sourceName; }; /// Stream output for Location (used e.g. in boost exceptions). inline std::ostream& operator<<(std::ostream& _out, Location const& _location) { - return _out << "[" << _location.start << "," << _location.end << ")"; + return _out << *_location.sourceName << "[" << _location.start << "," << _location.end << ")"; } } diff --git a/libsolidity/CMakeLists.txt b/libsolidity/CMakeLists.txt index ea2ef4b74..0a0b62bdd 100644 --- a/libsolidity/CMakeLists.txt +++ b/libsolidity/CMakeLists.txt @@ -1,21 +1,33 @@ cmake_policy(SET CMP0015 NEW) +# this policy was introduced in cmake 3.0 +# remove if, once 3.0 will be used on unix +if (${CMAKE_MAJOR_VERSION} GREATER 2) + # old policy do not use MACOSX_RPATH + cmake_policy(SET CMP0042 OLD) +endif() +set(CMAKE_AUTOMOC OFF) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DSTATICLIB") aux_source_directory(. SRC_LIST) +include_directories(${Boost_INCLUDE_DIRS}) +include_directories(${JSONCPP_INCLUDE_DIRS}) +include_directories(..) + set(EXECUTABLE solidity) file(GLOB HEADERS "*.h") -if(ETH_STATIC) + +if (ETH_STATIC) add_library(${EXECUTABLE} STATIC ${SRC_LIST} ${HEADERS}) else() add_library(${EXECUTABLE} SHARED ${SRC_LIST} ${HEADERS}) endif() -include_directories(..) - -target_link_libraries(${EXECUTABLE} evmcore devcore) +target_link_libraries(${EXECUTABLE} ${JSONCPP_LIBRARIES}) +target_link_libraries(${EXECUTABLE} evmcore) +target_link_libraries(${EXECUTABLE} devcore) install( TARGETS ${EXECUTABLE} ARCHIVE DESTINATION lib LIBRARY DESTINATION lib ) install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} ) diff --git a/libsolidity/Compiler.cpp b/libsolidity/Compiler.cpp index ed2b1f45f..258336917 100644 --- a/libsolidity/Compiler.cpp +++ b/libsolidity/Compiler.cpp @@ -26,96 +26,107 @@ #include #include #include +#include using namespace std; namespace dev { namespace solidity { -bytes Compiler::compile(ContractDefinition& _contract, bool _optimize) -{ - Compiler compiler; - compiler.compileContract(_contract); - return compiler.m_context.getAssembledBytecode(_optimize); -} - -void Compiler::compileContract(ContractDefinition& _contract) +void Compiler::compileContract(ContractDefinition const& _contract, vector const& _magicGlobals) { m_context = CompilerContext(); // clear it just in case - //@todo constructor + for (MagicVariableDeclaration const* variable: _magicGlobals) + m_context.addMagicGlobal(*variable); for (ASTPointer const& function: _contract.getDefinedFunctions()) - m_context.addFunction(*function); - //@todo sort them? - for (ASTPointer const& variable: _contract.getStateVariables()) - m_context.addStateVariable(*variable); + if (function->getName() != _contract.getName()) // don't add the constructor here + m_context.addFunction(*function); + registerStateVariables(_contract); - appendFunctionSelector(_contract.getDefinedFunctions()); + appendFunctionSelector(_contract); for (ASTPointer const& function: _contract.getDefinedFunctions()) - function->accept(*this); + if (function->getName() != _contract.getName()) // don't add the constructor here + function->accept(*this); - packIntoContractCreator(); + packIntoContractCreator(_contract); } -void Compiler::packIntoContractCreator() +void Compiler::packIntoContractCreator(ContractDefinition const& _contract) { - CompilerContext creatorContext; - eth::AssemblyItem sub = creatorContext.addSubroutine(m_context.getAssembly()); + CompilerContext runtimeContext; + swap(m_context, runtimeContext); + + registerStateVariables(_contract); + + FunctionDefinition* constructor = nullptr; + for (ASTPointer const& function: _contract.getDefinedFunctions()) + if (function->getName() == _contract.getName()) + { + constructor = function.get(); + break; + } + if (constructor) + { + eth::AssemblyItem returnTag = m_context.pushNewTag(); + m_context.addFunction(*constructor); // note that it cannot be called due to syntactic reasons + //@todo copy constructor arguments from calldata to memory prior to this + //@todo calling other functions inside the constructor should either trigger a parse error + //or we should copy them here (register them above and call "accept") - detecting which + // functions are referenced / called needs to be done in a recursive way. + appendCalldataUnpacker(*constructor, true); + m_context.appendJumpTo(m_context.getFunctionEntryLabel(*constructor)); + constructor->accept(*this); + m_context << returnTag; + } + + eth::AssemblyItem sub = m_context.addSubroutine(runtimeContext.getAssembly()); // stack contains sub size - creatorContext << eth::Instruction::DUP1 << sub << u256(0) << eth::Instruction::CODECOPY; - creatorContext << u256(0) << eth::Instruction::RETURN; - swap(m_context, creatorContext); + m_context << eth::Instruction::DUP1 << sub << u256(0) << eth::Instruction::CODECOPY; + m_context << u256(0) << eth::Instruction::RETURN; } -void Compiler::appendFunctionSelector(vector> const& _functions) +void Compiler::appendFunctionSelector(ContractDefinition const& _contract) { - // sort all public functions and store them together with a tag for their argument decoding section - map> publicFunctions; - for (ASTPointer const& f: _functions) - if (f->isPublic()) - publicFunctions.insert(make_pair(f->getName(), make_pair(f.get(), m_context.newTag()))); + vector interfaceFunctions = _contract.getInterfaceFunctions(); + vector callDataUnpackerEntryPoints; - //@todo remove constructor - - if (publicFunctions.size() > 255) + if (interfaceFunctions.size() > 255) BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("More than 255 public functions for contract.")); - //@todo check for calldatasize? - // retrieve the first byte of the call data - m_context << u256(0) << eth::Instruction::CALLDATALOAD << u256(0) << eth::Instruction::BYTE; - // check that it is not too large - m_context << eth::Instruction::DUP1 << u256(publicFunctions.size() - 1) << eth::Instruction::LT; - eth::AssemblyItem returnTag = m_context.appendConditionalJump(); - - // otherwise, jump inside jump table (each entry of the table has size 4) - m_context << u256(4) << eth::Instruction::MUL; - eth::AssemblyItem jumpTableStart = m_context.pushNewTag(); - m_context << eth::Instruction::ADD << eth::Instruction::JUMP; + // retrieve the first byte of the call data, which determines the called function + // @todo This code had a jump table in a previous version which was more efficient but also + // error prone (due to the optimizer and variable length tag addresses) + m_context << u256(1) << u256(0) // some constants + << eth::dupInstruction(1) << eth::Instruction::CALLDATALOAD + << eth::dupInstruction(2) << eth::Instruction::BYTE + << eth::dupInstruction(2); - // jump table, tell the optimizer not to remove the JUMPDESTs - m_context << eth::AssemblyItem(eth::NoOptimizeBegin) << jumpTableStart; - for (pair> const& f: publicFunctions) - m_context.appendJumpTo(f.second.second) << eth::Instruction::JUMPDEST; - m_context << eth::AssemblyItem(eth::NoOptimizeEnd); - - m_context << returnTag << eth::Instruction::STOP; - - for (pair> const& f: publicFunctions) + // stack here: 1 0 0, stack top will be counted up until it matches funid + for (unsigned funid = 0; funid < interfaceFunctions.size(); ++funid) { - FunctionDefinition const& function = *f.second.first; - m_context << f.second.second; + callDataUnpackerEntryPoints.push_back(m_context.newTag()); + m_context << eth::dupInstruction(2) << eth::dupInstruction(2) << eth::Instruction::EQ; + m_context.appendConditionalJumpTo(callDataUnpackerEntryPoints.back()); + if (funid < interfaceFunctions.size() - 1) + m_context << eth::dupInstruction(4) << eth::Instruction::ADD; + } + m_context << eth::Instruction::STOP; // function not found + for (unsigned funid = 0; funid < interfaceFunctions.size(); ++funid) + { + FunctionDefinition const& function = *interfaceFunctions[funid]; + m_context << callDataUnpackerEntryPoints[funid]; eth::AssemblyItem returnTag = m_context.pushNewTag(); appendCalldataUnpacker(function); m_context.appendJumpTo(m_context.getFunctionEntryLabel(function)); m_context << returnTag; - appendReturnValuePacker(function); } } -void Compiler::appendCalldataUnpacker(FunctionDefinition const& _function) +unsigned Compiler::appendCalldataUnpacker(FunctionDefinition const& _function, bool _fromMemory) { // We do not check the calldata size, everything is zero-padded. unsigned dataOffset = 1; @@ -124,17 +135,15 @@ void Compiler::appendCalldataUnpacker(FunctionDefinition const& _function) for (ASTPointer const& var: _function.getParameters()) { unsigned const numBytes = var->getType()->getCalldataEncodedSize(); - if (numBytes == 0) + if (numBytes > 32) BOOST_THROW_EXCEPTION(CompilerError() << errinfo_sourceLocation(var->getLocation()) << errinfo_comment("Type " + var->getType()->toString() + " not yet supported.")); - if (numBytes == 32) - m_context << u256(dataOffset) << eth::Instruction::CALLDATALOAD; - else - m_context << (u256(1) << ((32 - numBytes) * 8)) << u256(dataOffset) - << eth::Instruction::CALLDATALOAD << eth::Instruction::DIV; + bool leftAligned = var->getType()->getCategory() == Type::Category::STRING; + CompilerUtils(m_context).loadFromMemory(dataOffset, numBytes, leftAligned, !_fromMemory); dataOffset += numBytes; } + return dataOffset; } void Compiler::appendReturnValuePacker(FunctionDefinition const& _function) @@ -142,25 +151,33 @@ void Compiler::appendReturnValuePacker(FunctionDefinition const& _function) //@todo this can be also done more efficiently unsigned dataOffset = 0; vector> const& parameters = _function.getReturnParameters(); + unsigned stackDepth = CompilerUtils(m_context).getSizeOnStack(parameters); for (unsigned i = 0; i < parameters.size(); ++i) { Type const& paramType = *parameters[i]->getType(); unsigned numBytes = paramType.getCalldataEncodedSize(); - if (numBytes == 0) + if (numBytes > 32) BOOST_THROW_EXCEPTION(CompilerError() << errinfo_sourceLocation(parameters[i]->getLocation()) << errinfo_comment("Type " + paramType.toString() + " not yet supported.")); - m_context << eth::dupInstruction(parameters.size() - i); - if (numBytes != 32) - m_context << (u256(1) << ((32 - numBytes) * 8)) << eth::Instruction::MUL; - m_context << u256(dataOffset) << eth::Instruction::MSTORE; + CompilerUtils(m_context).copyToStackTop(stackDepth, paramType); + bool const leftAligned = paramType.getCategory() == Type::Category::STRING; + CompilerUtils(m_context).storeInMemory(dataOffset, numBytes, leftAligned); + stackDepth -= paramType.getSizeOnStack(); dataOffset += numBytes; } // note that the stack is not cleaned up here m_context << u256(dataOffset) << u256(0) << eth::Instruction::RETURN; } -bool Compiler::visit(FunctionDefinition& _function) +void Compiler::registerStateVariables(ContractDefinition const& _contract) +{ + //@todo sort them? + for (ASTPointer const& variable: _contract.getStateVariables()) + m_context.addStateVariable(*variable); +} + +bool Compiler::visit(FunctionDefinition const& _function) { //@todo to simplify this, the calling convention could by changed such that // caller puts: [retarg0] ... [retargm] [return address] [arg0] ... [argn] @@ -176,15 +193,12 @@ bool Compiler::visit(FunctionDefinition& _function) // stack upon entry: [return address] [arg0] [arg1] ... [argn] // reserve additional slots: [retarg0] ... [retargm] [localvar0] ... [localvarp] - unsigned const numArguments = _function.getParameters().size(); - unsigned const numReturnValues = _function.getReturnParameters().size(); - unsigned const numLocalVariables = _function.getLocalVariables().size(); - - for (ASTPointer const& variable: _function.getParameters() + _function.getReturnParameters()) + for (ASTPointer const& variable: _function.getParameters()) m_context.addVariable(*variable); + for (ASTPointer const& variable: _function.getReturnParameters()) + m_context.addAndInitializeVariable(*variable); for (VariableDeclaration const* localVariable: _function.getLocalVariables()) - m_context.addVariable(*localVariable); - m_context.initializeLocalVariables(numReturnValues + numLocalVariables); + m_context.addAndInitializeVariable(*localVariable); _function.getBody().accept(*this); @@ -196,12 +210,16 @@ bool Compiler::visit(FunctionDefinition& _function) // Note that the fact that the return arguments are of increasing index is vital for this // algorithm to work. + unsigned const argumentsSize = CompilerUtils::getSizeOnStack(_function.getParameters()); + unsigned const returnValuesSize = CompilerUtils::getSizeOnStack(_function.getReturnParameters()); + unsigned const localVariablesSize = CompilerUtils::getSizeOnStack(_function.getLocalVariables()); + vector stackLayout; - stackLayout.push_back(numReturnValues); // target of return address - stackLayout += vector(numArguments, -1); // discard all arguments - for (unsigned i = 0; i < numReturnValues; ++i) + stackLayout.push_back(returnValuesSize); // target of return address + stackLayout += vector(argumentsSize, -1); // discard all arguments + for (unsigned i = 0; i < returnValuesSize; ++i) stackLayout.push_back(i); - stackLayout += vector(numLocalVariables, -1); + stackLayout += vector(localVariablesSize, -1); while (stackLayout.back() != int(stackLayout.size() - 1)) if (stackLayout.back() < 0) @@ -221,20 +239,20 @@ bool Compiler::visit(FunctionDefinition& _function) return false; } -bool Compiler::visit(IfStatement& _ifStatement) +bool Compiler::visit(IfStatement const& _ifStatement) { - ExpressionCompiler::compileExpression(m_context, _ifStatement.getCondition()); + compileExpression(_ifStatement.getCondition()); eth::AssemblyItem trueTag = m_context.appendConditionalJump(); if (_ifStatement.getFalseStatement()) _ifStatement.getFalseStatement()->accept(*this); - eth::AssemblyItem endTag = m_context.appendJump(); + eth::AssemblyItem endTag = m_context.appendJumpToNew(); m_context << trueTag; _ifStatement.getTrueStatement().accept(*this); m_context << endTag; return false; } -bool Compiler::visit(WhileStatement& _whileStatement) +bool Compiler::visit(WhileStatement const& _whileStatement) { eth::AssemblyItem loopStart = m_context.newTag(); eth::AssemblyItem loopEnd = m_context.newTag(); @@ -242,7 +260,7 @@ bool Compiler::visit(WhileStatement& _whileStatement) m_breakTags.push_back(loopEnd); m_context << loopStart; - ExpressionCompiler::compileExpression(m_context, _whileStatement.getCondition()); + compileExpression(_whileStatement.getCondition()); m_context << eth::Instruction::ISZERO; m_context.appendConditionalJumpTo(loopEnd); @@ -256,59 +274,60 @@ bool Compiler::visit(WhileStatement& _whileStatement) return false; } -bool Compiler::visit(Continue&) +bool Compiler::visit(Continue const&) { if (!m_continueTags.empty()) m_context.appendJumpTo(m_continueTags.back()); return false; } -bool Compiler::visit(Break&) +bool Compiler::visit(Break const&) { if (!m_breakTags.empty()) m_context.appendJumpTo(m_breakTags.back()); return false; } -bool Compiler::visit(Return& _return) +bool Compiler::visit(Return const& _return) { //@todo modifications are needed to make this work with functions returning multiple values - if (Expression* expression = _return.getExpression()) + if (Expression const* expression = _return.getExpression()) { - ExpressionCompiler::compileExpression(m_context, *expression); + compileExpression(*expression); VariableDeclaration const& firstVariable = *_return.getFunctionReturnParameters().getParameters().front(); ExpressionCompiler::appendTypeConversion(m_context, *expression->getType(), *firstVariable.getType()); - unsigned stackPosition = m_context.baseToCurrentStackOffset(m_context.getBaseStackOffsetOfVariable(firstVariable)); - m_context << eth::swapInstruction(stackPosition) << eth::Instruction::POP; + CompilerUtils(m_context).moveToStackVariable(firstVariable); } m_context.appendJumpTo(m_returnTag); return false; } -bool Compiler::visit(VariableDefinition& _variableDefinition) +bool Compiler::visit(VariableDefinition const& _variableDefinition) { - if (Expression* expression = _variableDefinition.getExpression()) + if (Expression const* expression = _variableDefinition.getExpression()) { - ExpressionCompiler::compileExpression(m_context, *expression); + compileExpression(*expression); ExpressionCompiler::appendTypeConversion(m_context, *expression->getType(), *_variableDefinition.getDeclaration().getType()); - unsigned baseStackOffset = m_context.getBaseStackOffsetOfVariable(_variableDefinition.getDeclaration()); - unsigned stackPosition = m_context.baseToCurrentStackOffset(baseStackOffset); - m_context << eth::swapInstruction(stackPosition) << eth::Instruction::POP; + CompilerUtils(m_context).moveToStackVariable(_variableDefinition.getDeclaration()); } return false; } -bool Compiler::visit(ExpressionStatement& _expressionStatement) +bool Compiler::visit(ExpressionStatement const& _expressionStatement) { - Expression& expression = _expressionStatement.getExpression(); - ExpressionCompiler::compileExpression(m_context, expression); - if (expression.getType()->getCategory() != Type::Category::VOID) - m_context << eth::Instruction::POP; + Expression const& expression = _expressionStatement.getExpression(); + compileExpression(expression); + CompilerUtils(m_context).popStackElement(*expression.getType()); return false; } +void Compiler::compileExpression(Expression const& _expression) +{ + ExpressionCompiler::compileExpression(m_context, _expression, m_optimize); +} + } } diff --git a/libsolidity/Compiler.h b/libsolidity/Compiler.h index d931f5359..639e98410 100644 --- a/libsolidity/Compiler.h +++ b/libsolidity/Compiler.h @@ -27,35 +27,39 @@ namespace dev { namespace solidity { -class Compiler: private ASTVisitor +class Compiler: private ASTConstVisitor { public: - Compiler(): m_returnTag(m_context.newTag()) {} + explicit Compiler(bool _optimize = false): m_optimize(_optimize), m_returnTag(m_context.newTag()) {} - void compileContract(ContractDefinition& _contract); - bytes getAssembledBytecode(bool _optimize = false) { return m_context.getAssembledBytecode(_optimize); } + void compileContract(ContractDefinition const& _contract, std::vector const& _magicGlobals); + bytes getAssembledBytecode() { return m_context.getAssembledBytecode(m_optimize); } void streamAssembly(std::ostream& _stream) const { m_context.streamAssembly(_stream); } - /// Compile the given contract and return the EVM bytecode. - static bytes compile(ContractDefinition& _contract, bool _optimize); - private: - /// Creates a new compiler context / assembly and packs the current code into the data part. - void packIntoContractCreator(); - void appendFunctionSelector(std::vector > const& _functions); - void appendCalldataUnpacker(FunctionDefinition const& _function); + /// Creates a new compiler context / assembly, packs the current code into the data part and + /// adds the constructor code. + void packIntoContractCreator(ContractDefinition const& _contract); + void appendFunctionSelector(ContractDefinition const& _contract); + /// Creates code that unpacks the arguments for the given function, from memory if + /// @a _fromMemory is true, otherwise from call data. @returns the size of the data in bytes. + unsigned appendCalldataUnpacker(FunctionDefinition const& _function, bool _fromMemory = false); void appendReturnValuePacker(FunctionDefinition const& _function); - virtual bool visit(FunctionDefinition& _function) override; - virtual bool visit(IfStatement& _ifStatement) override; - virtual bool visit(WhileStatement& _whileStatement) override; - virtual bool visit(Continue& _continue) override; - virtual bool visit(Break& _break) override; - virtual bool visit(Return& _return) override; - virtual bool visit(VariableDefinition& _variableDefinition) override; - virtual bool visit(ExpressionStatement& _expressionStatement) override; + void registerStateVariables(ContractDefinition const& _contract); + + virtual bool visit(FunctionDefinition const& _function) override; + virtual bool visit(IfStatement const& _ifStatement) override; + virtual bool visit(WhileStatement const& _whileStatement) override; + virtual bool visit(Continue const& _continue) override; + virtual bool visit(Break const& _break) override; + virtual bool visit(Return const& _return) override; + virtual bool visit(VariableDefinition const& _variableDefinition) override; + virtual bool visit(ExpressionStatement const& _expressionStatement) override; + void compileExpression(Expression const& _expression); + bool const m_optimize; CompilerContext m_context; std::vector m_breakTags; ///< tag to jump to for a "break" statement std::vector m_continueTags; ///< tag to jump to for a "continue" statement diff --git a/libsolidity/CompilerContext.cpp b/libsolidity/CompilerContext.cpp index 3c1acdfa7..cd22c4e8b 100644 --- a/libsolidity/CompilerContext.cpp +++ b/libsolidity/CompilerContext.cpp @@ -30,26 +30,41 @@ using namespace std; namespace dev { namespace solidity { +void CompilerContext::addMagicGlobal(MagicVariableDeclaration const& _declaration) +{ + m_magicGlobals.insert(&_declaration); +} + void CompilerContext::addStateVariable(VariableDeclaration const& _declaration) { m_stateVariables[&_declaration] = m_stateVariablesSize; m_stateVariablesSize += _declaration.getType()->getStorageSize(); } -void CompilerContext::initializeLocalVariables(unsigned _numVariables) +void CompilerContext::addVariable(VariableDeclaration const& _declaration) +{ + m_localVariables[&_declaration] = m_localVariablesSize; + m_localVariablesSize += _declaration.getType()->getSizeOnStack(); +} + +void CompilerContext::addAndInitializeVariable(VariableDeclaration const& _declaration) { - if (_numVariables > 0) - { + addVariable(_declaration); + + unsigned const size = _declaration.getType()->getSizeOnStack(); + for (unsigned i = 0; i < size; ++i) *this << u256(0); - for (unsigned i = 1; i < _numVariables; ++i) - *this << eth::Instruction::DUP1; - m_asm.adjustDeposit(-_numVariables); - } + m_asm.adjustDeposit(-size); +} + +void CompilerContext::addFunction(FunctionDefinition const& _function) +{ + m_functionEntryLabels.insert(std::make_pair(&_function, m_asm.newTag())); } bool CompilerContext::isLocalVariable(Declaration const* _declaration) const { - return std::find(m_localVariables.begin(), m_localVariables.end(), _declaration) != m_localVariables.end(); + return m_localVariables.count(_declaration) > 0; } eth::AssemblyItem CompilerContext::getFunctionEntryLabel(FunctionDefinition const& _function) const @@ -62,10 +77,10 @@ eth::AssemblyItem CompilerContext::getFunctionEntryLabel(FunctionDefinition cons unsigned CompilerContext::getBaseStackOffsetOfVariable(Declaration const& _declaration) const { - auto res = find(begin(m_localVariables), end(m_localVariables), &_declaration); + auto res = m_localVariables.find(&_declaration); if (asserts(res != m_localVariables.end())) BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Variable not found on stack.")); - return unsigned(end(m_localVariables) - res - 1); + return m_localVariablesSize - res->second - 1; } unsigned CompilerContext::baseToCurrentStackOffset(unsigned _baseOffset) const diff --git a/libsolidity/CompilerContext.h b/libsolidity/CompilerContext.h index 562c29321..652e65a63 100644 --- a/libsolidity/CompilerContext.h +++ b/libsolidity/CompilerContext.h @@ -25,6 +25,7 @@ #include #include #include +#include #include namespace dev { @@ -40,14 +41,16 @@ class CompilerContext public: CompilerContext(): m_stateVariablesSize(0) {} + void addMagicGlobal(MagicVariableDeclaration const& _declaration); void addStateVariable(VariableDeclaration const& _declaration); void startNewFunction() { m_localVariables.clear(); m_asm.setDeposit(0); } - void initializeLocalVariables(unsigned _numVariables); - void addVariable(VariableDeclaration const& _declaration) { m_localVariables.push_back(&_declaration); } - void addFunction(FunctionDefinition const& _function) { m_functionEntryLabels.insert(std::make_pair(&_function, m_asm.newTag())); } + void addVariable(VariableDeclaration const& _declaration); + void addAndInitializeVariable(VariableDeclaration const& _declaration); + void addFunction(FunctionDefinition const& _function); void adjustStackOffset(int _adjustment) { m_asm.adjustDeposit(_adjustment); } + bool isMagicGlobal(Declaration const* _declaration) const { return m_magicGlobals.count(_declaration); } bool isFunctionDefinition(Declaration const* _declaration) const { return m_functionEntryLabels.count(_declaration); } bool isLocalVariable(Declaration const* _declaration) const; bool isStateVariable(Declaration const* _declaration) const { return m_stateVariables.count(_declaration); } @@ -65,7 +68,9 @@ public: /// Appends a JUMPI instruction to @a _tag CompilerContext& appendConditionalJumpTo(eth::AssemblyItem const& _tag) { m_asm.appendJumpI(_tag); return *this; } /// Appends a JUMP to a new tag and @returns the tag - eth::AssemblyItem appendJump() { return m_asm.appendJump().tag(); } + eth::AssemblyItem appendJumpToNew() { return m_asm.appendJump().tag(); } + /// Appends a JUMP to a tag already on the stack + CompilerContext& appendJump() { return *this << eth::Instruction::JUMP; } /// Appends a JUMP to a specific tag CompilerContext& appendJumpTo(eth::AssemblyItem const& _tag) { m_asm.appendJump(_tag); return *this; } /// Appends pushing of a new tag and @returns the new tag. @@ -88,12 +93,16 @@ public: private: eth::Assembly m_asm; + /// Magic global variables like msg, tx or this, distinguished by type. + std::set m_magicGlobals; /// Size of the state variables, offset of next variable to be added. u256 m_stateVariablesSize; /// Storage offsets of state variables std::map m_stateVariables; - /// Offsets of local variables on the stack. - std::vector m_localVariables; + /// Offsets of local variables on the stack (relative to stack base). + std::map m_localVariables; + /// Sum of stack sizes of local variables + unsigned m_localVariablesSize; /// Labels pointing to the entry points of funcitons. std::map m_functionEntryLabels; }; diff --git a/libsolidity/CompilerStack.cpp b/libsolidity/CompilerStack.cpp index c991171a5..7aaa79b1c 100644 --- a/libsolidity/CompilerStack.cpp +++ b/libsolidity/CompilerStack.cpp @@ -23,9 +23,11 @@ #include #include #include +#include #include #include #include +#include using namespace std; @@ -34,17 +36,208 @@ namespace dev namespace solidity { -bytes CompilerStack::compile(std::string const& _sourceCode, shared_ptr _scanner, - bool _optimize) +void CompilerStack::addSource(string const& _name, string const& _content) { - if (!_scanner) - _scanner = make_shared(); - _scanner->reset(CharStream(_sourceCode)); + if (m_sources.count(_name)) + BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Source by given name already exists.")); - ASTPointer contract = Parser().parse(_scanner); - NameAndTypeResolver().resolveNamesAndTypes(*contract); - return Compiler::compile(*contract, _optimize); + reset(true); + m_sources[_name].scanner = make_shared(CharStream(_content), _name); } +void CompilerStack::setSource(string const& _sourceCode) +{ + reset(); + addSource("", _sourceCode); +} + +void CompilerStack::parse() +{ + for (auto& sourcePair: m_sources) + { + sourcePair.second.scanner->reset(); + sourcePair.second.ast = Parser().parse(sourcePair.second.scanner); + } + resolveImports(); + + m_globalContext = make_shared(); + NameAndTypeResolver resolver(m_globalContext->getDeclarations()); + for (Source const* source: m_sourceOrder) + resolver.registerDeclarations(*source->ast); + for (Source const* source: m_sourceOrder) + for (ASTPointer const& node: source->ast->getNodes()) + if (ContractDefinition* contract = dynamic_cast(node.get())) + { + m_globalContext->setCurrentContract(*contract); + resolver.updateDeclaration(*m_globalContext->getCurrentThis()); + resolver.resolveNamesAndTypes(*contract); + m_contracts[contract->getName()].contract = contract; + } + m_parseSuccessful = true; +} + +void CompilerStack::parse(string const& _sourceCode) +{ + setSource(_sourceCode); + parse(); +} + +vector CompilerStack::getContractNames() const +{ + if (!m_parseSuccessful) + BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Parsing was not successful.")); + vector contractNames; + for (auto const& contract: m_contracts) + contractNames.push_back(contract.first); + return contractNames; +} + +void CompilerStack::compile(bool _optimize) +{ + if (!m_parseSuccessful) + parse(); + for (Source const* source: m_sourceOrder) + for (ASTPointer const& node: source->ast->getNodes()) + if (ContractDefinition* contract = dynamic_cast(node.get())) + { + m_globalContext->setCurrentContract(*contract); + shared_ptr compiler = make_shared(_optimize); + compiler->compileContract(*contract, m_globalContext->getMagicVariables()); + Contract& compiledContract = m_contracts[contract->getName()]; + compiledContract.bytecode = compiler->getAssembledBytecode(); + compiledContract.compiler = move(compiler); + } +} + +bytes const& CompilerStack::compile(string const& _sourceCode, bool _optimize) +{ + parse(_sourceCode); + compile(_optimize); + return getBytecode(); +} + +bytes const& CompilerStack::getBytecode(string const& _contractName) const +{ + return getContract(_contractName).bytecode; +} + +void CompilerStack::streamAssembly(ostream& _outStream, string const& _contractName) const +{ + getContract(_contractName).compiler->streamAssembly(_outStream); +} + +string const& CompilerStack::getInterface(string const& _contractName) const +{ + return getJsonDocumentation(_contractName, DocumentationType::ABI_INTERFACE); +} + +string const& CompilerStack::getJsonDocumentation(string const& _contractName, DocumentationType _type) const +{ + if (!m_parseSuccessful) + BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Parsing was not successful.")); + + Contract const& contract = getContract(_contractName); + + std::unique_ptr* doc; + switch (_type) + { + case DocumentationType::NATSPEC_USER: + doc = &contract.userDocumentation; + break; + case DocumentationType::NATSPEC_DEV: + doc = &contract.devDocumentation; + break; + case DocumentationType::ABI_INTERFACE: + doc = &contract.interface; + break; + default: + BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Illegal documentation type.")); + } + if (!*doc) + *doc = contract.interfaceHandler->getDocumentation(*contract.contract, _type); + return *(*doc); +} + +Scanner const& CompilerStack::getScanner(string const& _sourceName) const +{ + return *getSource(_sourceName).scanner; +} + +SourceUnit const& CompilerStack::getAST(string const& _sourceName) const +{ + return *getSource(_sourceName).ast; +} + +bytes CompilerStack::staticCompile(std::string const& _sourceCode, bool _optimize) +{ + CompilerStack stack; + return stack.compile(_sourceCode, _optimize); +} + +void CompilerStack::reset(bool _keepSources) +{ + m_parseSuccessful = false; + if (_keepSources) + for (auto sourcePair: m_sources) + sourcePair.second.reset(); + else + m_sources.clear(); + m_globalContext.reset(); + m_sourceOrder.clear(); + m_contracts.clear(); +} + +void CompilerStack::resolveImports() +{ + // topological sorting (depth first search) of the import graph, cutting potential cycles + vector sourceOrder; + set sourcesSeen; + + function toposort = [&](Source const* _source) + { + if (sourcesSeen.count(_source)) + return; + sourcesSeen.insert(_source); + for (ASTPointer const& node: _source->ast->getNodes()) + if (ImportDirective const* import = dynamic_cast(node.get())) + { + string const& id = import->getIdentifier(); + if (!m_sources.count(id)) + BOOST_THROW_EXCEPTION(ParserError() + << errinfo_sourceLocation(import->getLocation()) + << errinfo_comment("Source not found.")); + toposort(&m_sources[id]); + } + sourceOrder.push_back(_source); + }; + + for (auto const& sourcePair: m_sources) + toposort(&sourcePair.second); + + swap(m_sourceOrder, sourceOrder); +} + +CompilerStack::Contract const& CompilerStack::getContract(string const& _contractName) const +{ + if (m_contracts.empty()) + BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("No compiled contracts found.")); + if (_contractName.empty()) + return m_contracts.begin()->second; + auto it = m_contracts.find(_contractName); + if (it == m_contracts.end()) + BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Contract " + _contractName + " not found.")); + return it->second; +} + +CompilerStack::Source const& CompilerStack::getSource(string const& _sourceName) const +{ + auto it = m_sources.find(_sourceName); + if (it == m_sources.end()) + BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Given source file not found.")); + return it->second; +} + +CompilerStack::Contract::Contract(): interfaceHandler(make_shared()) {} + } } diff --git a/libsolidity/CompilerStack.h b/libsolidity/CompilerStack.h index b003745d2..b6c34f1ac 100644 --- a/libsolidity/CompilerStack.h +++ b/libsolidity/CompilerStack.h @@ -22,21 +22,114 @@ #pragma once +#include #include #include +#include #include namespace dev { namespace solidity { -class Scanner; // forward +// forward declarations +class Scanner; +class ContractDefinition; +class SourceUnit; +class Compiler; +class GlobalContext; +class InterfaceHandler; -class CompilerStack +enum class DocumentationType: uint8_t +{ + NATSPEC_USER = 1, + NATSPEC_DEV, + ABI_INTERFACE +}; + +/** + * Easy to use and self-contained Solidity compiler with as few header dependencies as possible. + * It holds state and can be used to either step through the compilation stages (and abort e.g. + * before compilation to bytecode) or run the whole compilation in one call. + */ +class CompilerStack: boost::noncopyable { public: + CompilerStack(): m_parseSuccessful(false) {} + + /// Adds a source object (e.g. file) to the parser. After this, parse has to be called again. + void addSource(std::string const& _name, std::string const& _content); + void setSource(std::string const& _sourceCode); + /// Parses all source units that were added + void parse(); + /// Sets the given source code as the only source unit and parses it. + void parse(std::string const& _sourceCode); + /// Returns a list of the contract names in the sources. + std::vector getContractNames() const; + + /// Compiles the source units that were previously added and parsed. + void compile(bool _optimize = false); + /// Parses and compiles the given source code. + /// @returns the compiled bytecode + bytes const& compile(std::string const& _sourceCode, bool _optimize = false); + + bytes const& getBytecode(std::string const& _contractName = "") const; + /// Streams a verbose version of the assembly to @a _outStream. + /// Prerequisite: Successful compilation. + void streamAssembly(std::ostream& _outStream, std::string const& _contractName = "") const; + + /// Returns a string representing the contract interface in JSON. + /// Prerequisite: Successful call to parse or compile. + std::string const& getInterface(std::string const& _contractName = "") const; + /// Returns a string representing the contract's documentation in JSON. + /// Prerequisite: Successful call to parse or compile. + /// @param type The type of the documentation to get. + /// Can be one of 3 types defined at @c DocumentationType + std::string const& getJsonDocumentation(std::string const& _contractName, DocumentationType _type) const; + + /// Returns the previously used scanner, useful for counting lines during error reporting. + Scanner const& getScanner(std::string const& _sourceName = "") const; + SourceUnit const& getAST(std::string const& _sourceName = "") const; + /// Compile the given @a _sourceCode to bytecode. If a scanner is provided, it is used for /// scanning the source code - this is useful for printing exception information. - static bytes compile(std::string const& _sourceCode, std::shared_ptr _scanner = std::shared_ptr(), bool _optimize = false); + static bytes staticCompile(std::string const& _sourceCode, bool _optimize = false); + +private: + /** + * Information pertaining to one source unit, filled gradually during parsing and compilation. + */ + struct Source + { + std::shared_ptr scanner; + std::shared_ptr ast; + std::string interface; + void reset() { scanner.reset(); ast.reset(); interface.clear(); } + }; + + struct Contract + { + ContractDefinition* contract; + std::shared_ptr compiler; + bytes bytecode; + std::shared_ptr interfaceHandler; + mutable std::unique_ptr interface; + mutable std::unique_ptr userDocumentation; + mutable std::unique_ptr devDocumentation; + + Contract(); + }; + + void reset(bool _keepSources = false); + void resolveImports(); + + Contract const& getContract(std::string const& _contractName = "") const; + Source const& getSource(std::string const& _sourceName = "") const; + + bool m_parseSuccessful; + std::map m_sources; + std::shared_ptr m_globalContext; + std::vector m_sourceOrder; + std::map m_contracts; }; } diff --git a/libsolidity/CompilerUtils.cpp b/libsolidity/CompilerUtils.cpp new file mode 100644 index 000000000..9f474896e --- /dev/null +++ b/libsolidity/CompilerUtils.cpp @@ -0,0 +1,111 @@ +/* + This file is part of cpp-ethereum. + + cpp-ethereum is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + cpp-ethereum is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with cpp-ethereum. If not, see . +*/ +/** + * @author Christian + * @date 2014 + * Routines used by both the compiler and the expression compiler. + */ + +#include +#include +#include + +using namespace std; + +namespace dev +{ +namespace solidity +{ + +void CompilerUtils::loadFromMemory(unsigned _offset, unsigned _bytes, bool _leftAligned, bool _fromCalldata) +{ + if (_bytes == 0) + { + m_context << u256(0); + return; + } + eth::Instruction load = _fromCalldata ? eth::Instruction::CALLDATALOAD : eth::Instruction::MLOAD; + if (asserts(_bytes <= 32)) + BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Memory load of more than 32 bytes requested.")); + if (_bytes == 32) + m_context << u256(_offset) << load; + else + { + // load data and add leading or trailing zeros by dividing/multiplying depending on alignment + u256 shiftFactor = u256(1) << ((32 - _bytes) * 8); + m_context << shiftFactor; + if (_leftAligned) + m_context << eth::Instruction::DUP1; + m_context << u256(_offset) << load << eth::Instruction::DIV; + if (_leftAligned) + m_context << eth::Instruction::MUL; + } +} + +void CompilerUtils::storeInMemory(unsigned _offset, unsigned _bytes, bool _leftAligned) +{ + if (_bytes == 0) + { + m_context << eth::Instruction::POP; + return; + } + if (asserts(_bytes <= 32)) + BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Memory store of more than 32 bytes requested.")); + if (_bytes != 32 && !_leftAligned) + // shift the value accordingly before storing + m_context << (u256(1) << ((32 - _bytes) * 8)) << eth::Instruction::MUL; + m_context << u256(_offset) << eth::Instruction::MSTORE; +} + +void CompilerUtils::moveToStackVariable(VariableDeclaration const& _variable) +{ + unsigned const stackPosition = m_context.baseToCurrentStackOffset(m_context.getBaseStackOffsetOfVariable(_variable)); + unsigned const size = _variable.getType()->getSizeOnStack(); + // move variable starting from its top end in the stack + if (stackPosition - size + 1 > 16) + BOOST_THROW_EXCEPTION(CompilerError() << errinfo_sourceLocation(_variable.getLocation()) + << errinfo_comment("Stack too deep.")); + for (unsigned i = 0; i < size; ++i) + m_context << eth::swapInstruction(stackPosition - size + 1) << eth::Instruction::POP; +} + +void CompilerUtils::copyToStackTop(unsigned _stackDepth, Type const& _type) +{ + if (_stackDepth > 16) + BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Stack too deep.")); + unsigned const size = _type.getSizeOnStack(); + for (unsigned i = 0; i < size; ++i) + m_context << eth::dupInstruction(_stackDepth); +} + +void CompilerUtils::popStackElement(Type const& _type) +{ + unsigned const size = _type.getSizeOnStack(); + for (unsigned i = 0; i < size; ++i) + m_context << eth::Instruction::POP; +} + +unsigned CompilerUtils::getSizeOnStack(vector> const& _variableTypes) +{ + unsigned size = 0; + for (shared_ptr const& type: _variableTypes) + size += type->getSizeOnStack(); + return size; +} + +} +} diff --git a/libsolidity/CompilerUtils.h b/libsolidity/CompilerUtils.h new file mode 100644 index 000000000..928f0e2d3 --- /dev/null +++ b/libsolidity/CompilerUtils.h @@ -0,0 +1,75 @@ +/* + This file is part of cpp-ethereum. + + cpp-ethereum is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + cpp-ethereum is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with cpp-ethereum. If not, see . +*/ +/** + * @author Christian + * @date 2014 + * Routines used by both the compiler and the expression compiler. + */ + +#pragma once + +#include +#include + +namespace dev { +namespace solidity { + +class Type; // forward + +class CompilerUtils +{ +public: + CompilerUtils(CompilerContext& _context): m_context(_context) {} + + /// Loads data from memory to the stack. + /// @param _offset offset in memory (or calldata) + /// @param _bytes number of bytes to load + /// @param _leftAligned if true, store left aligned on stack (otherwise right aligned) + /// @param _fromCalldata if true, load from calldata, not from memory + void loadFromMemory(unsigned _offset, unsigned _bytes = 32, bool _leftAligned = false, bool _fromCalldata = false); + /// Stores data from stack in memory. + /// @param _offset offset in memory + /// @param _bytes number of bytes to store + /// @param _leftAligned if true, data is left aligned on stack (otherwise right aligned) + void storeInMemory(unsigned _offset, unsigned _bytes = 32, bool _leftAligned = false); + + /// Moves the value that is at the top of the stack to a stack variable. + void moveToStackVariable(VariableDeclaration const& _variable); + /// Copies a variable of type @a _type from a stack depth of @a _stackDepth to the top of the stack. + void copyToStackTop(unsigned _stackDepth, Type const& _type); + /// Removes the current value from the top of the stack. + void popStackElement(Type const& _type); + + template + static unsigned getSizeOnStack(std::vector const& _variables); + static unsigned getSizeOnStack(std::vector> const& _variableTypes); + +private: + CompilerContext& m_context; +}; + +template +unsigned CompilerUtils::getSizeOnStack(std::vector const& _variables) +{ + unsigned size = 0; + for (T const& variable: _variables) + size += variable->getType()->getSizeOnStack(); + return size; +} + +} +} diff --git a/libsolidity/Scope.cpp b/libsolidity/DeclarationContainer.cpp similarity index 72% rename from libsolidity/Scope.cpp rename to libsolidity/DeclarationContainer.cpp index 540c41204..c7081bc78 100644 --- a/libsolidity/Scope.cpp +++ b/libsolidity/DeclarationContainer.cpp @@ -20,7 +20,7 @@ * Scope - object that holds declaration of names. */ -#include +#include #include namespace dev @@ -28,21 +28,21 @@ namespace dev namespace solidity { -bool Scope::registerDeclaration(Declaration& _declaration) +bool DeclarationContainer::registerDeclaration(Declaration const& _declaration, bool _update) { - if (m_declarations.find(_declaration.getName()) != m_declarations.end()) + if (!_update && m_declarations.find(_declaration.getName()) != m_declarations.end()) return false; m_declarations[_declaration.getName()] = &_declaration; return true; } -Declaration* Scope::resolveName(ASTString const& _name, bool _recursive) const +Declaration const* DeclarationContainer::resolveName(ASTString const& _name, bool _recursive) const { auto result = m_declarations.find(_name); if (result != m_declarations.end()) return result->second; - if (_recursive && m_enclosingScope) - return m_enclosingScope->resolveName(_name, true); + if (_recursive && m_enclosingContainer) + return m_enclosingContainer->resolveName(_name, true); return nullptr; } diff --git a/libsolidity/Scope.h b/libsolidity/DeclarationContainer.h similarity index 64% rename from libsolidity/Scope.h rename to libsolidity/DeclarationContainer.h index 637c2d5ce..c0a0b42c7 100644 --- a/libsolidity/Scope.h +++ b/libsolidity/DeclarationContainer.h @@ -36,19 +36,22 @@ namespace solidity * Container that stores mappings betwee names and declarations. It also contains a link to the * enclosing scope. */ -class Scope +class DeclarationContainer { public: - explicit Scope(Scope* _enclosingScope = nullptr): m_enclosingScope(_enclosingScope) {} + explicit DeclarationContainer(Declaration const* _enclosingDeclaration = nullptr, + DeclarationContainer const* _enclosingContainer = nullptr): + m_enclosingDeclaration(_enclosingDeclaration), m_enclosingContainer(_enclosingContainer) {} /// Registers the declaration in the scope unless its name is already declared. Returns true iff /// it was not yet declared. - bool registerDeclaration(Declaration& _declaration); - Declaration* resolveName(ASTString const& _name, bool _recursive = false) const; - Scope* getEnclosingScope() const { return m_enclosingScope; } + bool registerDeclaration(Declaration const& _declaration, bool _update = false); + Declaration const* resolveName(ASTString const& _name, bool _recursive = false) const; + Declaration const* getEnclosingDeclaration() const { return m_enclosingDeclaration; } private: - Scope* m_enclosingScope; - std::map m_declarations; + Declaration const* m_enclosingDeclaration; + DeclarationContainer const* m_enclosingContainer; + std::map m_declarations; }; } diff --git a/libsolidity/Exceptions.h b/libsolidity/Exceptions.h index 1903c1dc2..14f919772 100644 --- a/libsolidity/Exceptions.h +++ b/libsolidity/Exceptions.h @@ -36,8 +36,8 @@ struct TypeError: virtual Exception {}; struct DeclarationError: virtual Exception {}; struct CompilerError: virtual Exception {}; struct InternalCompilerError: virtual Exception {}; +struct DocstringParsingError: virtual Exception {}; -typedef boost::error_info errinfo_sourcePosition; typedef boost::error_info errinfo_sourceLocation; } diff --git a/libsolidity/ExpressionCompiler.cpp b/libsolidity/ExpressionCompiler.cpp index 05bbb0916..3beb423de 100644 --- a/libsolidity/ExpressionCompiler.cpp +++ b/libsolidity/ExpressionCompiler.cpp @@ -22,18 +22,20 @@ #include #include +#include #include #include #include +#include using namespace std; namespace dev { namespace solidity { -void ExpressionCompiler::compileExpression(CompilerContext& _context, Expression& _expression) +void ExpressionCompiler::compileExpression(CompilerContext& _context, Expression const& _expression, bool _optimize) { - ExpressionCompiler compiler(_context); + ExpressionCompiler compiler(_context, _optimize); _expression.accept(compiler); } @@ -44,24 +46,29 @@ void ExpressionCompiler::appendTypeConversion(CompilerContext& _context, compiler.appendTypeConversion(_typeOnStack, _targetType); } -bool ExpressionCompiler::visit(Assignment& _assignment) +bool ExpressionCompiler::visit(Assignment const& _assignment) { _assignment.getRightHandSide().accept(*this); appendTypeConversion(*_assignment.getRightHandSide().getType(), *_assignment.getType()); - m_currentLValue.reset(); _assignment.getLeftHandSide().accept(*this); + if (asserts(m_currentLValue.isValid())) + BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("LValue not retrieved.")); Token::Value op = _assignment.getAssignmentOperator(); if (op != Token::ASSIGN) // compound assignment + { + if (m_currentLValue.storesReferenceOnStack()) + m_context << eth::Instruction::SWAP1 << eth::Instruction::DUP2; + m_currentLValue.retrieveValue(_assignment, true); appendOrdinaryBinaryOperatorCode(Token::AssignmentToBinaryOp(op), *_assignment.getType()); - else - m_context << eth::Instruction::POP; + } + m_currentLValue.storeValue(_assignment); + m_currentLValue.reset(); - storeInLValue(_assignment); return false; } -void ExpressionCompiler::endVisit(UnaryOperation& _unaryOperation) +void ExpressionCompiler::endVisit(UnaryOperation const& _unaryOperation) { //@todo type checking and creating code for an operator should be in the same place: // the operator should know how to convert itself and to which types it applies, so @@ -76,23 +83,39 @@ void ExpressionCompiler::endVisit(UnaryOperation& _unaryOperation) m_context << eth::Instruction::NOT; break; case Token::DELETE: // delete - { - // a -> a xor a (= 0). // @todo semantics change for complex types - m_context << eth::Instruction::DUP1 << eth::Instruction::XOR; - storeInLValue(_unaryOperation); + if (asserts(m_currentLValue.isValid())) + BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("LValue not retrieved.")); + + m_context << u256(0); + if (m_currentLValue.storesReferenceOnStack()) + m_context << eth::Instruction::SWAP1; + m_currentLValue.storeValue(_unaryOperation); + m_currentLValue.reset(); break; - } case Token::INC: // ++ (pre- or postfix) case Token::DEC: // -- (pre- or postfix) + if (asserts(m_currentLValue.isValid())) + BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("LValue not retrieved.")); + m_currentLValue.retrieveValue(_unaryOperation); if (!_unaryOperation.isPrefixOperation()) - m_context << eth::Instruction::DUP1; + { + if (m_currentLValue.storesReferenceOnStack()) + m_context << eth::Instruction::SWAP1 << eth::Instruction::DUP2; + else + m_context << eth::Instruction::DUP1; + } m_context << u256(1); if (_unaryOperation.getOperator() == Token::INC) m_context << eth::Instruction::ADD; else m_context << eth::Instruction::SWAP1 << eth::Instruction::SUB; // @todo avoid the swap - storeInLValue(_unaryOperation, !_unaryOperation.isPrefixOperation()); + // Stack for prefix: [ref] (*ref)+-1 + // Stack for postfix: *ref [ref] (*ref)+-1 + if (m_currentLValue.storesReferenceOnStack()) + m_context << eth::Instruction::SWAP1; + m_currentLValue.storeValue(_unaryOperation, !_unaryOperation.isPrefixOperation()); + m_currentLValue.reset(); break; case Token::ADD: // + // unary add, so basically no-op @@ -106,10 +129,10 @@ void ExpressionCompiler::endVisit(UnaryOperation& _unaryOperation) } } -bool ExpressionCompiler::visit(BinaryOperation& _binaryOperation) +bool ExpressionCompiler::visit(BinaryOperation const& _binaryOperation) { - Expression& leftExpression = _binaryOperation.getLeftExpression(); - Expression& rightExpression = _binaryOperation.getRightExpression(); + Expression const& leftExpression = _binaryOperation.getLeftExpression(); + Expression const& rightExpression = _binaryOperation.getRightExpression(); Type const& commonType = _binaryOperation.getCommonType(); Token::Value const op = _binaryOperation.getOperator(); @@ -122,10 +145,24 @@ bool ExpressionCompiler::visit(BinaryOperation& _binaryOperation) if (Token::isCompareOp(op) || op == Token::DIV || op == Token::MOD) cleanupNeeded = true; - rightExpression.accept(*this); - appendTypeConversion(*rightExpression.getType(), commonType, cleanupNeeded); - leftExpression.accept(*this); - appendTypeConversion(*leftExpression.getType(), commonType, cleanupNeeded); + // for commutative operators, push the literal as late as possible to allow improved optimization + //@todo this has to be extended for literal expressions + bool swap = (m_optimize && Token::isCommutativeOp(op) && dynamic_cast(&rightExpression) + && !dynamic_cast(&leftExpression)); + if (swap) + { + leftExpression.accept(*this); + appendTypeConversion(*leftExpression.getType(), commonType, cleanupNeeded); + rightExpression.accept(*this); + appendTypeConversion(*rightExpression.getType(), commonType, cleanupNeeded); + } + else + { + rightExpression.accept(*this); + appendTypeConversion(*rightExpression.getType(), commonType, cleanupNeeded); + leftExpression.accept(*this); + appendTypeConversion(*leftExpression.getType(), commonType, cleanupNeeded); + } if (Token::isCompareOp(op)) appendCompareOperatorCode(op, commonType); else @@ -136,95 +173,269 @@ bool ExpressionCompiler::visit(BinaryOperation& _binaryOperation) return false; } -bool ExpressionCompiler::visit(FunctionCall& _functionCall) +bool ExpressionCompiler::visit(FunctionCall const& _functionCall) { + using Location = FunctionType::Location; if (_functionCall.isTypeConversion()) { - //@todo we only have integers and bools for now which cannot be explicitly converted + //@todo struct construction if (asserts(_functionCall.getArguments().size() == 1)) BOOST_THROW_EXCEPTION(InternalCompilerError()); - Expression& firstArgument = *_functionCall.getArguments().front(); + Expression const& firstArgument = *_functionCall.getArguments().front(); firstArgument.accept(*this); - appendTypeConversion(*firstArgument.getType(), *_functionCall.getType()); + if (firstArgument.getType()->getCategory() == Type::Category::CONTRACT && + _functionCall.getType()->getCategory() == Type::Category::INTEGER) + { + // explicit type conversion contract -> address, nothing to do. + } + else + appendTypeConversion(*firstArgument.getType(), *_functionCall.getType()); } else { - // Calling convention: Caller pushes return address and arguments - // Callee removes them and pushes return values - m_currentLValue.reset(); - _functionCall.getExpression().accept(*this); - if (asserts(m_currentLValue.isInCode())) - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Code reference expected.")); - eth::AssemblyItem functionTag(eth::PushTag, m_currentLValue.location); - - FunctionDefinition const& function = dynamic_cast(*_functionCall.getExpression().getType()).getFunction(); - - eth::AssemblyItem returnLabel = m_context.pushNewTag(); - std::vector> const& arguments = _functionCall.getArguments(); - if (asserts(arguments.size() == function.getParameters().size())) + FunctionType const& function = dynamic_cast(*_functionCall.getExpression().getType()); + std::vector> arguments = _functionCall.getArguments(); + if (asserts(arguments.size() == function.getParameterTypes().size())) BOOST_THROW_EXCEPTION(InternalCompilerError()); - for (unsigned i = 0; i < arguments.size(); ++i) + + switch (function.getLocation()) { - arguments[i]->accept(*this); - appendTypeConversion(*arguments[i]->getType(), *function.getParameters()[i]->getType()); + case Location::INTERNAL: + { + // Calling convention: Caller pushes return address and arguments + // Callee removes them and pushes return values + + eth::AssemblyItem returnLabel = m_context.pushNewTag(); + for (unsigned i = 0; i < arguments.size(); ++i) + { + arguments[i]->accept(*this); + appendTypeConversion(*arguments[i]->getType(), *function.getParameterTypes()[i]); + } + _functionCall.getExpression().accept(*this); + + m_context.appendJump(); + m_context << returnLabel; + + unsigned returnParametersSize = CompilerUtils::getSizeOnStack(function.getReturnParameterTypes()); + // callee adds return parameters, but removes arguments and return label + m_context.adjustStackOffset(returnParametersSize - CompilerUtils::getSizeOnStack(arguments) - 1); + + // @todo for now, the return value of a function is its first return value, so remove + // all others + for (unsigned i = 1; i < function.getReturnParameterTypes().size(); ++i) + CompilerUtils(m_context).popStackElement(*function.getReturnParameterTypes()[i]); + break; + } + case Location::EXTERNAL: + { + unsigned dataOffset = 1; // reserve one byte for the function index + for (unsigned i = 0; i < arguments.size(); ++i) + { + arguments[i]->accept(*this); + Type const& type = *function.getParameterTypes()[i]; + appendTypeConversion(*arguments[i]->getType(), type); + unsigned const numBytes = type.getCalldataEncodedSize(); + if (numBytes == 0 || numBytes > 32) + BOOST_THROW_EXCEPTION(CompilerError() + << errinfo_sourceLocation(arguments[i]->getLocation()) + << errinfo_comment("Type " + type.toString() + " not yet supported.")); + bool const leftAligned = type.getCategory() == Type::Category::STRING; + CompilerUtils(m_context).storeInMemory(dataOffset, numBytes, leftAligned); + dataOffset += numBytes; + } + //@todo only return the first return value for now + Type const* firstType = function.getReturnParameterTypes().empty() ? nullptr : + function.getReturnParameterTypes().front().get(); + unsigned retSize = firstType ? firstType->getCalldataEncodedSize() : 0; + // CALL arguments: outSize, outOff, inSize, inOff, value, addr, gas (stack top) + m_context << u256(retSize) << u256(0) << u256(dataOffset) << u256(0) << u256(0); + _functionCall.getExpression().accept(*this); // pushes addr and function index + m_context << u256(0) << eth::Instruction::MSTORE8 + << u256(25) << eth::Instruction::GAS << eth::Instruction::SUB + << eth::Instruction::CALL + << eth::Instruction::POP; // @todo do not ignore failure indicator + if (retSize > 0) + { + bool const leftAligned = firstType->getCategory() == Type::Category::STRING; + CompilerUtils(m_context).loadFromMemory(0, retSize, leftAligned); + } + break; + } + case Location::SEND: + m_context << u256(0) << u256(0) << u256(0) << u256(0); + arguments.front()->accept(*this); + //@todo might not be necessary + appendTypeConversion(*arguments.front()->getType(), *function.getParameterTypes().front(), true); + _functionCall.getExpression().accept(*this); + m_context << u256(25) << eth::Instruction::GAS << eth::Instruction::SUB + << eth::Instruction::CALL + << eth::Instruction::POP; + break; + case Location::SUICIDE: + arguments.front()->accept(*this); + //@todo might not be necessary + appendTypeConversion(*arguments.front()->getType(), *function.getParameterTypes().front(), true); + m_context << eth::Instruction::SUICIDE; + break; + case Location::SHA3: + arguments.front()->accept(*this); + appendTypeConversion(*arguments.front()->getType(), *function.getParameterTypes().front(), true); + // @todo move this once we actually use memory + CompilerUtils(m_context).storeInMemory(0); + m_context << u256(32) << u256(0) << eth::Instruction::SHA3; + break; + case Location::ECRECOVER: + case Location::SHA256: + case Location::RIPEMD160: + { + static const map contractAddresses{{Location::ECRECOVER, 1}, + {Location::SHA256, 2}, + {Location::RIPEMD160, 3}}; + u256 contractAddress = contractAddresses.find(function.getLocation())->second; + // @todo later, combine this code with external function call + for (unsigned i = 0; i < arguments.size(); ++i) + { + arguments[i]->accept(*this); + appendTypeConversion(*arguments[i]->getType(), *function.getParameterTypes()[i], true); + // @todo move this once we actually use memory + CompilerUtils(m_context).storeInMemory(i * 32); + } + m_context << u256(32) << u256(0) << u256(arguments.size() * 32) << u256(0) << u256(0) + << contractAddress << u256(500) //@todo determine actual gas requirement + << eth::Instruction::CALL + << eth::Instruction::POP; + CompilerUtils(m_context).loadFromMemory(0); + break; + } + default: + BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Invalid function type.")); } - - m_context.appendJumpTo(functionTag); - m_context << returnLabel; - - // callee adds return parameters, but removes arguments and return label - m_context.adjustStackOffset(function.getReturnParameters().size() - arguments.size() - 1); - - // @todo for now, the return value of a function is its first return value, so remove - // all others - for (unsigned i = 1; i < function.getReturnParameters().size(); ++i) - m_context << eth::Instruction::POP; } return false; } -void ExpressionCompiler::endVisit(MemberAccess&) +void ExpressionCompiler::endVisit(MemberAccess const& _memberAccess) { - + ASTString const& member = _memberAccess.getMemberName(); + switch (_memberAccess.getExpression().getType()->getCategory()) + { + case Type::Category::INTEGER: + if (member == "balance") + { + appendTypeConversion(*_memberAccess.getExpression().getType(), + IntegerType(0, IntegerType::Modifier::ADDRESS), true); + m_context << eth::Instruction::BALANCE; + } + else if (member == "send") + { + appendTypeConversion(*_memberAccess.getExpression().getType(), + IntegerType(0, IntegerType::Modifier::ADDRESS), true); + } + else + BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Invalid member access to integer.")); + break; + case Type::Category::CONTRACT: + { + ContractType const& type = dynamic_cast(*_memberAccess.getExpression().getType()); + m_context << type.getFunctionIndex(member); + break; + } + case Type::Category::MAGIC: + // we can ignore the kind of magic and only look at the name of the member + if (member == "coinbase") + m_context << eth::Instruction::COINBASE; + else if (member == "timestamp") + m_context << eth::Instruction::TIMESTAMP; + else if (member == "prevhash") + m_context << eth::Instruction::PREVHASH; + else if (member == "difficulty") + m_context << eth::Instruction::DIFFICULTY; + else if (member == "number") + m_context << eth::Instruction::NUMBER; + else if (member == "gaslimit") + m_context << eth::Instruction::GASLIMIT; + else if (member == "sender") + m_context << eth::Instruction::CALLER; + else if (member == "value") + m_context << eth::Instruction::CALLVALUE; + else if (member == "origin") + m_context << eth::Instruction::ORIGIN; + else if (member == "gas") + m_context << eth::Instruction::GAS; + else if (member == "gasprice") + m_context << eth::Instruction::GASPRICE; + else + BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unknown magic member.")); + break; + case Type::Category::STRUCT: + { + StructType const& type = dynamic_cast(*_memberAccess.getExpression().getType()); + m_context << type.getStorageOffsetOfMember(member) << eth::Instruction::ADD; + m_currentLValue = LValue(m_context, LValue::STORAGE, *_memberAccess.getType()); + m_currentLValue.retrieveValueIfLValueNotRequested(_memberAccess); + break; + } + default: + BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Member access to unknown type.")); + } } -void ExpressionCompiler::endVisit(IndexAccess&) +bool ExpressionCompiler::visit(IndexAccess const& _indexAccess) { + _indexAccess.getBaseExpression().accept(*this); + _indexAccess.getIndexExpression().accept(*this); + appendTypeConversion(*_indexAccess.getIndexExpression().getType(), + *dynamic_cast(*_indexAccess.getBaseExpression().getType()).getKeyType(), + true); + // @todo move this once we actually use memory + CompilerUtils(m_context).storeInMemory(0); + CompilerUtils(m_context).storeInMemory(32); + m_context << u256(64) << u256(0) << eth::Instruction::SHA3; + + m_currentLValue = LValue(m_context, LValue::STORAGE, *_indexAccess.getType()); + m_currentLValue.retrieveValueIfLValueNotRequested(_indexAccess); + return false; } -void ExpressionCompiler::endVisit(Identifier& _identifier) +void ExpressionCompiler::endVisit(Identifier const& _identifier) { Declaration const* declaration = _identifier.getReferencedDeclaration(); - if (m_context.isLocalVariable(declaration)) - m_currentLValue = LValueLocation(LValueLocation::STACK, - m_context.getBaseStackOffsetOfVariable(*declaration)); - else if (m_context.isStateVariable(declaration)) - m_currentLValue = LValueLocation(LValueLocation::STORAGE, - m_context.getStorageLocationOfVariable(*declaration)); - else if (m_context.isFunctionDefinition(declaration)) - m_currentLValue = LValueLocation(LValueLocation::CODE, - m_context.getFunctionEntryLabel(dynamic_cast(*declaration)).data()); - else - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Identifier type not supported or identifier not found.")); - - retrieveLValueValue(_identifier); + if (MagicVariableDeclaration const* magicVar = dynamic_cast(declaration)) + { + if (magicVar->getType()->getCategory() == Type::Category::CONTRACT) // must be "this" + m_context << eth::Instruction::ADDRESS; + return; + } + if (FunctionDefinition const* functionDef = dynamic_cast(declaration)) + { + m_context << m_context.getFunctionEntryLabel(*functionDef).pushTag(); + return; + } + if (dynamic_cast(declaration)) + { + m_currentLValue.fromIdentifier(_identifier, *declaration); + m_currentLValue.retrieveValueIfLValueNotRequested(_identifier); + return; + } + BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Identifier type not expected in expression context.")); } -void ExpressionCompiler::endVisit(Literal& _literal) +void ExpressionCompiler::endVisit(Literal const& _literal) { switch (_literal.getType()->getCategory()) { case Type::Category::INTEGER: case Type::Category::BOOL: + case Type::Category::STRING: m_context << _literal.getType()->literalValue(_literal); break; default: - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Only integer and boolean literals implemented for now.")); + BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Only integer, boolean and string literals implemented for now.")); } } -void ExpressionCompiler::appendAndOrOperatorCode(BinaryOperation& _binaryOperation) +void ExpressionCompiler::appendAndOrOperatorCode(BinaryOperation const& _binaryOperation) { Token::Value const op = _binaryOperation.getOperator(); if (asserts(op == Token::OR || op == Token::AND)) @@ -356,6 +567,11 @@ void ExpressionCompiler::appendTypeConversion(Type const& _typeOnStack, Type con return; if (_typeOnStack.getCategory() == Type::Category::INTEGER) appendHighBitsCleanup(dynamic_cast(_typeOnStack)); + else if (_typeOnStack.getCategory() == Type::Category::STRING) + { + // nothing to do, strings are high-order-bit-aligned + //@todo clear lower-order bytes if we allow explicit conversion to shorter strings + } else if (_typeOnStack != _targetType) // All other types should not be convertible to non-equal types. BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Invalid type conversion requested.")); @@ -371,66 +587,138 @@ void ExpressionCompiler::appendHighBitsCleanup(IntegerType const& _typeOnStack) m_context << ((u256(1) << _typeOnStack.getNumBits()) - 1) << eth::Instruction::AND; } -void ExpressionCompiler::retrieveLValueValue(Expression const& _expression) +ExpressionCompiler::LValue::LValue(CompilerContext& _compilerContext, LValueType _type, Type const& _dataType, + unsigned _baseStackOffset): + m_context(&_compilerContext), m_type(_type), m_baseStackOffset(_baseStackOffset), + m_stackSize(_dataType.getSizeOnStack()) { - switch (m_currentLValue.locationType) +} + +void ExpressionCompiler::LValue::retrieveValue(Expression const& _expression, bool _remove) const +{ + switch (m_type) { - case LValueLocation::CODE: - // not stored on the stack - break; - case LValueLocation::STACK: + case STACK: { - unsigned stackPos = m_context.baseToCurrentStackOffset(unsigned(m_currentLValue.location)); + unsigned stackPos = m_context->baseToCurrentStackOffset(unsigned(m_baseStackOffset)); if (stackPos >= 15) //@todo correct this by fetching earlier or moving to memory BOOST_THROW_EXCEPTION(CompilerError() << errinfo_sourceLocation(_expression.getLocation()) << errinfo_comment("Stack too deep.")); - m_context << eth::dupInstruction(stackPos + 1); + for (unsigned i = 0; i < m_stackSize; ++i) + *m_context << eth::dupInstruction(stackPos + 1); break; } - case LValueLocation::STORAGE: - m_context << m_currentLValue.location << eth::Instruction::SLOAD; + case STORAGE: + if (!_expression.getType()->isValueType()) + break; // no distinction between value and reference for non-value types + if (!_remove) + *m_context << eth::Instruction::DUP1; + if (m_stackSize == 1) + *m_context << eth::Instruction::SLOAD; + else + for (unsigned i = 0; i < m_stackSize; ++i) + { + *m_context << eth::Instruction::DUP1 << eth::Instruction::SLOAD << eth::Instruction::SWAP1; + if (i + 1 < m_stackSize) + *m_context << u256(1) << eth::Instruction::ADD; + else + *m_context << eth::Instruction::POP; + } break; - case LValueLocation::MEMORY: - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Location type not yet implemented.")); + case MEMORY: + if (!_expression.getType()->isValueType()) + break; // no distinction between value and reference for non-value types + BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_sourceLocation(_expression.getLocation()) + << errinfo_comment("Location type not yet implemented.")); break; default: - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unsupported location type.")); + BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_sourceLocation(_expression.getLocation()) + << errinfo_comment("Unsupported location type.")); break; } } -void ExpressionCompiler::storeInLValue(Expression const& _expression, bool _move) +void ExpressionCompiler::LValue::storeValue(Expression const& _expression, bool _move) const { - switch (m_currentLValue.locationType) + switch (m_type) { - case LValueLocation::STACK: + case STACK: { - unsigned stackPos = m_context.baseToCurrentStackOffset(unsigned(m_currentLValue.location)); - if (stackPos > 16) + unsigned stackDiff = m_context->baseToCurrentStackOffset(unsigned(m_baseStackOffset)) - m_stackSize + 1; + if (stackDiff > 16) BOOST_THROW_EXCEPTION(CompilerError() << errinfo_sourceLocation(_expression.getLocation()) << errinfo_comment("Stack too deep.")); - else if (stackPos > 0) - m_context << eth::swapInstruction(stackPos) << eth::Instruction::POP; + else if (stackDiff > 0) + for (unsigned i = 0; i < m_stackSize; ++i) + *m_context << eth::swapInstruction(stackDiff) << eth::Instruction::POP; if (!_move) - retrieveLValueValue(_expression); + retrieveValue(_expression); break; } - case LValueLocation::STORAGE: - if (!_move) - m_context << eth::Instruction::DUP1; - m_context << m_currentLValue.location << eth::Instruction::SSTORE; - break; - case LValueLocation::CODE: - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Location type does not support assignment.")); + case LValue::STORAGE: + if (!_expression.getType()->isValueType()) + break; // no distinction between value and reference for non-value types + // stack layout: value value ... value ref + if (!_move) // copy values + { + if (m_stackSize + 1 > 16) + BOOST_THROW_EXCEPTION(CompilerError() << errinfo_sourceLocation(_expression.getLocation()) + << errinfo_comment("Stack too deep.")); + for (unsigned i = 0; i < m_stackSize; ++i) + *m_context << eth::dupInstruction(m_stackSize + 1) << eth::Instruction::SWAP1; + } + if (m_stackSize > 0) // store high index value first + *m_context << u256(m_stackSize - 1) << eth::Instruction::ADD; + for (unsigned i = 0; i < m_stackSize; ++i) + { + if (i + 1 >= m_stackSize) + *m_context << eth::Instruction::SSTORE; + else + // v v ... v v r+x + *m_context << eth::Instruction::SWAP1 << eth::Instruction::DUP2 + << eth::Instruction::SSTORE + << u256(1) << eth::Instruction::SWAP1 << eth::Instruction::SUB; + } break; - case LValueLocation::MEMORY: - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Location type not yet implemented.")); + case LValue::MEMORY: + if (!_expression.getType()->isValueType()) + break; // no distinction between value and reference for non-value types + BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_sourceLocation(_expression.getLocation()) + << errinfo_comment("Location type not yet implemented.")); break; default: - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unsupported location type.")); + BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_sourceLocation(_expression.getLocation()) + << errinfo_comment("Unsupported location type.")); break; } } +void ExpressionCompiler::LValue::retrieveValueIfLValueNotRequested(Expression const& _expression) +{ + if (!_expression.lvalueRequested()) + { + retrieveValue(_expression, true); + reset(); + } +} + +void ExpressionCompiler::LValue::fromIdentifier(Identifier const& _identifier, Declaration const& _declaration) +{ + m_stackSize = _identifier.getType()->getSizeOnStack(); + if (m_context->isLocalVariable(&_declaration)) + { + m_type = STACK; + m_baseStackOffset = m_context->getBaseStackOffsetOfVariable(_declaration); + } + else if (m_context->isStateVariable(&_declaration)) + { + m_type = STORAGE; + *m_context << m_context->getStorageLocationOfVariable(_declaration); + } + else + BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_sourceLocation(_identifier.getLocation()) + << errinfo_comment("Identifier type not supported or identifier not found.")); +} + } } diff --git a/libsolidity/ExpressionCompiler.h b/libsolidity/ExpressionCompiler.h index bd5a9f866..c0b173d46 100644 --- a/libsolidity/ExpressionCompiler.h +++ b/libsolidity/ExpressionCompiler.h @@ -20,6 +20,7 @@ * Solidity AST to EVM bytecode compiler for expressions. */ +#include #include #include @@ -30,39 +31,42 @@ class AssemblyItem; // forward } namespace solidity { -class CompilerContext; // forward -class Type; // forward -class IntegerType; // forward +// forward declarations +class CompilerContext; +class Type; +class IntegerType; +class StaticStringType; /** * Compiler for expressions, i.e. converts an AST tree whose root is an Expression into a stream * of EVM instructions. It needs a compiler context that is the same for the whole compilation * unit. */ -class ExpressionCompiler: private ASTVisitor +class ExpressionCompiler: private ASTConstVisitor { public: /// Compile the given @a _expression into the @a _context. - static void compileExpression(CompilerContext& _context, Expression& _expression); + static void compileExpression(CompilerContext& _context, Expression const& _expression, bool _optimize = false); /// Appends code to remove dirty higher order bits in case of an implicit promotion to a wider type. static void appendTypeConversion(CompilerContext& _context, Type const& _typeOnStack, Type const& _targetType); private: - ExpressionCompiler(CompilerContext& _compilerContext): m_context(_compilerContext) {} - - virtual bool visit(Assignment& _assignment) override; - virtual void endVisit(UnaryOperation& _unaryOperation) override; - virtual bool visit(BinaryOperation& _binaryOperation) override; - virtual bool visit(FunctionCall& _functionCall) override; - virtual void endVisit(MemberAccess& _memberAccess) override; - virtual void endVisit(IndexAccess& _indexAccess) override; - virtual void endVisit(Identifier& _identifier) override; - virtual void endVisit(Literal& _literal) override; + explicit ExpressionCompiler(CompilerContext& _compilerContext, bool _optimize = false): + m_optimize(_optimize), m_context(_compilerContext), m_currentLValue(m_context) {} + + virtual bool visit(Assignment const& _assignment) override; + virtual void endVisit(UnaryOperation const& _unaryOperation) override; + virtual bool visit(BinaryOperation const& _binaryOperation) override; + virtual bool visit(FunctionCall const& _functionCall) override; + virtual void endVisit(MemberAccess const& _memberAccess) override; + virtual bool visit(IndexAccess const& _indexAccess) override; + virtual void endVisit(Identifier const& _identifier) override; + virtual void endVisit(Literal const& _literal) override; ///@{ ///@name Append code for various operator types - void appendAndOrOperatorCode(BinaryOperation& _binaryOperation); + void appendAndOrOperatorCode(BinaryOperation const& _binaryOperation); void appendCompareOperatorCode(Token::Value _operator, Type const& _type); void appendOrdinaryBinaryOperatorCode(Token::Value _operator, Type const& _type); @@ -72,44 +76,66 @@ private: /// @} /// Appends an implicit or explicit type conversion. For now this comprises only erasing - /// higher-order bits (@see appendHighBitCleanup) when widening integer types. + /// higher-order bits (@see appendHighBitCleanup) when widening integer. /// If @a _cleanupNeeded, high order bits cleanup is also done if no type conversion would be /// necessary. void appendTypeConversion(Type const& _typeOnStack, Type const& _targetType, bool _cleanupNeeded = false); //// Appends code that cleans higher-order bits for integer types. void appendHighBitsCleanup(IntegerType const& _typeOnStack); - /// Copies the value of the current lvalue to the top of the stack. - void retrieveLValueValue(Expression const& _expression); - /// Stores the value on top of the stack in the current lvalue. Removes it from the stack if - /// @a _move is true. - void storeInLValue(Expression const& _expression, bool _move = false); - /** - * Location of an lvalue, either in code (for a function) on the stack, in the storage or memory. + * Helper class to store and retrieve lvalues to and from various locations. + * All types except STACK store a reference in a slot on the stack, STACK just + * stores the base stack offset of the variable in @a m_baseStackOffset. */ - struct LValueLocation + class LValue { - enum LocationType { INVALID, CODE, STACK, MEMORY, STORAGE }; - - LValueLocation() { reset(); } - LValueLocation(LocationType _type, u256 const& _location): locationType(_type), location(_location) {} - void reset() { locationType = INVALID; location = 0; } - bool isValid() const { return locationType != INVALID; } - bool isInCode() const { return locationType == CODE; } - bool isInOnStack() const { return locationType == STACK; } - bool isInMemory() const { return locationType == MEMORY; } - bool isInStorage() const { return locationType == STORAGE; } - - LocationType locationType; - /// Depending on the type, this is the id of a tag (code), the base offset of a stack - /// variable (@see CompilerContext::getBaseStackOffsetOfVariable) or the offset in - /// storage or memory. - u256 location; + public: + enum LValueType { NONE, STACK, MEMORY, STORAGE }; + + explicit LValue(CompilerContext& _compilerContext): m_context(&_compilerContext) { reset(); } + LValue(CompilerContext& _compilerContext, LValueType _type, Type const& _dataType, unsigned _baseStackOffset = 0); + + /// Set type according to the declaration and retrieve the reference. + /// @a _expression is the current expression + void fromIdentifier(Identifier const& _identifier, Declaration const& _declaration); + void reset() { m_type = NONE; m_baseStackOffset = 0; } + + bool isValid() const { return m_type != NONE; } + bool isInOnStack() const { return m_type == STACK; } + bool isInMemory() const { return m_type == MEMORY; } + bool isInStorage() const { return m_type == STORAGE; } + + /// @returns true if this lvalue reference type occupies a slot on the stack. + bool storesReferenceOnStack() const { return m_type == STORAGE || m_type == MEMORY; } + + /// Copies the value of the current lvalue to the top of the stack and, if @a _remove is true, + /// also removes the reference from the stack (note that is does not reset the type to @a NONE). + /// @a _expression is the current expression, used for error reporting. + void retrieveValue(Expression const& _expression, bool _remove = false) const; + /// Stores a value (from the stack directly beneath the reference, which is assumed to + /// be on the top of the stack, if any) in the lvalue and removes the reference. + /// Also removes the stored value from the stack if @a _move is + /// true. @a _expression is the current expression, used for error reporting. + void storeValue(Expression const& _expression, bool _move = false) const; + + /// Convenience function to convert the stored reference to a value and reset type to NONE if + /// the reference was not requested by @a _expression. + void retrieveValueIfLValueNotRequested(Expression const& _expression); + + private: + CompilerContext* m_context; + LValueType m_type; + /// If m_type is STACK, this is base stack offset (@see + /// CompilerContext::getBaseStackOffsetOfVariable) of a local variable. + unsigned m_baseStackOffset; + /// Size of the value of this lvalue on the stack. + unsigned m_stackSize; }; - LValueLocation m_currentLValue; + bool m_optimize; CompilerContext& m_context; + LValue m_currentLValue; }; diff --git a/libsolidity/GlobalContext.cpp b/libsolidity/GlobalContext.cpp new file mode 100644 index 000000000..f4805b1f7 --- /dev/null +++ b/libsolidity/GlobalContext.cpp @@ -0,0 +1,100 @@ +/* + This file is part of cpp-ethereum. + + cpp-ethereum is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + cpp-ethereum is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with cpp-ethereum. If not, see . +*/ +/** + * @author Christian + * @date 2014 + * Container of the (implicit and explicit) global objects. + */ + +#include +#include +#include +#include + +using namespace std; + +namespace dev +{ +namespace solidity +{ + +GlobalContext::GlobalContext(): +m_magicVariables(vector>{make_shared("block", make_shared(MagicType::Kind::BLOCK)), + make_shared("msg", make_shared(MagicType::Kind::MSG)), + make_shared("tx", make_shared(MagicType::Kind::TX)), + make_shared("suicide", + make_shared(TypePointers({std::make_shared(0, + IntegerType::Modifier::ADDRESS)}), + TypePointers(), + FunctionType::Location::SUICIDE)), + make_shared("sha3", + make_shared(TypePointers({std::make_shared(256, IntegerType::Modifier::HASH)}), + TypePointers({std::make_shared(256, IntegerType::Modifier::HASH)}), + FunctionType::Location::SHA3)), + make_shared("sha256", + make_shared(TypePointers({std::make_shared(256, IntegerType::Modifier::HASH)}), + TypePointers({std::make_shared(256, IntegerType::Modifier::HASH)}), + FunctionType::Location::SHA256)), + make_shared("ecrecover", + make_shared(TypePointers({std::make_shared(256, IntegerType::Modifier::HASH), + std::make_shared(8, IntegerType::Modifier::HASH), + std::make_shared(256, IntegerType::Modifier::HASH), + std::make_shared(256, IntegerType::Modifier::HASH)}), + TypePointers({std::make_shared(0, IntegerType::Modifier::ADDRESS)}), + FunctionType::Location::ECRECOVER)), + make_shared("ripemd160", + make_shared(TypePointers({std::make_shared(256, IntegerType::Modifier::HASH)}), + TypePointers({std::make_shared(160, IntegerType::Modifier::HASH)}), + FunctionType::Location::RIPEMD160))}) +{ +} + +void GlobalContext::setCurrentContract(ContractDefinition const& _contract) +{ + m_currentContract = &_contract; +} + +vector GlobalContext::getDeclarations() const +{ + vector declarations; + declarations.reserve(m_magicVariables.size() + 1); + for (ASTPointer const& variable: m_magicVariables) + declarations.push_back(variable.get()); + return declarations; +} + +MagicVariableDeclaration const* GlobalContext::getCurrentThis() const +{ + if (!m_thisPointer[m_currentContract]) + m_thisPointer[m_currentContract] = make_shared( + "this", make_shared(*m_currentContract)); + return m_thisPointer[m_currentContract].get(); + +} + +vector GlobalContext::getMagicVariables() const +{ + vector declarations; + declarations.reserve(m_magicVariables.size() + 1); + for (ASTPointer const& variable: m_magicVariables) + declarations.push_back(variable.get()); + declarations.push_back(getCurrentThis()); + return declarations; +} + +} +} diff --git a/libsolidity/GlobalContext.h b/libsolidity/GlobalContext.h new file mode 100644 index 000000000..50a21f702 --- /dev/null +++ b/libsolidity/GlobalContext.h @@ -0,0 +1,64 @@ +/* + This file is part of cpp-ethereum. + + cpp-ethereum is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + cpp-ethereum is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with cpp-ethereum. If not, see . +*/ +/** + * @author Christian + * @date 2014 + * Container of the (implicit and explicit) global objects. + */ + +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace dev +{ +namespace solidity +{ + +class Type; // forward + +/** + * Container for all global objects which look like AST nodes, but are not part of the AST + * that is currently being compiled. + * @note must not be destroyed or moved during compilation as its objects can be referenced from + * other objects. + */ +class GlobalContext: private boost::noncopyable +{ +public: + GlobalContext(); + void setCurrentContract(ContractDefinition const& _contract); + MagicVariableDeclaration const* getCurrentThis() const; + + /// @returns all magic variables. + std::vector getMagicVariables() const; + /// @returns a vector of all implicit global declarations excluding "this". + std::vector getDeclarations() const; + +private: + std::vector> m_magicVariables; + ContractDefinition const* m_currentContract; + std::map> mutable m_thisPointer; +}; + +} +} diff --git a/libsolidity/InterfaceHandler.cpp b/libsolidity/InterfaceHandler.cpp new file mode 100644 index 000000000..f26088afa --- /dev/null +++ b/libsolidity/InterfaceHandler.cpp @@ -0,0 +1,340 @@ + +#include +#include +#include + +namespace dev +{ +namespace solidity +{ + +/* -- public -- */ + +InterfaceHandler::InterfaceHandler() +{ + m_lastTag = DocTagType::NONE; +} + +std::unique_ptr InterfaceHandler::getDocumentation(ContractDefinition& _contractDef, + DocumentationType _type) +{ + switch(_type) + { + case DocumentationType::NATSPEC_USER: + return getUserDocumentation(_contractDef); + case DocumentationType::NATSPEC_DEV: + return getDevDocumentation(_contractDef); + case DocumentationType::ABI_INTERFACE: + return getABIInterface(_contractDef); + } + + BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unknown documentation type")); + return nullptr; +} + +std::unique_ptr InterfaceHandler::getABIInterface(ContractDefinition& _contractDef) +{ + Json::Value methods(Json::arrayValue); + + for (FunctionDefinition const* f: _contractDef.getInterfaceFunctions()) + { + Json::Value method; + Json::Value inputs(Json::arrayValue); + Json::Value outputs(Json::arrayValue); + + auto populateParameters = [](std::vector> const& _vars) + { + Json::Value params(Json::arrayValue); + for (ASTPointer const& var: _vars) + { + Json::Value input; + input["name"] = var->getName(); + input["type"] = var->getType()->toString(); + params.append(input); + } + return params; + }; + + method["name"] = f->getName(); + method["inputs"] = populateParameters(f->getParameters()); + method["outputs"] = populateParameters(f->getReturnParameters()); + methods.append(method); + } + return std::unique_ptr(new std::string(m_writer.write(methods))); +} + +std::unique_ptr InterfaceHandler::getUserDocumentation(ContractDefinition& _contractDef) +{ + Json::Value doc; + Json::Value methods(Json::objectValue); + + for (FunctionDefinition const* f: _contractDef.getInterfaceFunctions()) + { + Json::Value user; + auto strPtr = f->getDocumentation(); + if (strPtr) + { + resetUser(); + parseDocString(*strPtr, CommentOwner::FUNCTION); + if (!m_notice.empty()) + {// since @notice is the only user tag if missing function should not appear + user["notice"] = Json::Value(m_notice); + methods[f->getName()] = user; + } + } + } + doc["methods"] = methods; + + return std::unique_ptr(new std::string(m_writer.write(doc))); +} + +std::unique_ptr InterfaceHandler::getDevDocumentation(ContractDefinition& _contractDef) +{ + // LTODO: Somewhere in this function warnings for mismatch of param names + // should be thrown + Json::Value doc; + Json::Value methods(Json::objectValue); + + auto contractDoc = _contractDef.getDocumentation(); + if (contractDoc) + { + m_contractAuthor.clear(); + m_title.clear(); + parseDocString(*contractDoc, CommentOwner::CONTRACT); + + if (!m_contractAuthor.empty()) + doc["author"] = m_contractAuthor; + + if (!m_title.empty()) + doc["title"] = m_title; + } + + for (FunctionDefinition const* f: _contractDef.getInterfaceFunctions()) + { + Json::Value method; + auto strPtr = f->getDocumentation(); + if (strPtr) + { + resetDev(); + parseDocString(*strPtr, CommentOwner::FUNCTION); + + if (!m_dev.empty()) + method["details"] = Json::Value(m_dev); + + if (!m_author.empty()) + method["author"] = m_author; + + Json::Value params(Json::objectValue); + for (auto const& pair: m_params) + params[pair.first] = pair.second; + + if (!m_params.empty()) + method["params"] = params; + + if (!m_return.empty()) + method["return"] = m_return; + + if (!method.empty()) // add the function, only if we have any documentation to add + methods[f->getName()] = method; + } + } + doc["methods"] = methods; + + return std::unique_ptr(new std::string(m_writer.write(doc))); +} + +/* -- private -- */ +void InterfaceHandler::resetUser() +{ + m_notice.clear(); +} + +void InterfaceHandler::resetDev() +{ + m_dev.clear(); + m_author.clear(); + m_return.clear(); + m_params.clear(); +} + +static inline std::string::const_iterator skipLineOrEOS(std::string::const_iterator _nlPos, + std::string::const_iterator _end) +{ + return (_nlPos == _end) ? _end : ++_nlPos; +} + +std::string::const_iterator InterfaceHandler::parseDocTagLine(std::string::const_iterator _pos, + std::string::const_iterator _end, + std::string& _tagString, + DocTagType _tagType) +{ + auto nlPos = std::find(_pos, _end, '\n'); + std::copy(_pos, nlPos, back_inserter(_tagString)); + m_lastTag = _tagType; + return skipLineOrEOS(nlPos, _end); +} + +std::string::const_iterator InterfaceHandler::parseDocTagParam(std::string::const_iterator _pos, + std::string::const_iterator _end) +{ + // find param name + auto currPos = std::find(_pos, _end, ' '); + if (currPos == _end) + BOOST_THROW_EXCEPTION(DocstringParsingError() << errinfo_comment("End of param name not found" + std::string(_pos, _end))); + + + auto paramName = std::string(_pos, currPos); + + currPos += 1; + auto nlPos = std::find(currPos, _end, '\n'); + auto paramDesc = std::string(currPos, nlPos); + m_params.push_back(std::make_pair(paramName, paramDesc)); + + m_lastTag = DocTagType::PARAM; + return skipLineOrEOS(nlPos, _end); +} + +std::string::const_iterator InterfaceHandler::appendDocTagParam(std::string::const_iterator _pos, + std::string::const_iterator _end) +{ + // Should never be called with an empty vector + if (asserts(!m_params.empty())) + BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Internal: Tried to append to empty parameter")); + + auto pair = m_params.back(); + pair.second += " "; + auto nlPos = std::find(_pos, _end, '\n'); + std::copy(_pos, nlPos, back_inserter(pair.second)); + + m_params.at(m_params.size() - 1) = pair; + + return skipLineOrEOS(nlPos, _end); +} + +std::string::const_iterator InterfaceHandler::parseDocTag(std::string::const_iterator _pos, + std::string::const_iterator _end, + std::string const& _tag, + CommentOwner _owner) +{ + // LTODO: need to check for @(start of a tag) between here and the end of line + // for all cases. Also somehow automate list of acceptable tags for each + // language construct since current way does not scale well. + if (m_lastTag == DocTagType::NONE || _tag != "") + { + if (_tag == "dev") + return parseDocTagLine(_pos, _end, m_dev, DocTagType::DEV); + else if (_tag == "notice") + return parseDocTagLine(_pos, _end, m_notice, DocTagType::NOTICE); + else if (_tag == "return") + return parseDocTagLine(_pos, _end, m_return, DocTagType::RETURN); + else if (_tag == "author") + { + if (_owner == CommentOwner::CONTRACT) + return parseDocTagLine(_pos, _end, m_contractAuthor, DocTagType::AUTHOR); + else if (_owner == CommentOwner::FUNCTION) + return parseDocTagLine(_pos, _end, m_author, DocTagType::AUTHOR); + else + // LTODO: for now this else makes no sense but later comments will go to more language constructs + BOOST_THROW_EXCEPTION(DocstringParsingError() << errinfo_comment("@author tag is legal only for contracts")); + } + else if (_tag == "title") + { + if (_owner == CommentOwner::CONTRACT) + return parseDocTagLine(_pos, _end, m_title, DocTagType::TITLE); + else + // LTODO: Unknown tag, throw some form of warning and not just an exception + BOOST_THROW_EXCEPTION(DocstringParsingError() << errinfo_comment("@title tag is legal only for contracts")); + } + else if (_tag == "param") + return parseDocTagParam(_pos, _end); + else + // LTODO: Unknown tag, throw some form of warning and not just an exception + BOOST_THROW_EXCEPTION(DocstringParsingError() << errinfo_comment("Unknown tag " + _tag + " encountered")); + } + else + return appendDocTag(_pos, _end, _owner); +} + +std::string::const_iterator InterfaceHandler::appendDocTag(std::string::const_iterator _pos, + std::string::const_iterator _end, + CommentOwner _owner) +{ + switch (m_lastTag) + { + case DocTagType::DEV: + m_dev += " "; + return parseDocTagLine(_pos, _end, m_dev, DocTagType::DEV); + case DocTagType::NOTICE: + m_notice += " "; + return parseDocTagLine(_pos, _end, m_notice, DocTagType::NOTICE); + case DocTagType::RETURN: + m_return += " "; + return parseDocTagLine(_pos, _end, m_return, DocTagType::RETURN); + case DocTagType::AUTHOR: + if (_owner == CommentOwner::CONTRACT) + { + m_contractAuthor += " "; + return parseDocTagLine(_pos, _end, m_contractAuthor, DocTagType::AUTHOR); + } + else if (_owner == CommentOwner::FUNCTION) + { + m_author += " "; + return parseDocTagLine(_pos, _end, m_author, DocTagType::AUTHOR); + } + else + // LTODO: Unknown tag, throw some form of warning and not just an exception + BOOST_THROW_EXCEPTION(DocstringParsingError() << errinfo_comment("@author tag in illegal comment")); + case DocTagType::TITLE: + if (_owner == CommentOwner::CONTRACT) + { + m_title += " "; + return parseDocTagLine(_pos, _end, m_title, DocTagType::TITLE); + } + else + // LTODO: Unknown tag, throw some form of warning and not just an exception + BOOST_THROW_EXCEPTION(DocstringParsingError() << errinfo_comment("@title tag in illegal comment")); + case DocTagType::PARAM: + return appendDocTagParam(_pos, _end); + default: + BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Internal: Illegal documentation tag type")); + break; + } +} + +static inline std::string::const_iterator getFirstSpaceOrNl(std::string::const_iterator _pos, + std::string::const_iterator _end) +{ + auto spacePos = std::find(_pos, _end, ' '); + auto nlPos = std::find(_pos, _end, '\n'); + return (spacePos < nlPos) ? spacePos : nlPos; +} + +void InterfaceHandler::parseDocString(std::string const& _string, CommentOwner _owner) +{ + auto currPos = _string.begin(); + auto end = _string.end(); + + while (currPos != end) + { + auto tagPos = std::find(currPos, end, '@'); + auto nlPos = std::find(currPos, end, '\n'); + + if (tagPos != end && tagPos < nlPos) + { + // we found a tag + auto tagNameEndPos = getFirstSpaceOrNl(tagPos, end); + if (tagNameEndPos == end) + BOOST_THROW_EXCEPTION(DocstringParsingError() << + errinfo_comment("End of tag " + std::string(tagPos, tagNameEndPos) + "not found")); + + currPos = parseDocTag(tagNameEndPos + 1, end, std::string(tagPos + 1, tagNameEndPos), _owner); + } + else if (m_lastTag != DocTagType::NONE) // continuation of the previous tag + currPos = appendDocTag(currPos + 1, end, _owner); + else if (currPos != end) // skip the line if a newline was found + currPos = nlPos + 1; + } +} + +} //solidity NS +} // dev NS diff --git a/libsolidity/InterfaceHandler.h b/libsolidity/InterfaceHandler.h new file mode 100644 index 000000000..b1cd4b562 --- /dev/null +++ b/libsolidity/InterfaceHandler.h @@ -0,0 +1,123 @@ +/* + This file is part of cpp-ethereum. + + cpp-ethereum is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + cpp-ethereum is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with cpp-ethereum. If not, see . +*/ +/** + * @author Lefteris + * @date 2014 + * Takes the parsed AST and produces the Natspec + * documentation and the ABI interface + * https://github.com/ethereum/wiki/wiki/Ethereum-Natural-Specification-Format + * + * Can generally deal with JSON files + */ + +#pragma once + +#include +#include +#include + +namespace dev +{ +namespace solidity +{ + +// Forward declarations +class ContractDefinition; +enum class DocumentationType: uint8_t; + +enum class DocTagType: uint8_t +{ + NONE = 0, + DEV, + NOTICE, + PARAM, + RETURN, + AUTHOR, + TITLE +}; + +enum class CommentOwner +{ + CONTRACT, + FUNCTION +}; + +class InterfaceHandler +{ +public: + InterfaceHandler(); + + /// Get the given type of documentation + /// @param _contractDef The contract definition + /// @param _type The type of the documentation. Can be one of the + /// types provided by @c DocumentationType + /// @return A unique pointer contained string with the json + /// representation of provided type + std::unique_ptr getDocumentation(ContractDefinition& _contractDef, + DocumentationType _type); + /// Get the ABI Interface of the contract + /// @param _contractDef The contract definition + /// @return A unique pointer contained string with the json + /// representation of the contract's ABI Interface + std::unique_ptr getABIInterface(ContractDefinition& _contractDef); + /// Get the User documentation of the contract + /// @param _contractDef The contract definition + /// @return A unique pointer contained string with the json + /// representation of the contract's user documentation + std::unique_ptr getUserDocumentation(ContractDefinition& _contractDef); + /// Get the Developer's documentation of the contract + /// @param _contractDef The contract definition + /// @return A unique pointer contained string with the json + /// representation of the contract's developer documentation + std::unique_ptr getDevDocumentation(ContractDefinition& _contractDef); + +private: + void resetUser(); + void resetDev(); + + std::string::const_iterator parseDocTagLine(std::string::const_iterator _pos, + std::string::const_iterator _end, + std::string& _tagString, + DocTagType _tagType); + std::string::const_iterator parseDocTagParam(std::string::const_iterator _pos, + std::string::const_iterator _end); + std::string::const_iterator appendDocTagParam(std::string::const_iterator _pos, + std::string::const_iterator _end); + void parseDocString(std::string const& _string, CommentOwner _owner); + std::string::const_iterator appendDocTag(std::string::const_iterator _pos, + std::string::const_iterator _end, + CommentOwner _owner); + std::string::const_iterator parseDocTag(std::string::const_iterator _pos, + std::string::const_iterator _end, + std::string const& _tag, + CommentOwner _owner); + + Json::StyledWriter m_writer; + + // internal state + DocTagType m_lastTag; + std::string m_notice; + std::string m_dev; + std::string m_return; + std::string m_contractAuthor; + std::string m_author; + std::string m_title; + std::vector> m_params; +}; + +} //solidity NS +} // dev NS diff --git a/libsolidity/NameAndTypeResolver.cpp b/libsolidity/NameAndTypeResolver.cpp index 0578e5996..540b066eb 100644 --- a/libsolidity/NameAndTypeResolver.cpp +++ b/libsolidity/NameAndTypeResolver.cpp @@ -32,12 +32,25 @@ namespace solidity { +NameAndTypeResolver::NameAndTypeResolver(std::vector const& _globals) +{ + for (Declaration const* declaration: _globals) + m_scopes[nullptr].registerDeclaration(*declaration); +} + +void NameAndTypeResolver::registerDeclarations(SourceUnit& _sourceUnit) +{ + // The helper registers all declarations in m_scopes as a side-effect of its construction. + DeclarationRegistrationHelper registrar(m_scopes, _sourceUnit); +} + void NameAndTypeResolver::resolveNamesAndTypes(ContractDefinition& _contract) { - reset(); - DeclarationRegistrationHelper registrar(m_scopes, _contract); m_currentScope = &m_scopes[&_contract]; - //@todo structs + for (ASTPointer const& structDef: _contract.getDefinedStructs()) + ReferencesResolver resolver(*structDef, *this, nullptr); + for (ASTPointer const& structDef: _contract.getDefinedStructs()) + structDef->checkValidityOfMembers(); for (ASTPointer const& variable: _contract.getStateVariables()) ReferencesResolver resolver(*variable, *this, nullptr); for (ASTPointer const& function: _contract.getDefinedFunctions()) @@ -52,12 +65,19 @@ void NameAndTypeResolver::resolveNamesAndTypes(ContractDefinition& _contract) for (ASTPointer const& function: _contract.getDefinedFunctions()) { m_currentScope = &m_scopes[function.get()]; - function->getBody().checkTypeRequirements(); + function->checkTypeRequirements(); } m_currentScope = &m_scopes[nullptr]; } -Declaration* NameAndTypeResolver::resolveName(ASTString const& _name, Declaration const* _scope) const +void NameAndTypeResolver::updateDeclaration(Declaration const& _declaration) +{ + m_scopes[nullptr].registerDeclaration(_declaration, true); + if (asserts(_declaration.getScope() == nullptr)) + BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Updated declaration outside global scope.")); +} + +Declaration const* NameAndTypeResolver::resolveName(ASTString const& _name, Declaration const* _scope) const { auto iterator = m_scopes.find(_scope); if (iterator == end(m_scopes)) @@ -65,20 +85,14 @@ Declaration* NameAndTypeResolver::resolveName(ASTString const& _name, Declaratio return iterator->second.resolveName(_name, false); } -Declaration* NameAndTypeResolver::getNameFromCurrentScope(ASTString const& _name, bool _recursive) +Declaration const* NameAndTypeResolver::getNameFromCurrentScope(ASTString const& _name, bool _recursive) { return m_currentScope->resolveName(_name, _recursive); } -void NameAndTypeResolver::reset() -{ - m_scopes.clear(); - m_currentScope = nullptr; -} - -DeclarationRegistrationHelper::DeclarationRegistrationHelper(map& _scopes, +DeclarationRegistrationHelper::DeclarationRegistrationHelper(map& _scopes, ASTNode& _astRoot): - m_scopes(_scopes), m_currentScope(&m_scopes[nullptr]) + m_scopes(_scopes), m_currentScope(nullptr) { _astRoot.accept(*this); } @@ -133,38 +147,37 @@ bool DeclarationRegistrationHelper::visit(VariableDeclaration& _declaration) return true; } -void DeclarationRegistrationHelper::enterNewSubScope(ASTNode& _node) +void DeclarationRegistrationHelper::enterNewSubScope(Declaration const& _declaration) { - map::iterator iter; + map::iterator iter; bool newlyAdded; - tie(iter, newlyAdded) = m_scopes.emplace(&_node, Scope(m_currentScope)); + tie(iter, newlyAdded) = m_scopes.emplace(&_declaration, DeclarationContainer(m_currentScope, &m_scopes[m_currentScope])); if (asserts(newlyAdded)) BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unable to add new scope.")); - m_currentScope = &iter->second; + m_currentScope = &_declaration; } void DeclarationRegistrationHelper::closeCurrentScope() { if (asserts(m_currentScope)) BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Closed non-existing scope.")); - m_currentScope = m_currentScope->getEnclosingScope(); + m_currentScope = m_scopes[m_currentScope].getEnclosingDeclaration(); } void DeclarationRegistrationHelper::registerDeclaration(Declaration& _declaration, bool _opensScope) { - if (asserts(m_currentScope)) - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Declaration registered without scope.")); - if (!m_currentScope->registerDeclaration(_declaration)) + if (!m_scopes[m_currentScope].registerDeclaration(_declaration)) BOOST_THROW_EXCEPTION(DeclarationError() << errinfo_sourceLocation(_declaration.getLocation()) << errinfo_comment("Identifier already declared.")); //@todo the exception should also contain the location of the first declaration + _declaration.setScope(m_currentScope); if (_opensScope) enterNewSubScope(_declaration); } ReferencesResolver::ReferencesResolver(ASTNode& _root, NameAndTypeResolver& _resolver, - ParameterList* _returnParameters): - m_resolver(_resolver), m_returnParameters(_returnParameters) + ParameterList* _returnParameters, bool _allowLazyTypes): + m_resolver(_resolver), m_returnParameters(_returnParameters), m_allowLazyTypes(_allowLazyTypes) { _root.accept(*this); } @@ -174,7 +187,13 @@ void ReferencesResolver::endVisit(VariableDeclaration& _variable) // endVisit because the internal type needs resolving if it is a user defined type // or mapping if (_variable.getTypeName()) + { _variable.setType(_variable.getTypeName()->toType()); + if (!_variable.getType()) + BOOST_THROW_EXCEPTION(_variable.getTypeName()->createTypeError("Invalid type name")); + } + else if (!m_allowLazyTypes) + BOOST_THROW_EXCEPTION(_variable.createTypeError("Explicit type needed.")); // otherwise we have a "var"-declaration whose type is resolved by the first assignment } @@ -188,27 +207,22 @@ bool ReferencesResolver::visit(Return& _return) bool ReferencesResolver::visit(Mapping&) { - // @todo return true; } bool ReferencesResolver::visit(UserDefinedTypeName& _typeName) { - Declaration* declaration = m_resolver.getNameFromCurrentScope(_typeName.getName()); + Declaration const* declaration = m_resolver.getNameFromCurrentScope(_typeName.getName()); if (!declaration) BOOST_THROW_EXCEPTION(DeclarationError() << errinfo_sourceLocation(_typeName.getLocation()) << errinfo_comment("Undeclared identifier.")); - StructDefinition* referencedStruct = dynamic_cast(declaration); - //@todo later, contracts are also valid types - if (!referencedStruct) - BOOST_THROW_EXCEPTION(_typeName.createTypeError("Identifier does not name a type name.")); - _typeName.setReferencedStruct(*referencedStruct); + _typeName.setReferencedDeclaration(*declaration); return false; } bool ReferencesResolver::visit(Identifier& _identifier) { - Declaration* declaration = m_resolver.getNameFromCurrentScope(_identifier.getName()); + Declaration const* declaration = m_resolver.getNameFromCurrentScope(_identifier.getName()); if (!declaration) BOOST_THROW_EXCEPTION(DeclarationError() << errinfo_sourceLocation(_identifier.getLocation()) << errinfo_comment("Undeclared identifier.")); diff --git a/libsolidity/NameAndTypeResolver.h b/libsolidity/NameAndTypeResolver.h index 909024942..1ff9febf0 100644 --- a/libsolidity/NameAndTypeResolver.h +++ b/libsolidity/NameAndTypeResolver.h @@ -25,7 +25,7 @@ #include #include -#include +#include #include namespace dev @@ -41,27 +41,33 @@ namespace solidity class NameAndTypeResolver: private boost::noncopyable { public: - NameAndTypeResolver() {} - + explicit NameAndTypeResolver(std::vector const& _globals); + /// Registers all declarations found in the source unit. + void registerDeclarations(SourceUnit& _sourceUnit); + /// Resolves all names and types referenced from the given contract. void resolveNamesAndTypes(ContractDefinition& _contract); + /// Updates the given global declaration (used for "this"). Not to be used with declarations + /// that create their own scope. + void updateDeclaration(Declaration const& _declaration); /// Resolves the given @a _name inside the scope @a _scope. If @a _scope is omitted, /// the global scope is used (i.e. the one containing only the contract). /// @returns a pointer to the declaration on success or nullptr on failure. - Declaration* resolveName(ASTString const& _name, Declaration const* _scope = nullptr) const; + Declaration const* resolveName(ASTString const& _name, Declaration const* _scope = nullptr) const; /// Resolves a name in the "current" scope. Should only be called during the initial /// resolving phase. - Declaration* getNameFromCurrentScope(ASTString const& _name, bool _recursive = true); + Declaration const* getNameFromCurrentScope(ASTString const& _name, bool _recursive = true); private: void reset(); - /// Maps nodes declaring a scope to scopes, i.e. ContractDefinition, FunctionDeclaration and - /// StructDefinition (@todo not yet implemented), where nullptr denotes the global scope. - std::map m_scopes; + /// Maps nodes declaring a scope to scopes, i.e. ContractDefinition and FunctionDeclaration, + /// where nullptr denotes the global scope. Note that structs are not scope since they do + /// not contain code. + std::map m_scopes; - Scope* m_currentScope; + DeclarationContainer* m_currentScope; }; /** @@ -71,7 +77,7 @@ private: class DeclarationRegistrationHelper: private ASTVisitor { public: - DeclarationRegistrationHelper(std::map& _scopes, ASTNode& _astRoot); + DeclarationRegistrationHelper(std::map& _scopes, ASTNode& _astRoot); private: bool visit(ContractDefinition& _contract); @@ -83,12 +89,12 @@ private: void endVisit(VariableDefinition& _variableDefinition); bool visit(VariableDeclaration& _declaration); - void enterNewSubScope(ASTNode& _node); + void enterNewSubScope(Declaration const& _declaration); void closeCurrentScope(); void registerDeclaration(Declaration& _declaration, bool _opensScope); - std::map& m_scopes; - Scope* m_currentScope; + std::map& m_scopes; + Declaration const* m_currentScope; FunctionDefinition* m_currentFunction; }; @@ -99,7 +105,8 @@ private: class ReferencesResolver: private ASTVisitor { public: - ReferencesResolver(ASTNode& _root, NameAndTypeResolver& _resolver, ParameterList* _returnParameters); + ReferencesResolver(ASTNode& _root, NameAndTypeResolver& _resolver, + ParameterList* _returnParameters, bool _allowLazyTypes = true); private: virtual void endVisit(VariableDeclaration& _variable) override; @@ -110,6 +117,7 @@ private: NameAndTypeResolver& m_resolver; ParameterList* m_returnParameters; + bool m_allowLazyTypes; }; } diff --git a/libsolidity/Parser.cpp b/libsolidity/Parser.cpp index 276da0728..b678b2fc0 100644 --- a/libsolidity/Parser.cpp +++ b/libsolidity/Parser.cpp @@ -20,30 +20,27 @@ * Solidity parser. */ +#include #include #include #include #include #include +using namespace std; + namespace dev { namespace solidity { -ASTPointer Parser::parse(std::shared_ptr const& _scanner) -{ - m_scanner = _scanner; - return parseContractDefinition(); -} - - /// AST node factory that also tracks the begin and end position of an AST node /// while it is being parsed class Parser::ASTNodeFactory { public: - ASTNodeFactory(Parser const& _parser): m_parser(_parser), m_location(_parser.getPosition(), -1) {} + ASTNodeFactory(Parser const& _parser): + m_parser(_parser), m_location(_parser.getPosition(), -1, _parser.getSourceName()) {} void markEndPosition() { m_location.end = m_parser.getEndPosition(); } void setLocationEmpty() { m_location.end = m_location.start; } @@ -55,7 +52,7 @@ public: { if (m_location.end < 0) markEndPosition(); - return std::make_shared(m_location, std::forward(_args)...); + return make_shared(m_location, forward(_args)...); } private: @@ -63,6 +60,33 @@ private: Location m_location; }; +ASTPointer Parser::parse(shared_ptr const& _scanner) +{ + m_scanner = _scanner; + ASTNodeFactory nodeFactory(*this); + vector> nodes; + while (_scanner->getCurrentToken() != Token::EOS) + { + switch (m_scanner->getCurrentToken()) + { + case Token::IMPORT: + nodes.push_back(parseImportDirective()); + break; + case Token::CONTRACT: + nodes.push_back(parseContractDefinition()); + break; + default: + BOOST_THROW_EXCEPTION(createParserError(std::string("Expected import directive or contract definition."))); + } + } + return nodeFactory.createNode(nodes); +} + +std::shared_ptr const& Parser::getSourceName() const +{ + return m_scanner->getSourceName(); +} + int Parser::getPosition() const { return m_scanner->getCurrentLocation().start; @@ -73,15 +97,30 @@ int Parser::getEndPosition() const return m_scanner->getCurrentLocation().end; } +ASTPointer Parser::parseImportDirective() +{ + ASTNodeFactory nodeFactory(*this); + expectToken(Token::IMPORT); + if (m_scanner->getCurrentToken() != Token::STRING_LITERAL) + BOOST_THROW_EXCEPTION(createParserError("Expected string literal (URL).")); + ASTPointer url = getLiteralAndAdvance(); + nodeFactory.markEndPosition(); + expectToken(Token::SEMICOLON); + return nodeFactory.createNode(url); +} + ASTPointer Parser::parseContractDefinition() { ASTNodeFactory nodeFactory(*this); + ASTPointer docstring; + if (m_scanner->getCurrentCommentLiteral() != "") + docstring = make_shared(m_scanner->getCurrentCommentLiteral()); expectToken(Token::CONTRACT); ASTPointer name = expectIdentifierToken(); expectToken(Token::LBRACE); - std::vector> structs; - std::vector> stateVariables; - std::vector> functions; + vector> structs; + vector> stateVariables; + vector> functions; bool visibilityIsPublic = true; while (true) { @@ -110,13 +149,16 @@ ASTPointer Parser::parseContractDefinition() } nodeFactory.markEndPosition(); expectToken(Token::RBRACE); - expectToken(Token::EOS); - return nodeFactory.createNode(name, structs, stateVariables, functions); + return nodeFactory.createNode(name, docstring, structs, stateVariables, functions); } ASTPointer Parser::parseFunctionDefinition(bool _isPublic) { ASTNodeFactory nodeFactory(*this); + ASTPointer docstring; + if (m_scanner->getCurrentCommentLiteral() != "") + docstring = make_shared(m_scanner->getCurrentCommentLiteral()); + expectToken(Token::FUNCTION); ASTPointer name(expectIdentifierToken()); ASTPointer parameters(parseParameterList()); @@ -138,12 +180,13 @@ ASTPointer Parser::parseFunctionDefinition(bool _isPublic) // create an empty parameter list at a zero-length location ASTNodeFactory nodeFactory(*this); nodeFactory.setLocationEmpty(); - returnParameters = nodeFactory.createNode(std::vector>()); + returnParameters = nodeFactory.createNode(vector>()); } ASTPointer block = parseBlock(); nodeFactory.setEndPositionFromNode(block); - return nodeFactory.createNode(name, _isPublic, parameters, - isDeclaredConst, returnParameters, block); + return nodeFactory.createNode(name, _isPublic, docstring, + parameters, + isDeclaredConst, returnParameters, block); } ASTPointer Parser::parseStructDefinition() @@ -151,7 +194,7 @@ ASTPointer Parser::parseStructDefinition() ASTNodeFactory nodeFactory(*this); expectToken(Token::STRUCT); ASTPointer name = expectIdentifierToken(); - std::vector> members; + vector> members; expectToken(Token::LBRACE); while (m_scanner->getCurrentToken() != Token::RBRACE) { @@ -223,7 +266,7 @@ ASTPointer Parser::parseMapping() ASTPointer Parser::parseParameterList(bool _allowEmpty) { ASTNodeFactory nodeFactory(*this); - std::vector> parameters; + vector> parameters; expectToken(Token::LPAREN); if (!_allowEmpty || m_scanner->getCurrentToken() != Token::RPAREN) { @@ -244,7 +287,7 @@ ASTPointer Parser::parseBlock() { ASTNodeFactory nodeFactory(*this); expectToken(Token::LBRACE); - std::vector> statements; + vector> statements; while (m_scanner->getCurrentToken() != Token::RBRACE) statements.push_back(parseStatement()); nodeFactory.markEndPosition(); @@ -442,7 +485,7 @@ ASTPointer Parser::parseLeftHandSideExpression() case Token::LPAREN: { m_scanner->next(); - std::vector> arguments = parseFunctionCallArguments(); + vector> arguments = parseFunctionCallArguments(); nodeFactory.markEndPosition(); expectToken(Token::RPAREN); expression = nodeFactory.createNode(expression, arguments); @@ -498,9 +541,9 @@ ASTPointer Parser::parsePrimaryExpression() return expression; } -std::vector> Parser::parseFunctionCallArguments() +vector> Parser::parseFunctionCallArguments() { - std::vector> arguments; + vector> arguments; if (m_scanner->getCurrentToken() != Token::RPAREN) { arguments.push_back(parseExpression()); @@ -516,7 +559,7 @@ std::vector> Parser::parseFunctionCallArguments() void Parser::expectToken(Token::Value _value) { if (m_scanner->getCurrentToken() != _value) - BOOST_THROW_EXCEPTION(createParserError(std::string("Expected token ") + std::string(Token::getName(_value)))); + BOOST_THROW_EXCEPTION(createParserError(string("Expected token ") + string(Token::getName(_value)))); m_scanner->next(); } @@ -538,14 +581,15 @@ ASTPointer Parser::expectIdentifierToken() ASTPointer Parser::getLiteralAndAdvance() { - ASTPointer identifier = std::make_shared(m_scanner->getCurrentLiteral()); + ASTPointer identifier = make_shared(m_scanner->getCurrentLiteral()); m_scanner->next(); return identifier; } -ParserError Parser::createParserError(std::string const& _description) const +ParserError Parser::createParserError(string const& _description) const { - return ParserError() << errinfo_sourcePosition(getPosition()) << errinfo_comment(_description); + return ParserError() << errinfo_sourceLocation(Location(getPosition(), getPosition(), getSourceName())) + << errinfo_comment(_description); } diff --git a/libsolidity/Parser.h b/libsolidity/Parser.h index 307a0d6a1..52a374e03 100644 --- a/libsolidity/Parser.h +++ b/libsolidity/Parser.h @@ -34,7 +34,8 @@ class Scanner; class Parser { public: - ASTPointer parse(std::shared_ptr const& _scanner); + ASTPointer parse(std::shared_ptr const& _scanner); + std::shared_ptr const& getSourceName() const; private: class ASTNodeFactory; @@ -46,6 +47,7 @@ private: ///@{ ///@name Parsing functions for the AST nodes + ASTPointer parseImportDirective(); ASTPointer parseContractDefinition(); ASTPointer parseFunctionDefinition(bool _isPublic); ASTPointer parseStructDefinition(); diff --git a/libsolidity/Scanner.cpp b/libsolidity/Scanner.cpp index b13e52d7e..08bf744d4 100644 --- a/libsolidity/Scanner.cpp +++ b/libsolidity/Scanner.cpp @@ -63,34 +63,34 @@ namespace solidity namespace { -bool IsDecimalDigit(char c) +bool isDecimalDigit(char c) { return '0' <= c && c <= '9'; } -bool IsHexDigit(char c) +bool isHexDigit(char c) { - return IsDecimalDigit(c) + return isDecimalDigit(c) || ('a' <= c && c <= 'f') || ('A' <= c && c <= 'F'); } -bool IsLineTerminator(char c) +bool isLineTerminator(char c) { return c == '\n'; } -bool IsWhiteSpace(char c) +bool isWhiteSpace(char c) { return c == ' ' || c == '\n' || c == '\t'; } -bool IsIdentifierStart(char c) +bool isIdentifierStart(char c) { return c == '_' || c == '$' || ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z'); } -bool IsIdentifierPart(char c) +bool isIdentifierPart(char c) { - return IsIdentifierStart(c) || IsDecimalDigit(c); + return isIdentifierStart(c) || isDecimalDigit(c); } -int HexValue(char c) +int hexValue(char c) { if (c >= '0' && c <= '9') return c - '0'; @@ -102,22 +102,69 @@ int HexValue(char c) } } // end anonymous namespace -void Scanner::reset(CharStream const& _source) + + +/// Scoped helper for literal recording. Automatically drops the literal +/// if aborting the scanning before it's complete. +enum LiteralType { + LITERAL_TYPE_STRING, + LITERAL_TYPE_NUMBER, // not really different from string type in behaviour + LITERAL_TYPE_COMMENT +}; + +class LiteralScope +{ +public: + explicit LiteralScope(Scanner* _self, enum LiteralType _type): m_type(_type) + , m_scanner(_self) + , m_complete(false) + { + if (_type == LITERAL_TYPE_COMMENT) + m_scanner->m_nextSkippedComment.literal.clear(); + else + m_scanner->m_nextToken.literal.clear(); + } + ~LiteralScope() + { + if (!m_complete) + { + if (m_type == LITERAL_TYPE_COMMENT) + m_scanner->m_nextSkippedComment.literal.clear(); + else + m_scanner->m_nextToken.literal.clear(); + } + } + void complete() { m_complete = true; } + +private: + enum LiteralType m_type; + Scanner* m_scanner; + bool m_complete; +}; // end of LiteralScope class + + +void Scanner::reset(CharStream const& _source, string const& _sourceName) { m_source = _source; + m_sourceName = make_shared(_sourceName); + reset(); +} + +void Scanner::reset() +{ + m_source.reset(); m_char = m_source.get(); skipWhitespace(); scanToken(); next(); } - bool Scanner::scanHexByte(char& o_scannedByte) { char x = 0; for (int i = 0; i < 2; i++) { - int d = HexValue(m_char); + int d = hexValue(m_char); if (d < 0) { rollback(i); @@ -136,9 +183,11 @@ BOOST_STATIC_ASSERT(Token::NUM_TOKENS <= 0x100); Token::Value Scanner::next() { - m_current_token = m_next_token; + m_currentToken = m_nextToken; + m_skippedComment = m_nextSkippedComment; scanToken(); - return m_current_token.token; + + return m_currentToken.token; } Token::Value Scanner::selectToken(char _next, Token::Value _then, Token::Value _else) @@ -150,27 +199,54 @@ Token::Value Scanner::selectToken(char _next, Token::Value _then, Token::Value _ return _else; } - bool Scanner::skipWhitespace() { - int const start_position = getSourcePos(); - while (IsWhiteSpace(m_char)) + int const startPosition = getSourcePos(); + while (isWhiteSpace(m_char)) advance(); // Return whether or not we skipped any characters. - return getSourcePos() != start_position; + return getSourcePos() != startPosition; } - Token::Value Scanner::skipSingleLineComment() { // The line terminator at the end of the line is not considered // to be part of the single-line comment; it is recognized // separately by the lexical grammar and becomes part of the // stream of input elements for the syntactic grammar - while (advance() && !IsLineTerminator(m_char)) { }; + while (advance() && !isLineTerminator(m_char)) { }; return Token::WHITESPACE; } +Token::Value Scanner::scanDocumentationComment() +{ + LiteralScope literal(this, LITERAL_TYPE_COMMENT); + advance(); //consume the last '/' + while (!isSourcePastEndOfInput()) + { + if (isLineTerminator(m_char)) + { + // check if next line is also a documentation comment + skipWhitespace(); + if (!m_source.isPastEndOfInput(3) && + m_source.get(0) == '/' && + m_source.get(1) == '/' && + m_source.get(2) == '/') + { + addCommentLiteralChar('\n'); + m_char = m_source.advanceAndGet(3); + } + else + break; // next line is not a documentation comment, we are done + + } + addCommentLiteralChar(m_char); + advance(); + } + literal.complete(); + return Token::COMMENT_LITERAL; +} + Token::Value Scanner::skipMultiLineComment() { if (asserts(m_char == '*')) @@ -196,12 +272,13 @@ Token::Value Scanner::skipMultiLineComment() void Scanner::scanToken() { - m_next_token.literal.clear(); + m_nextToken.literal.clear(); + m_nextSkippedComment.literal.clear(); Token::Value token; do { // Remember the position of the next token - m_next_token.location.start = getSourcePos(); + m_nextToken.location.start = getSourcePos(); switch (m_char) { case '\n': // fall-through @@ -280,7 +357,7 @@ void Scanner::scanToken() } else if (m_char == '=') token = selectToken(Token::ASSIGN_SUB); - else if (m_char == '.' || IsDecimalDigit(m_char)) + else if (m_char == '.' || isDecimalDigit(m_char)) token = scanNumber('-'); else token = Token::SUB; @@ -297,7 +374,21 @@ void Scanner::scanToken() // / // /* /= advance(); if (m_char == '/') - token = skipSingleLineComment(); + { + if (!advance()) /* double slash comment directly before EOS */ + token = Token::WHITESPACE; + else if (m_char == '/') + { + Token::Value comment; + m_nextSkippedComment.location.start = getSourcePos(); + comment = scanDocumentationComment(); + m_nextSkippedComment.location.end = getSourcePos(); + m_nextSkippedComment.token = comment; + token = Token::WHITESPACE; + } + else + token = skipSingleLineComment(); + } else if (m_char == '*') token = skipMultiLineComment(); else if (m_char == '=') @@ -332,7 +423,7 @@ void Scanner::scanToken() case '.': // . Number advance(); - if (IsDecimalDigit(m_char)) + if (isDecimalDigit(m_char)) token = scanNumber('.'); else token = Token::PERIOD; @@ -371,9 +462,9 @@ void Scanner::scanToken() token = selectToken(Token::BIT_NOT); break; default: - if (IsIdentifierStart(m_char)) + if (isIdentifierStart(m_char)) token = scanIdentifierOrKeyword(); - else if (IsDecimalDigit(m_char)) + else if (isDecimalDigit(m_char)) token = scanNumber(); else if (skipWhitespace()) token = Token::WHITESPACE; @@ -387,8 +478,8 @@ void Scanner::scanToken() // whitespace. } while (token == Token::WHITESPACE); - m_next_token.location.end = getSourcePos(); - m_next_token.token = token; + m_nextToken.location.end = getSourcePos(); + m_nextToken.token = token; } bool Scanner::scanEscape() @@ -396,7 +487,7 @@ bool Scanner::scanEscape() char c = m_char; advance(); // Skip escaped newlines. - if (IsLineTerminator(c)) + if (isLineTerminator(c)) return true; switch (c) { @@ -436,8 +527,8 @@ Token::Value Scanner::scanString() { char const quote = m_char; advance(); // consume quote - LiteralScope literal(this); - while (m_char != quote && !isSourcePastEndOfInput() && !IsLineTerminator(m_char)) + LiteralScope literal(this, LITERAL_TYPE_STRING); + while (m_char != quote && !isSourcePastEndOfInput() && !isLineTerminator(m_char)) { char c = m_char; advance(); @@ -449,24 +540,23 @@ Token::Value Scanner::scanString() else addLiteralChar(c); } - if (m_char != quote) return Token::ILLEGAL; - literal.Complete(); + if (m_char != quote) + return Token::ILLEGAL; + literal.complete(); advance(); // consume quote return Token::STRING_LITERAL; } - void Scanner::scanDecimalDigits() { - while (IsDecimalDigit(m_char)) + while (isDecimalDigit(m_char)) addLiteralCharAndAdvance(); } - Token::Value Scanner::scanNumber(char _charSeen) { enum { DECIMAL, HEX, BINARY } kind = DECIMAL; - LiteralScope literal(this); + LiteralScope literal(this, LITERAL_TYPE_NUMBER); if (_charSeen == '.') { // we have already seen a decimal point of the float @@ -487,9 +577,9 @@ Token::Value Scanner::scanNumber(char _charSeen) // hex number kind = HEX; addLiteralCharAndAdvance(); - if (!IsHexDigit(m_char)) + if (!isHexDigit(m_char)) return Token::ILLEGAL; // we must have at least one hex digit after 'x'/'X' - while (IsHexDigit(m_char)) + while (isHexDigit(m_char)) addLiteralCharAndAdvance(); } } @@ -509,12 +599,13 @@ Token::Value Scanner::scanNumber(char _charSeen) { if (asserts(kind != HEX)) // 'e'/'E' must be scanned as part of the hex number BOOST_THROW_EXCEPTION(InternalCompilerError()); - if (kind != DECIMAL) return Token::ILLEGAL; + if (kind != DECIMAL) + return Token::ILLEGAL; // scan exponent addLiteralCharAndAdvance(); if (m_char == '+' || m_char == '-') addLiteralCharAndAdvance(); - if (!IsDecimalDigit(m_char)) + if (!isDecimalDigit(m_char)) return Token::ILLEGAL; // we must have at least one decimal digit after 'e'/'E' scanDecimalDigits(); } @@ -522,9 +613,9 @@ Token::Value Scanner::scanNumber(char _charSeen) // not be an identifier start or a decimal digit; see ECMA-262 // section 7.8.3, page 17 (note that we read only one decimal digit // if the value is 0). - if (IsDecimalDigit(m_char) || IsIdentifierStart(m_char)) + if (isDecimalDigit(m_char) || isIdentifierStart(m_char)) return Token::ILLEGAL; - literal.Complete(); + literal.complete(); return Token::NUMBER; } @@ -532,210 +623,41 @@ Token::Value Scanner::scanNumber(char _charSeen) // ---------------------------------------------------------------------------- // Keyword Matcher -#define KEYWORDS(KEYWORD_GROUP, KEYWORD) \ - KEYWORD_GROUP('a') \ - KEYWORD("address", Token::ADDRESS) \ - KEYWORD_GROUP('b') \ - KEYWORD("break", Token::BREAK) \ - KEYWORD("bool", Token::BOOL) \ - KEYWORD_GROUP('c') \ - KEYWORD("case", Token::CASE) \ - KEYWORD("const", Token::CONST) \ - KEYWORD("continue", Token::CONTINUE) \ - KEYWORD("contract", Token::CONTRACT) \ - KEYWORD_GROUP('d') \ - KEYWORD("default", Token::DEFAULT) \ - KEYWORD("delete", Token::DELETE) \ - KEYWORD("do", Token::DO) \ - KEYWORD_GROUP('e') \ - KEYWORD("else", Token::ELSE) \ - KEYWORD("extends", Token::EXTENDS) \ - KEYWORD_GROUP('f') \ - KEYWORD("false", Token::FALSE_LITERAL) \ - KEYWORD("for", Token::FOR) \ - KEYWORD("function", Token::FUNCTION) \ - KEYWORD_GROUP('h') \ - KEYWORD("hash", Token::HASH) \ - KEYWORD("hash8", Token::HASH8) \ - KEYWORD("hash16", Token::HASH16) \ - KEYWORD("hash24", Token::HASH24) \ - KEYWORD("hash32", Token::HASH32) \ - KEYWORD("hash40", Token::HASH40) \ - KEYWORD("hash48", Token::HASH48) \ - KEYWORD("hash56", Token::HASH56) \ - KEYWORD("hash64", Token::HASH64) \ - KEYWORD("hash72", Token::HASH72) \ - KEYWORD("hash80", Token::HASH80) \ - KEYWORD("hash88", Token::HASH88) \ - KEYWORD("hash96", Token::HASH96) \ - KEYWORD("hash104", Token::HASH104) \ - KEYWORD("hash112", Token::HASH112) \ - KEYWORD("hash120", Token::HASH120) \ - KEYWORD("hash128", Token::HASH128) \ - KEYWORD("hash136", Token::HASH136) \ - KEYWORD("hash144", Token::HASH144) \ - KEYWORD("hash152", Token::HASH152) \ - KEYWORD("hash160", Token::HASH160) \ - KEYWORD("hash168", Token::HASH168) \ - KEYWORD("hash178", Token::HASH176) \ - KEYWORD("hash184", Token::HASH184) \ - KEYWORD("hash192", Token::HASH192) \ - KEYWORD("hash200", Token::HASH200) \ - KEYWORD("hash208", Token::HASH208) \ - KEYWORD("hash216", Token::HASH216) \ - KEYWORD("hash224", Token::HASH224) \ - KEYWORD("hash232", Token::HASH232) \ - KEYWORD("hash240", Token::HASH240) \ - KEYWORD("hash248", Token::HASH248) \ - KEYWORD("hash256", Token::HASH256) \ - KEYWORD_GROUP('i') \ - KEYWORD("if", Token::IF) \ - KEYWORD("in", Token::IN) \ - KEYWORD("int", Token::INT) \ - KEYWORD("int8", Token::INT8) \ - KEYWORD("int16", Token::INT16) \ - KEYWORD("int24", Token::INT24) \ - KEYWORD("int32", Token::INT32) \ - KEYWORD("int40", Token::INT40) \ - KEYWORD("int48", Token::INT48) \ - KEYWORD("int56", Token::INT56) \ - KEYWORD("int64", Token::INT64) \ - KEYWORD("int72", Token::INT72) \ - KEYWORD("int80", Token::INT80) \ - KEYWORD("int88", Token::INT88) \ - KEYWORD("int96", Token::INT96) \ - KEYWORD("int104", Token::INT104) \ - KEYWORD("int112", Token::INT112) \ - KEYWORD("int120", Token::INT120) \ - KEYWORD("int128", Token::INT128) \ - KEYWORD("int136", Token::INT136) \ - KEYWORD("int144", Token::INT144) \ - KEYWORD("int152", Token::INT152) \ - KEYWORD("int160", Token::INT160) \ - KEYWORD("int168", Token::INT168) \ - KEYWORD("int178", Token::INT176) \ - KEYWORD("int184", Token::INT184) \ - KEYWORD("int192", Token::INT192) \ - KEYWORD("int200", Token::INT200) \ - KEYWORD("int208", Token::INT208) \ - KEYWORD("int216", Token::INT216) \ - KEYWORD("int224", Token::INT224) \ - KEYWORD("int232", Token::INT232) \ - KEYWORD("int240", Token::INT240) \ - KEYWORD("int248", Token::INT248) \ - KEYWORD("int256", Token::INT256) \ - KEYWORD_GROUP('l') \ - KEYWORD_GROUP('m') \ - KEYWORD("mapping", Token::MAPPING) \ - KEYWORD_GROUP('n') \ - KEYWORD("new", Token::NEW) \ - KEYWORD("null", Token::NULL_LITERAL) \ - KEYWORD_GROUP('p') \ - KEYWORD("private", Token::PRIVATE) \ - KEYWORD("public", Token::PUBLIC) \ - KEYWORD_GROUP('r') \ - KEYWORD("real", Token::REAL) \ - KEYWORD("return", Token::RETURN) \ - KEYWORD("returns", Token::RETURNS) \ - KEYWORD_GROUP('s') \ - KEYWORD("string", Token::STRING_TYPE) \ - KEYWORD("struct", Token::STRUCT) \ - KEYWORD("switch", Token::SWITCH) \ - KEYWORD_GROUP('t') \ - KEYWORD("text", Token::TEXT) \ - KEYWORD("this", Token::THIS) \ - KEYWORD("true", Token::TRUE_LITERAL) \ - KEYWORD_GROUP('u') \ - KEYWORD("uint", Token::UINT) \ - KEYWORD("uint8", Token::UINT8) \ - KEYWORD("uint16", Token::UINT16) \ - KEYWORD("uint24", Token::UINT24) \ - KEYWORD("uint32", Token::UINT32) \ - KEYWORD("uint40", Token::UINT40) \ - KEYWORD("uint48", Token::UINT48) \ - KEYWORD("uint56", Token::UINT56) \ - KEYWORD("uint64", Token::UINT64) \ - KEYWORD("uint72", Token::UINT72) \ - KEYWORD("uint80", Token::UINT80) \ - KEYWORD("uint88", Token::UINT88) \ - KEYWORD("uint96", Token::UINT96) \ - KEYWORD("uint104", Token::UINT104) \ - KEYWORD("uint112", Token::UINT112) \ - KEYWORD("uint120", Token::UINT120) \ - KEYWORD("uint128", Token::UINT128) \ - KEYWORD("uint136", Token::UINT136) \ - KEYWORD("uint144", Token::UINT144) \ - KEYWORD("uint152", Token::UINT152) \ - KEYWORD("uint160", Token::UINT160) \ - KEYWORD("uint168", Token::UINT168) \ - KEYWORD("uint178", Token::UINT176) \ - KEYWORD("uint184", Token::UINT184) \ - KEYWORD("uint192", Token::UINT192) \ - KEYWORD("uint200", Token::UINT200) \ - KEYWORD("uint208", Token::UINT208) \ - KEYWORD("uint216", Token::UINT216) \ - KEYWORD("uint224", Token::UINT224) \ - KEYWORD("uint232", Token::UINT232) \ - KEYWORD("uint240", Token::UINT240) \ - KEYWORD("uint248", Token::UINT248) \ - KEYWORD("uint256", Token::UINT256) \ - KEYWORD("ureal", Token::UREAL) \ - KEYWORD_GROUP('v') \ - KEYWORD("var", Token::VAR) \ - KEYWORD_GROUP('w') \ - KEYWORD("while", Token::WHILE) \ - - -static Token::Value KeywordOrIdentifierToken(string const& input) + +static Token::Value keywordOrIdentifierToken(string const& _input) { - if (asserts(!input.empty())) - BOOST_THROW_EXCEPTION(InternalCompilerError()); - int const kMinLength = 2; - int const kMaxLength = 10; - if (input.size() < kMinLength || input.size() > kMaxLength) - return Token::IDENTIFIER; - switch (input[0]) - { - default: -#define KEYWORD_GROUP_CASE(ch) \ - break; \ -case ch: -#define KEYWORD(keyword, token) \ - { \ - /* 'keyword' is a char array, so sizeof(keyword) is */ \ - /* strlen(keyword) plus 1 for the NUL char. */ \ - int const keyword_length = sizeof(keyword) - 1; \ - BOOST_STATIC_ASSERT(keyword_length >= kMinLength); \ - BOOST_STATIC_ASSERT(keyword_length <= kMaxLength); \ - if (input == keyword) \ - return token; \ - } - KEYWORDS(KEYWORD_GROUP_CASE, KEYWORD) - } - return Token::IDENTIFIER; + // The following macros are used inside TOKEN_LIST and cause non-keyword tokens to be ignored + // and keywords to be put inside the keywords variable. +#define KEYWORD(name, string, precedence) {string, Token::name}, +#define TOKEN(name, string, precedence) + static const map keywords({TOKEN_LIST(TOKEN, KEYWORD)}); +#undef KEYWORD +#undef TOKEN + auto it = keywords.find(_input); + return it == keywords.end() ? Token::IDENTIFIER : it->second; } Token::Value Scanner::scanIdentifierOrKeyword() { - if (asserts(IsIdentifierStart(m_char))) + if (asserts(isIdentifierStart(m_char))) BOOST_THROW_EXCEPTION(InternalCompilerError()); - LiteralScope literal(this); + LiteralScope literal(this, LITERAL_TYPE_STRING); addLiteralCharAndAdvance(); // Scan the rest of the identifier characters. - while (IsIdentifierPart(m_char)) + while (isIdentifierPart(m_char)) addLiteralCharAndAdvance(); - literal.Complete(); - return KeywordOrIdentifierToken(m_next_token.literal); + literal.complete(); + return keywordOrIdentifierToken(m_nextToken.literal); } -char CharStream::advanceAndGet() +char CharStream::advanceAndGet(size_t _chars) { if (isPastEndOfInput()) return 0; - ++m_pos; + m_pos += _chars; if (isPastEndOfInput()) return 0; - return get(); + return m_source[m_pos]; } char CharStream::rollback(size_t _amount) diff --git a/libsolidity/Scanner.h b/libsolidity/Scanner.h index 997365f3c..18b1f5d3a 100644 --- a/libsolidity/Scanner.h +++ b/libsolidity/Scanner.h @@ -74,11 +74,13 @@ public: CharStream(): m_pos(0) {} explicit CharStream(std::string const& _source): m_source(_source), m_pos(0) {} int getPos() const { return m_pos; } - bool isPastEndOfInput() const { return m_pos >= m_source.size(); } - char get() const { return m_source[m_pos]; } - char advanceAndGet(); + bool isPastEndOfInput(size_t _charsForward = 0) const { return (m_pos + _charsForward) >= m_source.size(); } + char get(size_t _charsForward = 0) const { return m_source[m_pos + _charsForward]; } + char advanceAndGet(size_t _chars=1); char rollback(size_t _amount); + void reset() { m_pos = 0; } + ///@{ ///@name Error printing helper functions /// Functions that help pretty-printing parse errors @@ -93,50 +95,55 @@ private: }; + class Scanner { + friend class LiteralScope; public: - // Scoped helper for literal recording. Automatically drops the literal - // if aborting the scanning before it's complete. - class LiteralScope - { - public: - explicit LiteralScope(Scanner* self): scanner_(self), complete_(false) { scanner_->startNewLiteral(); } - ~LiteralScope() { if (!complete_) scanner_->dropLiteral(); } - void Complete() { complete_ = true; } - - private: - Scanner* scanner_; - bool complete_; - }; - Scanner() { reset(CharStream()); } - explicit Scanner(CharStream const& _source) { reset(_source); } + explicit Scanner(CharStream const& _source = CharStream(), std::string const& _sourceName = "") { reset(_source, _sourceName); } - /// Resets the scanner as if newly constructed with _input as input. - void reset(CharStream const& _source); + /// Resets the scanner as if newly constructed with _source and _sourceName as input. + void reset(CharStream const& _source, std::string const& _sourceName); + /// Resets scanner to the start of input. + void reset(); - /// Returns the next token and advances input. + /// Returns the next token and advances input Token::Value next(); ///@{ ///@name Information about the current token /// Returns the current token - Token::Value getCurrentToken() { return m_current_token.token; } - Location getCurrentLocation() const { return m_current_token.location; } - std::string const& getCurrentLiteral() const { return m_current_token.literal; } + Token::Value getCurrentToken() + { + return m_currentToken.token; + } + Location getCurrentLocation() const { return m_currentToken.location; } + std::string const& getCurrentLiteral() const { return m_currentToken.literal; } + ///@} + + ///@{ + ///@name Information about the current comment token + + Location getCurrentCommentLocation() const { return m_skippedComment.location; } + std::string const& getCurrentCommentLiteral() const { return m_skippedComment.literal; } + /// Called by the parser during FunctionDefinition parsing to clear the current comment + void clearCurrentCommentLiteral() { m_skippedComment.literal.clear(); } + ///@} ///@{ ///@name Information about the next token /// Returns the next token without advancing input. - Token::Value peekNextToken() const { return m_next_token.token; } - Location peekLocation() const { return m_next_token.location; } - std::string const& peekLiteral() const { return m_next_token.literal; } + Token::Value peekNextToken() const { return m_nextToken.token; } + Location peekLocation() const { return m_nextToken.location; } + std::string const& peekLiteral() const { return m_nextToken.literal; } ///@} + std::shared_ptr const& getSourceName() const { return m_sourceName; } + ///@{ ///@name Error printing helper functions /// Functions that help pretty-printing parse errors @@ -146,7 +153,7 @@ public: ///@} private: - // Used for the current and look-ahead token. + /// Used for the current and look-ahead token and comments struct TokenDesc { Token::Value token; @@ -156,9 +163,8 @@ private: ///@{ ///@name Literal buffer support - inline void startNewLiteral() { m_next_token.literal.clear(); } - inline void addLiteralChar(char c) { m_next_token.literal.push_back(c); } - inline void dropLiteral() { m_next_token.literal.clear(); } + inline void addLiteralChar(char c) { m_nextToken.literal.push_back(c); } + inline void addCommentLiteralChar(char c) { m_nextSkippedComment.literal.push_back(c); } inline void addLiteralCharAndAdvance() { addLiteralChar(m_char); advance(); } ///@} @@ -171,7 +177,7 @@ private: bool scanHexByte(char& o_scannedByte); - /// Scans a single JavaScript token. + /// Scans a single Solidity token. void scanToken(); /// Skips all whitespace and @returns true if something was skipped. @@ -184,6 +190,7 @@ private: Token::Value scanIdentifierOrKeyword(); Token::Value scanString(); + Token::Value scanDocumentationComment(); /// Scans an escape-sequence which is part of a string and adds the /// decoded character to the current literal. Returns true if a pattern @@ -194,10 +201,14 @@ private: int getSourcePos() { return m_source.getPos(); } bool isSourcePastEndOfInput() { return m_source.isPastEndOfInput(); } - TokenDesc m_current_token; // desc for current token (as returned by Next()) - TokenDesc m_next_token; // desc for next token (one token look-ahead) + TokenDesc m_skippedComment; // desc for current skipped comment + TokenDesc m_nextSkippedComment; // desc for next skiped comment + + TokenDesc m_currentToken; // desc for current token (as returned by Next()) + TokenDesc m_nextToken; // desc for next token (one token look-ahead) CharStream m_source; + std::shared_ptr m_sourceName; /// one character look-ahead, equals 0 at end of input char m_char; diff --git a/libsolidity/SourceReferenceFormatter.cpp b/libsolidity/SourceReferenceFormatter.cpp index d3f2152a6..c61f9b685 100644 --- a/libsolidity/SourceReferenceFormatter.cpp +++ b/libsolidity/SourceReferenceFormatter.cpp @@ -21,6 +21,7 @@ */ #include +#include #include #include @@ -38,7 +39,6 @@ void SourceReferenceFormatter::printSourceLocation(ostream& _stream, int startLine; int startColumn; tie(startLine, startColumn) = _scanner.translatePositionToLineColumn(_location.start); - _stream << "starting at line " << (startLine + 1) << ", column " << (startColumn + 1) << "\n"; int endLine; int endColumn; tie(endLine, endColumn) = _scanner.translatePositionToLineColumn(_location.end); @@ -58,37 +58,28 @@ void SourceReferenceFormatter::printSourceLocation(ostream& _stream, << "Spanning multiple lines.\n"; } -void SourceReferenceFormatter::printSourcePosition(ostream& _stream, - int _position, - const Scanner& _scanner) -{ - int line; - int column; - tie(line, column) = _scanner.translatePositionToLineColumn(_position); - _stream << "at line " << (line + 1) << ", column " << (column + 1) << endl - << _scanner.getLineAtPosition(_position) << endl - << string(column, ' ') << "^" << endl; -} - void SourceReferenceFormatter::printExceptionInformation(ostream& _stream, Exception const& _exception, string const& _name, - Scanner const& _scanner) + CompilerStack const& _compiler) { - _stream << _name; - if (string const* description = boost::get_error_info(_exception)) - _stream << ": " << *description; + Location const* location = boost::get_error_info(_exception); + Scanner const* scanner; - if (int const* position = boost::get_error_info(_exception)) + if (location) { - _stream << " "; - printSourcePosition(_stream, *position, _scanner); - } - if (Location const* location = boost::get_error_info(_exception)) - { - _stream << " "; - printSourceLocation(_stream, *location, _scanner); + scanner = &_compiler.getScanner(*location->sourceName); + int startLine; + int startColumn; + tie(startLine, startColumn) = scanner->translatePositionToLineColumn(location->start); + _stream << *location->sourceName << ":" << (startLine + 1) << ":" << (startColumn + 1) << ": "; } + _stream << _name; + if (string const* description = boost::get_error_info(_exception)) + _stream << ": " << *description << endl; + + if (location) + printSourceLocation(_stream, *location, *scanner); } } diff --git a/libsolidity/SourceReferenceFormatter.h b/libsolidity/SourceReferenceFormatter.h index 4736066fd..8e3f126f0 100644 --- a/libsolidity/SourceReferenceFormatter.h +++ b/libsolidity/SourceReferenceFormatter.h @@ -34,14 +34,14 @@ namespace solidity { class Scanner; // forward +class CompilerStack; // forward struct SourceReferenceFormatter { public: static void printSourceLocation(std::ostream& _stream, Location const& _location, Scanner const& _scanner); - static void printSourcePosition(std::ostream& _stream, int _position, Scanner const& _scanner); static void printExceptionInformation(std::ostream& _stream, Exception const& _exception, - std::string const& _name, Scanner const& _scanner); + std::string const& _name, CompilerStack const& _compiler); }; } diff --git a/libsolidity/Token.h b/libsolidity/Token.h index 67971c3d0..22378ae07 100644 --- a/libsolidity/Token.h +++ b/libsolidity/Token.h @@ -160,7 +160,6 @@ namespace solidity K(RETURNS, "returns", 0) \ K(STRUCT, "struct", 0) \ K(SWITCH, "switch", 0) \ - K(THIS, "this", 0) \ K(VAR, "var", 0) \ K(WHILE, "while", 0) \ \ @@ -270,6 +269,39 @@ namespace solidity K(ADDRESS, "address", 0) \ K(BOOL, "bool", 0) \ K(STRING_TYPE, "string", 0) \ + K(STRING0, "string0", 0) \ + K(STRING1, "string1", 0) \ + K(STRING2, "string2", 0) \ + K(STRING3, "string3", 0) \ + K(STRING4, "string4", 0) \ + K(STRING5, "string5", 0) \ + K(STRING6, "string6", 0) \ + K(STRING7, "string7", 0) \ + K(STRING8, "string8", 0) \ + K(STRING9, "string9", 0) \ + K(STRING10, "string10", 0) \ + K(STRING11, "string11", 0) \ + K(STRING12, "string12", 0) \ + K(STRING13, "string13", 0) \ + K(STRING14, "string14", 0) \ + K(STRING15, "string15", 0) \ + K(STRING16, "string16", 0) \ + K(STRING17, "string17", 0) \ + K(STRING18, "string18", 0) \ + K(STRING19, "string19", 0) \ + K(STRING20, "string20", 0) \ + K(STRING21, "string21", 0) \ + K(STRING22, "string22", 0) \ + K(STRING23, "string23", 0) \ + K(STRING24, "string24", 0) \ + K(STRING25, "string25", 0) \ + K(STRING26, "string26", 0) \ + K(STRING27, "string27", 0) \ + K(STRING28, "string28", 0) \ + K(STRING29, "string29", 0) \ + K(STRING30, "string30", 0) \ + K(STRING31, "string31", 0) \ + K(STRING32, "string32", 0) \ K(TEXT, "text", 0) \ K(REAL, "real", 0) \ K(UREAL, "ureal", 0) \ @@ -281,6 +313,7 @@ namespace solidity K(FALSE_LITERAL, "false", 0) \ T(NUMBER, NULL, 0) \ T(STRING_LITERAL, NULL, 0) \ + T(COMMENT_LITERAL, NULL, 0) \ \ /* Identifiers (not keywords or future reserved words). */ \ T(IDENTIFIER, NULL, 0) \ @@ -296,6 +329,9 @@ class Token { public: // All token values. + // attention! msvc issue: + // http://stackoverflow.com/questions/9567868/compile-errors-after-adding-v8-to-my-project-c2143-c2059 + // @todo: avoid TOKEN_LIST macro #define T(name, string, precedence) name, enum Value { @@ -314,25 +350,13 @@ public: } // Predicates - static bool isKeyword(Value tok) { return m_tokenType[tok] == 'K'; } - static bool isIdentifier(Value tok) { return tok == IDENTIFIER; } static bool isElementaryTypeName(Value tok) { return INT <= tok && tok < TYPES_END; } static bool isAssignmentOp(Value tok) { return ASSIGN <= tok && tok <= ASSIGN_MOD; } static bool isBinaryOp(Value op) { return COMMA <= op && op <= MOD; } - static bool isTruncatingBinaryOp(Value op) { return BIT_OR <= op && op <= SHR; } + static bool isCommutativeOp(Value op) { return op == BIT_OR || op == BIT_XOR || op == BIT_AND || + op == ADD || op == MUL || op == EQ || op == NE; } static bool isArithmeticOp(Value op) { return ADD <= op && op <= MOD; } static bool isCompareOp(Value op) { return EQ <= op && op <= IN; } - static bool isOrderedRelationalCompareOp(Value op) - { - return op == LT || op == LTE || op == GT || op == GTE; - } - static bool isEqualityOp(Value op) { return op == EQ; } - static bool isInequalityOp(Value op) { return op == NE; } - static bool isArithmeticCompareOp(Value op) - { - return isOrderedRelationalCompareOp(op) || - isEqualityOp(op) || isInequalityOp(op); - } static Value AssignmentToBinaryOp(Value op) { diff --git a/libsolidity/Types.cpp b/libsolidity/Types.cpp index 3a4112c45..00e530c3f 100644 --- a/libsolidity/Types.cpp +++ b/libsolidity/Types.cpp @@ -32,7 +32,7 @@ namespace dev namespace solidity { -shared_ptr Type::fromElementaryTypeName(Token::Value _typeToken) +shared_ptr Type::fromElementaryTypeName(Token::Value _typeToken) { if (asserts(Token::isElementaryTypeName(_typeToken))) BOOST_THROW_EXCEPTION(InternalCompilerError()); @@ -44,47 +44,65 @@ shared_ptr Type::fromElementaryTypeName(Token::Value _typeToken) if (bytes == 0) bytes = 32; int modifier = offset / 33; - return make_shared(bytes * 8, + return make_shared(bytes * 8, modifier == 0 ? IntegerType::Modifier::SIGNED : modifier == 1 ? IntegerType::Modifier::UNSIGNED : IntegerType::Modifier::HASH); } else if (_typeToken == Token::ADDRESS) - return make_shared(0, IntegerType::Modifier::ADDRESS); + return make_shared(0, IntegerType::Modifier::ADDRESS); else if (_typeToken == Token::BOOL) - return make_shared(); + return make_shared(); + else if (Token::STRING0 <= _typeToken && _typeToken <= Token::STRING32) + return make_shared(int(_typeToken) - int(Token::STRING0)); else BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unable to convert elementary typename " + std::string(Token::toString(_typeToken)) + " to type.")); } -shared_ptr Type::fromUserDefinedTypeName(UserDefinedTypeName const& _typeName) +shared_ptr Type::fromUserDefinedTypeName(UserDefinedTypeName const& _typeName) { - return make_shared(*_typeName.getReferencedStruct()); + Declaration const* declaration = _typeName.getReferencedDeclaration(); + if (StructDefinition const* structDef = dynamic_cast(declaration)) + return make_shared(*structDef); + else if (FunctionDefinition const* function = dynamic_cast(declaration)) + return make_shared(*function); + else if (ContractDefinition const* contract = dynamic_cast(declaration)) + return make_shared(*contract); + return shared_ptr(); } -shared_ptr Type::fromMapping(Mapping const&) +shared_ptr Type::fromMapping(Mapping const& _typeName) { - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Mapping types not yet implemented.")); + shared_ptr keyType = _typeName.getKeyType().toType(); + if (!keyType) + BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Error resolving type name.")); + shared_ptr valueType = _typeName.getValueType().toType(); + if (!valueType) + BOOST_THROW_EXCEPTION(_typeName.getValueType().createTypeError("Invalid type name")); + return make_shared(keyType, valueType); } -shared_ptr Type::forLiteral(Literal const& _literal) +shared_ptr Type::forLiteral(Literal const& _literal) { switch (_literal.getToken()) { case Token::TRUE_LITERAL: case Token::FALSE_LITERAL: - return make_shared(); + return make_shared(); case Token::NUMBER: return IntegerType::smallestTypeForLiteral(_literal.getValue()); case Token::STRING_LITERAL: - return shared_ptr(); // @todo + //@todo put larger strings into dynamic strings + return StaticStringType::smallestTypeForLiteral(_literal.getValue()); default: - return shared_ptr(); + return shared_ptr(); } } -shared_ptr IntegerType::smallestTypeForLiteral(string const& _literal) +const MemberList Type::EmptyMemberList = MemberList(); + +shared_ptr IntegerType::smallestTypeForLiteral(string const& _literal) { bigint value(_literal); bool isSigned = value < 0 || (!_literal.empty() && _literal.front() == '-'); @@ -93,8 +111,8 @@ shared_ptr IntegerType::smallestTypeForLiteral(string const& _liter value = ((-value) - 1) << 1; unsigned bytes = max(bytesRequired(value), 1u); if (bytes > 32) - return shared_ptr(); - return make_shared(bytes * 8, isSigned ? Modifier::SIGNED : Modifier::UNSIGNED); + return shared_ptr(); + return make_shared(bytes * 8, isSigned ? Modifier::SIGNED : Modifier::UNSIGNED); } IntegerType::IntegerType(int _bits, IntegerType::Modifier _modifier): @@ -125,7 +143,7 @@ bool IntegerType::isImplicitlyConvertibleTo(Type const& _convertTo) const bool IntegerType::isExplicitlyConvertibleTo(Type const& _convertTo) const { - return _convertTo.getCategory() == getCategory(); + return _convertTo.getCategory() == getCategory() || _convertTo.getCategory() == Category::CONTRACT; } bool IntegerType::acceptsBinaryOperator(Token::Value _operator) const @@ -174,6 +192,49 @@ u256 IntegerType::literalValue(Literal const& _literal) const return u256(value); } +const MemberList IntegerType::AddressMemberList = + MemberList({{"balance", make_shared(256)}, + {"send", make_shared(TypePointers({make_shared(256)}), + TypePointers(), FunctionType::Location::SEND)}}); + +shared_ptr StaticStringType::smallestTypeForLiteral(string const& _literal) +{ + if (_literal.length() <= 32) + return make_shared(_literal.length()); + return shared_ptr(); +} + +StaticStringType::StaticStringType(int _bytes): m_bytes(_bytes) +{ + if (asserts(m_bytes >= 0 && m_bytes <= 32)) + BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Invalid byte number for static string type: " + + dev::toString(m_bytes))); +} + +bool StaticStringType::isImplicitlyConvertibleTo(Type const& _convertTo) const +{ + if (_convertTo.getCategory() != getCategory()) + return false; + StaticStringType const& convertTo = dynamic_cast(_convertTo); + return convertTo.m_bytes >= m_bytes; +} + +bool StaticStringType::operator==(Type const& _other) const +{ + if (_other.getCategory() != getCategory()) + return false; + StaticStringType const& other = dynamic_cast(_other); + return other.m_bytes == m_bytes; +} + +u256 StaticStringType::literalValue(const Literal& _literal) const +{ + u256 value = 0; + for (char c: _literal.getValue()) + value = (value << 8) | byte(c); + return value << ((32 - _literal.getValue().length()) * 8); +} + bool BoolType::isExplicitlyConvertibleTo(Type const& _convertTo) const { // conversion to integer is fine, but not to address @@ -197,6 +258,15 @@ u256 BoolType::literalValue(Literal const& _literal) const BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Bool type constructed from non-boolean literal.")); } +bool ContractType::isExplicitlyConvertibleTo(Type const& _convertTo) const +{ + if (isImplicitlyConvertibleTo(_convertTo)) + return true; + if (_convertTo.getCategory() == Category::INTEGER) + return dynamic_cast(_convertTo).isAddress(); + return false; +} + bool ContractType::operator==(Type const& _other) const { if (_other.getCategory() != getCategory()) @@ -213,6 +283,36 @@ u256 ContractType::getStorageSize() const return max(1, size); } +string ContractType::toString() const +{ + return "contract " + m_contract.getName(); +} + +MemberList const& ContractType::getMembers() const +{ + // We need to lazy-initialize it because of recursive references. + if (!m_members) + { + map> members; + for (FunctionDefinition const* function: m_contract.getInterfaceFunctions()) + members[function->getName()] = make_shared(*function, false); + m_members.reset(new MemberList(members)); + } + return *m_members; +} + +unsigned ContractType::getFunctionIndex(string const& _functionName) const +{ + unsigned index = 0; + for (FunctionDefinition const* function: m_contract.getInterfaceFunctions()) + { + if (function->getName() == _functionName) + return index; + ++index; + } + BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Index of non-existing contract function requested.")); +} + bool StructType::operator==(Type const& _other) const { if (_other.getCategory() != getCategory()) @@ -224,17 +324,109 @@ bool StructType::operator==(Type const& _other) const u256 StructType::getStorageSize() const { u256 size = 0; - for (ASTPointer const& variable: m_struct.getMembers()) - size += variable->getType()->getStorageSize(); + for (pair> const& member: getMembers()) + size += member.second->getStorageSize(); return max(1, size); } +bool StructType::canLiveOutsideStorage() const +{ + for (pair> const& member: getMembers()) + if (!member.second->canLiveOutsideStorage()) + return false; + return true; +} + +string StructType::toString() const +{ + return string("struct ") + m_struct.getName(); +} + +MemberList const& StructType::getMembers() const +{ + // We need to lazy-initialize it because of recursive references. + if (!m_members) + { + map> members; + for (ASTPointer const& variable: m_struct.getMembers()) + members[variable->getName()] = variable->getType(); + m_members.reset(new MemberList(members)); + } + return *m_members; +} + +u256 StructType::getStorageOffsetOfMember(string const& _name) const +{ + //@todo cache member offset? + u256 offset; + for (ASTPointer variable: m_struct.getMembers()) + { + if (variable->getName() == _name) + return offset; + offset += variable->getType()->getStorageSize(); + } + BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Storage offset of non-existing member requested.")); +} + +FunctionType::FunctionType(FunctionDefinition const& _function, bool _isInternal) +{ + TypePointers params; + TypePointers retParams; + params.reserve(_function.getParameters().size()); + for (ASTPointer const& var: _function.getParameters()) + params.push_back(var->getType()); + retParams.reserve(_function.getReturnParameters().size()); + for (ASTPointer const& var: _function.getReturnParameters()) + retParams.push_back(var->getType()); + swap(params, m_parameterTypes); + swap(retParams, m_returnParameterTypes); + m_location = _isInternal ? Location::INTERNAL : Location::EXTERNAL; +} + bool FunctionType::operator==(Type const& _other) const { if (_other.getCategory() != getCategory()) return false; FunctionType const& other = dynamic_cast(_other); - return other.m_function == m_function; + + if (m_location != other.m_location) + return false; + if (m_parameterTypes.size() != other.m_parameterTypes.size() || + m_returnParameterTypes.size() != other.m_returnParameterTypes.size()) + return false; + auto typeCompare = [](TypePointer const& _a, TypePointer const& _b) -> bool { return *_a == *_b; }; + + if (!equal(m_parameterTypes.cbegin(), m_parameterTypes.cend(), + other.m_parameterTypes.cbegin(), typeCompare)) + return false; + if (!equal(m_returnParameterTypes.cbegin(), m_returnParameterTypes.cend(), + other.m_returnParameterTypes.cbegin(), typeCompare)) + return false; + return true; +} + +string FunctionType::toString() const +{ + string name = "function ("; + for (auto it = m_parameterTypes.begin(); it != m_parameterTypes.end(); ++it) + name += (*it)->toString() + (it + 1 == m_parameterTypes.end() ? "" : ","); + name += ") returns ("; + for (auto it = m_returnParameterTypes.begin(); it != m_returnParameterTypes.end(); ++it) + name += (*it)->toString() + (it + 1 == m_returnParameterTypes.end() ? "" : ","); + return name + ")"; +} + +unsigned FunctionType::getSizeOnStack() const +{ + switch (m_location) + { + case Location::INTERNAL: + return 1; + case Location::EXTERNAL: + return 2; + default: + return 0; + } } bool MappingType::operator==(Type const& _other) const @@ -245,6 +437,11 @@ bool MappingType::operator==(Type const& _other) const return *other.m_keyType == *m_keyType && *other.m_valueType == *m_valueType; } +string MappingType::toString() const +{ + return "mapping(" + getKeyType()->toString() + " => " + getValueType()->toString() + ")"; +} + bool TypeType::operator==(Type const& _other) const { if (_other.getCategory() != getCategory()) @@ -253,5 +450,55 @@ bool TypeType::operator==(Type const& _other) const return *getActualType() == *other.getActualType(); } +MagicType::MagicType(MagicType::Kind _kind): + m_kind(_kind) +{ + switch (m_kind) + { + case Kind::BLOCK: + m_members = MemberList({{"coinbase", make_shared(0, IntegerType::Modifier::ADDRESS)}, + {"timestamp", make_shared(256)}, + {"prevhash", make_shared(256, IntegerType::Modifier::HASH)}, + {"difficulty", make_shared(256)}, + {"number", make_shared(256)}, + {"gaslimit", make_shared(256)}}); + break; + case Kind::MSG: + m_members = MemberList({{"sender", make_shared(0, IntegerType::Modifier::ADDRESS)}, + {"gas", make_shared(256)}, + {"value", make_shared(256)}}); + break; + case Kind::TX: + m_members = MemberList({{"origin", make_shared(0, IntegerType::Modifier::ADDRESS)}, + {"gasprice", make_shared(256)}}); + break; + default: + BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unknown kind of magic.")); + } +} + +bool MagicType::operator==(Type const& _other) const +{ + if (_other.getCategory() != getCategory()) + return false; + MagicType const& other = dynamic_cast(_other); + return other.m_kind == m_kind; +} + +string MagicType::toString() const +{ + switch (m_kind) + { + case Kind::BLOCK: + return "block"; + case Kind::MSG: + return "msg"; + case Kind::TX: + return "tx"; + default: + BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unknown kind of magic.")); + } +} + } } diff --git a/libsolidity/Types.h b/libsolidity/Types.h index 607ee3a6f..8e93bd31d 100644 --- a/libsolidity/Types.h +++ b/libsolidity/Types.h @@ -24,6 +24,7 @@ #include #include +#include #include #include #include @@ -35,7 +36,35 @@ namespace dev namespace solidity { -// @todo realMxN, string, mapping +// @todo realMxN, dynamic strings, text, arrays + +class Type; // forward +using TypePointer = std::shared_ptr; +using TypePointers = std::vector; + +/** + * List of members of a type. + */ +class MemberList +{ +public: + using MemberMap = std::map; + + MemberList() {} + explicit MemberList(MemberMap const& _members): m_memberTypes(_members) {} + TypePointer getMemberType(std::string const& _name) const + { + auto it = m_memberTypes.find(_name); + return it != m_memberTypes.end() ? it->second : TypePointer(); + } + + MemberMap::const_iterator begin() const { return m_memberTypes.begin(); } + MemberMap::const_iterator end() const { return m_memberTypes.end(); } + +private: + MemberMap m_memberTypes; +}; + /** * Abstract base class that forms the root of the type hierarchy. @@ -45,20 +74,21 @@ class Type: private boost::noncopyable public: enum class Category { - INTEGER, BOOL, REAL, STRING, CONTRACT, STRUCT, FUNCTION, MAPPING, VOID, TYPE + INTEGER, BOOL, REAL, STRING, CONTRACT, STRUCT, FUNCTION, MAPPING, VOID, TYPE, MAGIC }; ///@{ ///@name Factory functions /// Factory functions that convert an AST @ref TypeName to a Type. - static std::shared_ptr fromElementaryTypeName(Token::Value _typeToken); - static std::shared_ptr fromUserDefinedTypeName(UserDefinedTypeName const& _typeName); - static std::shared_ptr fromMapping(Mapping const& _typeName); + static std::shared_ptr fromElementaryTypeName(Token::Value _typeToken); + static std::shared_ptr fromUserDefinedTypeName(UserDefinedTypeName const& _typeName); + static std::shared_ptr fromMapping(Mapping const& _typeName); + static std::shared_ptr fromFunction(FunctionDefinition const& _function); /// @} /// Auto-detect the proper type for a literal. @returns an empty pointer if the literal does /// not fit any type. - static std::shared_ptr forLiteral(Literal const& _literal); + static std::shared_ptr forLiteral(Literal const& _literal); virtual Category getCategory() const = 0; virtual bool isImplicitlyConvertibleTo(Type const& _other) const { return *this == _other; } @@ -78,6 +108,19 @@ public: /// @returns number of bytes required to hold this value in storage. /// For dynamically "allocated" types, it returns the size of the statically allocated head, virtual u256 getStorageSize() const { return 1; } + /// Returns true if the type can be stored in storage. + virtual bool canBeStored() const { return true; } + /// Returns false if the type cannot live outside the storage, i.e. if it includes some mapping. + virtual bool canLiveOutsideStorage() const { return true; } + /// Returns true if the type can be stored as a value (as opposed to a reference) on the stack, + /// i.e. it behaves differently in lvalue context and in value context. + virtual bool isValueType() const { return false; } + virtual unsigned getSizeOnStack() const { return 1; } + + /// Returns the list of all members of this type. Default implementation: no members. + virtual MemberList const& getMembers() const { return EmptyMemberList; } + /// Convenience method, returns the type of the given named member or an empty pointer if no such member exists. + TypePointer getMemberType(std::string const& _name) const { return getMembers().getMemberType(_name); } virtual std::string toString() const = 0; virtual u256 literalValue(Literal const&) const @@ -85,6 +128,10 @@ public: BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Literal value requested " "for type without literals.")); } + +protected: + /// Convenience object used when returning an empty member list. + static const MemberList EmptyMemberList; }; /** @@ -101,7 +148,7 @@ public: /// @returns the smallest integer type for the given literal or an empty pointer /// if no type fits. - static std::shared_ptr smallestTypeForLiteral(std::string const& _literal); + static std::shared_ptr smallestTypeForLiteral(std::string const& _literal); explicit IntegerType(int _bits, Modifier _modifier = Modifier::UNSIGNED); @@ -112,7 +159,10 @@ public: virtual bool operator==(Type const& _other) const override; - virtual unsigned getCalldataEncodedSize() const { return m_bits / 8; } + virtual unsigned getCalldataEncodedSize() const override { return m_bits / 8; } + virtual bool isValueType() const override { return true; } + + virtual MemberList const& getMembers() const { return isAddress() ? AddressMemberList : EmptyMemberList; } virtual std::string toString() const override; virtual u256 literalValue(Literal const& _literal) const override; @@ -125,6 +175,36 @@ public: private: int m_bits; Modifier m_modifier; + static const MemberList AddressMemberList; +}; + +/** + * String type with fixed length, up to 32 bytes. + */ +class StaticStringType: public Type +{ +public: + virtual Category getCategory() const override { return Category::STRING; } + + /// @returns the smallest string type for the given literal or an empty pointer + /// if no type fits. + static std::shared_ptr smallestTypeForLiteral(std::string const& _literal); + + StaticStringType(int _bytes); + + virtual bool isImplicitlyConvertibleTo(Type const& _convertTo) const override; + virtual bool operator==(Type const& _other) const override; + + virtual unsigned getCalldataEncodedSize() const override { return m_bytes; } + virtual bool isValueType() const override { return true; } + + virtual std::string toString() const override { return "string" + dev::toString(m_bytes); } + virtual u256 literalValue(Literal const& _literal) const override; + + int getNumBytes() const { return m_bytes; } + +private: + int m_bytes; }; /** @@ -133,6 +213,7 @@ private: class BoolType: public Type { public: + BoolType() {} virtual Category getCategory() const { return Category::BOOL; } virtual bool isExplicitlyConvertibleTo(Type const& _convertTo) const override; virtual bool acceptsBinaryOperator(Token::Value _operator) const override @@ -145,6 +226,7 @@ public: } virtual unsigned getCalldataEncodedSize() const { return 1; } + virtual bool isValueType() const override { return true; } virtual std::string toString() const override { return "bool"; } virtual u256 literalValue(Literal const& _literal) const override; @@ -158,13 +240,21 @@ class ContractType: public Type public: virtual Category getCategory() const override { return Category::CONTRACT; } ContractType(ContractDefinition const& _contract): m_contract(_contract) {} - + /// Contracts can be converted to themselves and to addresses. + virtual bool isExplicitlyConvertibleTo(Type const& _convertTo) const override; virtual bool operator==(Type const& _other) const override; - virtual u256 getStorageSize() const; - virtual std::string toString() const override { return "contract{...}"; } + virtual u256 getStorageSize() const override; + virtual bool isValueType() const override { return true; } + virtual std::string toString() const override; + + virtual MemberList const& getMembers() const override; + + unsigned getFunctionIndex(std::string const& _functionName) const; private: ContractDefinition const& m_contract; + /// List of member types, will be lazy-initialized because of recursive references. + mutable std::unique_ptr m_members; }; /** @@ -181,30 +271,57 @@ public: } virtual bool operator==(Type const& _other) const override; - virtual u256 getStorageSize() const; - virtual std::string toString() const override { return "struct{...}"; } + virtual u256 getStorageSize() const override; + virtual bool canLiveOutsideStorage() const override; + virtual unsigned getSizeOnStack() const override { return 1; /*@todo*/ } + virtual std::string toString() const override; + + virtual MemberList const& getMembers() const override; + + u256 getStorageOffsetOfMember(std::string const& _name) const; private: StructDefinition const& m_struct; + /// List of member types, will be lazy-initialized because of recursive references. + mutable std::unique_ptr m_members; }; /** - * The type of a function, there is one distinct type per function definition. + * The type of a function, identified by its (return) parameter types. + * @todo the return parameters should also have names, i.e. return parameters should be a struct + * type. */ class FunctionType: public Type { public: + /// The meaning of the value(s) on the stack referencing the function: + /// INTERNAL: jump tag, EXTERNAL: contract address + function index, + /// OTHERS: special virtual function, nothing on the stack + enum class Location { INTERNAL, EXTERNAL, SEND, SHA3, SUICIDE, ECRECOVER, SHA256, RIPEMD160 }; + virtual Category getCategory() const override { return Category::FUNCTION; } - FunctionType(FunctionDefinition const& _function): m_function(_function) {} + explicit FunctionType(FunctionDefinition const& _function, bool _isInternal = true); + FunctionType(TypePointers const& _parameterTypes, TypePointers const& _returnParameterTypes, + Location _location = Location::INTERNAL): + m_parameterTypes(_parameterTypes), m_returnParameterTypes(_returnParameterTypes), + m_location(_location) {} - FunctionDefinition const& getFunction() const { return m_function; } + TypePointers const& getParameterTypes() const { return m_parameterTypes; } + TypePointers const& getReturnParameterTypes() const { return m_returnParameterTypes; } virtual bool operator==(Type const& _other) const override; - virtual std::string toString() const override { return "function(...)returns(...)"; } - virtual u256 getStorageSize() const { BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Storage size of non-storable function type requested.")); } + virtual std::string toString() const override; + virtual bool canBeStored() const override { return false; } + virtual u256 getStorageSize() const override { BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Storage size of non-storable function type requested.")); } + virtual bool canLiveOutsideStorage() const override { return false; } + virtual unsigned getSizeOnStack() const override; + + Location const& getLocation() const { return m_location; } private: - FunctionDefinition const& m_function; + TypePointers m_parameterTypes; + TypePointers m_returnParameterTypes; + Location m_location; }; /** @@ -214,14 +331,19 @@ class MappingType: public Type { public: virtual Category getCategory() const override { return Category::MAPPING; } - MappingType() {} + MappingType(TypePointer const& _keyType, TypePointer const& _valueType): + m_keyType(_keyType), m_valueType(_valueType) {} virtual bool operator==(Type const& _other) const override; - virtual std::string toString() const override { return "mapping(...=>...)"; } + virtual std::string toString() const override; + virtual bool canLiveOutsideStorage() const override { return false; } + + TypePointer getKeyType() const { return m_keyType; } + TypePointer getValueType() const { return m_valueType; } private: - std::shared_ptr m_keyType; - std::shared_ptr m_valueType; + TypePointer m_keyType; + TypePointer m_valueType; }; /** @@ -235,7 +357,10 @@ public: VoidType() {} virtual std::string toString() const override { return "void"; } - virtual u256 getStorageSize() const { BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Storage size of non-storable void type requested.")); } + virtual bool canBeStored() const override { return false; } + virtual u256 getStorageSize() const override { BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Storage size of non-storable void type requested.")); } + virtual bool canLiveOutsideStorage() const override { return false; } + virtual unsigned getSizeOnStack() const override { return 0; } }; /** @@ -246,18 +371,45 @@ class TypeType: public Type { public: virtual Category getCategory() const override { return Category::TYPE; } - TypeType(std::shared_ptr const& _actualType): m_actualType(_actualType) {} + TypeType(TypePointer const& _actualType): m_actualType(_actualType) {} - std::shared_ptr const& getActualType() const { return m_actualType; } + TypePointer const& getActualType() const { return m_actualType; } virtual bool operator==(Type const& _other) const override; - virtual u256 getStorageSize() const { BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Storage size of non-storable type type requested.")); } + virtual bool canBeStored() const override { return false; } + virtual u256 getStorageSize() const override { BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Storage size of non-storable type type requested.")); } + virtual bool canLiveOutsideStorage() const override { return false; } virtual std::string toString() const override { return "type(" + m_actualType->toString() + ")"; } private: - std::shared_ptr m_actualType; + TypePointer m_actualType; }; +/** + * Special type for magic variables (block, msg, tx), similar to a struct but without any reference + * (it always references a global singleton by name). + */ +class MagicType: public Type +{ +public: + enum class Kind { BLOCK, MSG, TX }; + virtual Category getCategory() const override { return Category::MAGIC; } + + MagicType(Kind _kind); + virtual bool operator==(Type const& _other) const; + virtual bool canBeStored() const override { return false; } + virtual bool canLiveOutsideStorage() const override { return true; } + virtual unsigned getSizeOnStack() const override { return 0; } + virtual MemberList const& getMembers() const override { return m_members; } + + virtual std::string toString() const override; + +private: + Kind m_kind; + + MemberList m_members; +}; + } } diff --git a/libweb3jsonrpc/CMakeLists.txt b/libweb3jsonrpc/CMakeLists.txt index b24a11196..f371024e6 100644 --- a/libweb3jsonrpc/CMakeLists.txt +++ b/libweb3jsonrpc/CMakeLists.txt @@ -1,53 +1,36 @@ cmake_policy(SET CMP0015 NEW) +# this policy was introduced in cmake 3.0 +# remove if, once 3.0 will be used on unix +if (${CMAKE_MAJOR_VERSION} GREATER 2) + # old policy do not use MACOSX_RPATH + cmake_policy(SET CMP0042 OLD) +endif() +set(CMAKE_AUTOMOC OFF) aux_source_directory(. SRC_LIST) +include_directories(${JSON_RPC_CPP_INCLUDE_DIRS}) +include_directories(${LEVELDB_INCLUDE_DIRS}) include_directories(..) -link_directories(../libethcore) -link_directories(../libwebthree) set(EXECUTABLE web3jsonrpc) + file(GLOB HEADERS "*.h") -if(ETH_STATIC) +if (ETH_STATIC) add_library(${EXECUTABLE} STATIC ${SRC_LIST} ${HEADERS}) else() add_library(${EXECUTABLE} SHARED ${SRC_LIST} ${HEADERS}) endif() +target_link_libraries(${EXECUTABLE} ${LEVELDB_LIBRARIES}) +target_link_libraries(${EXECUTABLE} ${JSONCPP_LIBRARIES}) +target_link_libraries(${EXECUTABLE} ${JSON_RPC_CPP_SERVER_LIBRARIES}) + target_link_libraries(${EXECUTABLE} webthree) target_link_libraries(${EXECUTABLE} secp256k1) -target_link_libraries(${EXECUTABLE} gmp) -if(MINIUPNPC_LS) - target_link_libraries(${EXECUTABLE} ${MINIUPNPC_LS}) -endif() -target_link_libraries(${EXECUTABLE} ${LEVELDB_LS}) -target_link_libraries(${EXECUTABLE} ${CRYPTOPP_LS}) -target_link_libraries(${EXECUTABLE} ${JSONRPC_LS}) -target_link_libraries(${EXECUTABLE} ${LEVELDB_LS}) -if(READLINE_LS) -target_link_libraries(${EXECUTABLE} ${READLINE_LS}) -endif() - -if ("${TARGET_PLATFORM}" STREQUAL "w64") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -static-libgcc -static-libstdc++") - target_link_libraries(${EXECUTABLE} boost_system-mt-s) - target_link_libraries(${EXECUTABLE} boost_filesystem-mt-s) - target_link_libraries(${EXECUTABLE} boost_thread_win32-mt-s) - target_link_libraries(${EXECUTABLE} gcc) - target_link_libraries(${EXECUTABLE} gdi32) - target_link_libraries(${EXECUTABLE} ws2_32) - target_link_libraries(${EXECUTABLE} mswsock) - target_link_libraries(${EXECUTABLE} shlwapi) - target_link_libraries(${EXECUTABLE} iphlpapi) - set(CMAKE_SHARED_LIBRARY_LINK_CXX_FLAGS) -elseif (UNIX) -else () - target_link_libraries(${EXECUTABLE} boost_system) - target_link_libraries(${EXECUTABLE} boost_filesystem) - find_package(Threads REQUIRED) - target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT}) -endif () +target_link_libraries(${EXECUTABLE} solidity) +target_link_libraries(${EXECUTABLE} serpent) install( TARGETS ${EXECUTABLE} ARCHIVE DESTINATION lib LIBRARY DESTINATION lib ) install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} ) diff --git a/libweb3jsonrpc/CorsHttpServer.h b/libweb3jsonrpc/CorsHttpServer.h index d3bd8a6e9..e697ecaa1 100644 --- a/libweb3jsonrpc/CorsHttpServer.h +++ b/libweb3jsonrpc/CorsHttpServer.h @@ -19,7 +19,7 @@ * @date 2014 */ -#include +#include namespace jsonrpc { diff --git a/libweb3jsonrpc/WebThreeStubServer.cpp b/libweb3jsonrpc/WebThreeStubServer.cpp index 3849fb4a8..fc1bd28d1 100644 --- a/libweb3jsonrpc/WebThreeStubServer.cpp +++ b/libweb3jsonrpc/WebThreeStubServer.cpp @@ -21,6 +21,9 @@ * @date 2014 */ +#include +#include +#include #include "WebThreeStubServer.h" #include #include @@ -31,6 +34,7 @@ #include #include #include +#include using namespace std; using namespace dev; @@ -47,7 +51,6 @@ static Json::Value toJson(dev::eth::BlockInfo const& _bi) res["transactionsRoot"] = toJS(_bi.transactionsRoot); res["difficulty"] = toJS(_bi.difficulty); res["number"] = (int)_bi.number; - res["minGasPrice"] = toJS(_bi.minGasPrice); res["gasLimit"] = (int)_bi.gasLimit; res["timestamp"] = (int)_bi.timestamp; res["extraData"] = jsFromBinary(_bi.extraData); @@ -55,34 +58,6 @@ static Json::Value toJson(dev::eth::BlockInfo const& _bi) return res; } -static Json::Value toJson(dev::eth::PastMessage const& _t) -{ - Json::Value res; - res["input"] = jsFromBinary(_t.input); - res["output"] = jsFromBinary(_t.output); - res["to"] = toJS(_t.to); - res["from"] = toJS(_t.from); - res["value"] = jsToDecimal(toJS(_t.value)); - res["origin"] = toJS(_t.origin); - res["timestamp"] = toJS(_t.timestamp); - res["coinbase"] = toJS(_t.coinbase); - res["block"] = toJS(_t.block); - Json::Value path; - for (int i: _t.path) - path.append(i); - res["path"] = path; - res["number"] = (int)_t.number; - return res; -} - -static Json::Value toJson(dev::eth::PastMessages const& _pms) -{ - Json::Value res; - for (dev::eth::PastMessage const& t: _pms) - res.append(toJson(t)); - return res; -} - static Json::Value toJson(dev::eth::Transaction const& _t) { Json::Value res; @@ -100,6 +75,7 @@ static Json::Value toJson(dev::eth::Transaction const& _t) static Json::Value toJson(dev::eth::LogEntry const& _e) { Json::Value res; + res["data"] = jsFromBinary(_e.data); res["address"] = toJS(_e.address); for (auto const& t: _e.topics) @@ -107,7 +83,7 @@ static Json::Value toJson(dev::eth::LogEntry const& _e) return res; } -/*static*/ Json::Value toJson(dev::eth::LogEntries const& _es) // commented to avoid warning. Uncomment once in use @ poC-7. +static Json::Value toJson(dev::eth::LogEntries const& _es) // commented to avoid warning. Uncomment once in use @ poC-7. { Json::Value res; for (dev::eth::LogEntry const& e: _es) @@ -115,81 +91,38 @@ static Json::Value toJson(dev::eth::LogEntry const& _e) return res; } -static dev::eth::MessageFilter toMessageFilter(Json::Value const& _json) +static Json::Value toJson(std::map const& _storage) { - dev::eth::MessageFilter filter; - if (!_json.isObject() || _json.empty()) - return filter; - - if (!_json["earliest"].empty()) - filter.withEarliest(_json["earliest"].asInt()); - if (!_json["latest"].empty()) - filter.withLatest(_json["lastest"].asInt()); - if (!_json["max"].empty()) - filter.withMax(_json["max"].asInt()); - if (!_json["skip"].empty()) - filter.withSkip(_json["skip"].asInt()); - if (!_json["from"].empty()) - { - if (_json["from"].isArray()) - for (auto i : _json["from"]) - filter.from(jsToAddress(i.asString())); - else - filter.from(jsToAddress(_json["from"].asString())); - } - if (!_json["to"].empty()) - { - if (_json["to"].isArray()) - for (auto i : _json["to"]) - filter.to(jsToAddress(i.asString())); - else - filter.to(jsToAddress(_json["to"].asString())); - } - if (!_json["altered"].empty()) - { - if (_json["altered"].isArray()) - for (auto i: _json["altered"]) - if (i.isObject()) - filter.altered(jsToAddress(i["id"].asString()), jsToU256(i["at"].asString())); - else - filter.altered((jsToAddress(i.asString()))); - else if (_json["altered"].isObject()) - filter.altered(jsToAddress(_json["altered"]["id"].asString()), jsToU256(_json["altered"]["at"].asString())); - else - filter.altered(jsToAddress(_json["altered"].asString())); - } - return filter; + Json::Value res(Json::objectValue); + for (auto i: _storage) + res[toJS(i.first)] = toJS(i.second); + return res; } -/*static*/ dev::eth::LogFilter toLogFilter(Json::Value const& _json) // commented to avoid warning. Uncomment once in use @ PoC-7. +static dev::eth::LogFilter toLogFilter(Json::Value const& _json) // commented to avoid warning. Uncomment once in use @ PoC-7. { dev::eth::LogFilter filter; if (!_json.isObject() || _json.empty()) return filter; - if (!_json["earliest"].empty()) + if (_json["earliest"].isInt()) filter.withEarliest(_json["earliest"].asInt()); - if (!_json["latest"].empty()) + if (_json["latest"].isInt()) filter.withLatest(_json["lastest"].asInt()); - if (!_json["max"].empty()) + if (_json["max"].isInt()) filter.withMax(_json["max"].asInt()); - if (!_json["skip"].empty()) + if (_json["skip"].isInt()) filter.withSkip(_json["skip"].asInt()); - if (!_json["from"].empty()) - { - if (_json["from"].isArray()) - for (auto i : _json["from"]) - filter.from(jsToAddress(i.asString())); - else - filter.from(jsToAddress(_json["from"].asString())); - } if (!_json["address"].empty()) { if (_json["address"].isArray()) + { for (auto i : _json["address"]) - filter.address(jsToAddress(i.asString())); - else - filter.from(jsToAddress(_json["address"].asString())); + if (i.isString()) + filter.address(jsToAddress(i.asString())); + } + else if (_json["address"].isString()) + filter.address(jsToAddress(_json["address"].asString())); } if (!_json["topics"].empty()) { @@ -208,11 +141,11 @@ static dev::eth::MessageFilter toMessageFilter(Json::Value const& _json) static shh::Message toMessage(Json::Value const& _json) { shh::Message ret; - if (!_json["from"].empty()) + if (_json["from"].isString()) ret.setFrom(jsToPublic(_json["from"].asString())); - if (!_json["to"].empty()) + if (_json["to"].isString()) ret.setTo(jsToPublic(_json["to"].asString())); - if (!_json["payload"].empty()) + if (_json["payload"].isString()) ret.setPayload(jsToBytes(_json["payload"].asString())); return ret; } @@ -223,9 +156,9 @@ static shh::Envelope toSealed(Json::Value const& _json, shh::Message const& _m, unsigned workToProve = 50; shh::BuildTopic bt; - if (!_json["ttl"].empty()) + if (_json["ttl"].isInt()) ttl = _json["ttl"].asInt(); - if (!_json["workToProve"].empty()) + if (_json["workToProve"].isInt()) workToProve = _json["workToProve"].asInt(); if (!_json["topic"].empty()) { @@ -233,17 +166,18 @@ static shh::Envelope toSealed(Json::Value const& _json, shh::Message const& _m, bt.shift(jsToBytes(_json["topic"].asString())); else if (_json["topic"].isArray()) for (auto i: _json["topic"]) - bt.shift(jsToBytes(i.asString())); + if (i.isString()) + bt.shift(jsToBytes(i.asString())); } return _m.seal(_from, bt, ttl, workToProve); } static pair toWatch(Json::Value const& _json) { - shh::BuildTopicMask bt(shh::BuildTopicMask::Empty); + shh::BuildTopicMask bt; Public to; - if (!_json["to"].empty()) + if (_json["to"].isString()) to = jsToPublic(_json["to"].asString()); if (!_json["topic"].empty()) @@ -252,12 +186,8 @@ static pair toWatch(Json::Value const& _json) bt.shift(jsToBytes(_json["topic"].asString())); else if (_json["topic"].isArray()) for (auto i: _json["topic"]) - { if (i.isString()) bt.shift(jsToBytes(i.asString())); - else - bt.shift(); - } } return make_pair(bt.toTopicMask(), to); } @@ -271,15 +201,14 @@ static Json::Value toJson(h256 const& _h, shh::Envelope const& _e, shh::Message res["ttl"] = (int)_e.ttl(); res["workProved"] = (int)_e.workProved(); for (auto const& t: _e.topics()) - res["topics"].append(toJS((u256)t)); + res["topics"].append(toJS(t)); res["payload"] = toJS(_m.payload()); res["from"] = toJS(_m.from()); res["to"] = toJS(_m.to()); return res; } - -WebThreeStubServer::WebThreeStubServer(jsonrpc::AbstractServerConnector* _conn, WebThreeDirect& _web3, std::vector const& _accounts): +WebThreeStubServer::WebThreeStubServer(jsonrpc::AbstractServerConnector& _conn, WebThreeDirect& _web3, std::vector const& _accounts): AbstractWebThreeStubServer(_conn), m_web3(_web3) { @@ -356,33 +285,42 @@ static TransactionSkeleton toTransaction(Json::Value const& _json) if (!_json.isObject() || _json.empty()) return ret; - if (!_json["from"].empty()) + if (_json["from"].isString()) ret.from = jsToAddress(_json["from"].asString()); - if (!_json["to"].empty()) + if (_json["to"].isString()) ret.to = jsToAddress(_json["to"].asString()); if (!_json["value"].empty()) - ret.value = jsToU256(_json["value"].asString()); + { + if (_json["value"].isString()) + ret.value = jsToU256(_json["value"].asString()); + else if (_json["value"].isInt()) + ret.value = u256(_json["value"].asInt()); + } if (!_json["gas"].empty()) - ret.gas = jsToU256(_json["gas"].asString()); + { + if (_json["gas"].isString()) + ret.gas = jsToU256(_json["gas"].asString()); + else if (_json["gas"].isInt()) + ret.gas = u256(_json["gas"].asInt()); + } if (!_json["gasPrice"].empty()) - ret.gasPrice = jsToU256(_json["gasPrice"].asString()); - - if (!_json["data"].empty() || _json["code"].empty() || _json["dataclose"].empty()) { - if (_json["data"].isString()) + if (_json["gasPrice"].isString()) + ret.gasPrice = jsToU256(_json["gasPrice"].asString()); + else if (_json["gasPrice"].isInt()) + ret.gas = u256(_json["gas"].asInt()); + } + if (!_json["data"].empty()) + { + if (_json["data"].isString()) // ethereum.js has preconstructed the data array ret.data = jsToBytes(_json["data"].asString()); - else if (_json["code"].isString()) - ret.data = jsToBytes(_json["code"].asString()); - else if (_json["data"].isArray()) + else if (_json["data"].isArray()) // old style: array of 32-byte-padded values. TODO: remove PoC-8 for (auto i: _json["data"]) - dev::operator +=(ret.data, jsToBytes(jsPadded(i.asString(), 32))); - else if (_json["code"].isArray()) - for (auto i: _json["code"]) - dev::operator +=(ret.data, jsToBytes(jsPadded(i.asString(), 32))); - else if (_json["dataclose"].isArray()) - for (auto i: _json["dataclose"]) - dev::operator +=(ret.data, jsToBytes(i.asString())); + dev::operator +=(ret.data, padded(jsToBytes(i.asString()), 32)); } + + if (_json["code"].isString()) + ret.data = jsToBytes(_json["code"].asString()); return ret; } @@ -452,11 +390,18 @@ std::string WebThreeStubServer::db_get(std::string const& _name, std::string con return toJS(dev::asBytes(ret)); } -Json::Value WebThreeStubServer::eth_getMessages(int const& _id) +Json::Value WebThreeStubServer::eth_filterLogs(int const& _id) { if (!client()) - return Json::Value(); - return toJson(client()->messages(_id)); + return Json::Value(Json::arrayValue); + return toJson(client()->logs(_id)); +} + +Json::Value WebThreeStubServer::eth_logs(Json::Value const& _json) +{ + if (!client()) + return Json::Value(Json::arrayValue); + return toJson(client()->logs(toLogFilter(_json))); } std::string WebThreeStubServer::db_getString(std::string const& _name, std::string const& _key) @@ -487,7 +432,8 @@ int WebThreeStubServer::eth_newFilter(Json::Value const& _json) unsigned ret = -1; if (!client()) return ret; - ret = client()->installWatch(toMessageFilter(_json)); +// ret = client()->installWatch(toMessageFilter(_json)); + ret = client()->installWatch(toLogFilter(_json)); return ret; } @@ -512,20 +458,67 @@ std::string WebThreeStubServer::shh_newGroup(std::string const& _id, std::string std::string WebThreeStubServer::shh_newIdentity() { - cnote << this << m_ids; +// cnote << this << m_ids; KeyPair kp = KeyPair::create(); m_ids[kp.pub()] = kp.secret(); return toJS(kp.pub()); } -std::string WebThreeStubServer::eth_compile(string const& _s) +Json::Value WebThreeStubServer::eth_compilers() +{ + Json::Value ret(Json::arrayValue); + ret.append("lll"); + ret.append("solidity"); + ret.append("serpent"); + return ret; +} + +std::string WebThreeStubServer::eth_lll(std::string const& _code) +{ + string res; + vector errors; + res = toJS(dev::eth::compileLLL(_code, true, &errors)); + cwarn << "LLL compilation errors: " << errors; + return res; +} + +std::string WebThreeStubServer::eth_serpent(std::string const& _code) { - return toJS(dev::eth::compileLLL(_s)); + string res; + try + { + res = toJS(dev::asBytes(::compile(_code))); + } + catch (string err) + { + cwarn << "Solidity compilation error: " << err; + } + catch (...) + { + cwarn << "Uncought serpent compilation exception"; + } + return res; } -std::string WebThreeStubServer::eth_lll(string const& _s) +std::string WebThreeStubServer::eth_solidity(std::string const& _code) { - return toJS(dev::eth::compileLLL(_s)); + string res; + dev::solidity::CompilerStack compiler; + try + { + res = toJS(compiler.compile(_code, true)); + } + catch (dev::Exception const& exception) + { + ostringstream error; + solidity::SourceReferenceFormatter::printExceptionInformation(error, exception, "Error", compiler); + cwarn << "Solidity compilation error: " << error.str(); + } + catch (...) + { + cwarn << "Uncought solidity compilation exception"; + } + return res; } int WebThreeStubServer::eth_number() @@ -540,7 +533,7 @@ int WebThreeStubServer::eth_peerCount() bool WebThreeStubServer::shh_post(Json::Value const& _json) { - cnote << this << m_ids; +// cnote << this << m_ids; shh::Message m = toMessage(_json); Secret from; @@ -652,6 +645,13 @@ std::string WebThreeStubServer::eth_stateAt(string const& _address, string const return client() ? toJS(client()->stateAt(jsToAddress(_address), jsToU256(_storage), block)) : ""; } +Json::Value WebThreeStubServer::eth_storageAt(string const& _address) +{ + if (!client()) + return Json::Value(Json::objectValue); + return toJson(client()->storageAt(jsToAddress(_address))); +} + std::string WebThreeStubServer::eth_transact(Json::Value const& _json) { std::string ret; diff --git a/libweb3jsonrpc/WebThreeStubServer.h b/libweb3jsonrpc/WebThreeStubServer.h index 10ca2fd76..474fda9af 100644 --- a/libweb3jsonrpc/WebThreeStubServer.h +++ b/libweb3jsonrpc/WebThreeStubServer.h @@ -29,7 +29,7 @@ #pragma warning(pop) #include -#include +#include #include #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" @@ -62,7 +62,7 @@ class Interface; class WebThreeStubServer: public AbstractWebThreeStubServer { public: - WebThreeStubServer(jsonrpc::AbstractServerConnector* _conn, dev::WebThreeDirect& _web3, std::vector const& _accounts); + WebThreeStubServer(jsonrpc::AbstractServerConnector& _conn, dev::WebThreeDirect& _web3, std::vector const& _accounts); virtual Json::Value eth_accounts(); virtual std::string eth_balanceAt(std::string const& _address); @@ -72,11 +72,12 @@ public: virtual bool eth_changed(int const& _id); virtual std::string eth_codeAt(std::string const& _address); virtual std::string eth_coinbase(); - virtual std::string eth_compile(std::string const& _s); + virtual Json::Value eth_compilers(); virtual double eth_countAt(std::string const& _address); virtual int eth_defaultBlock(); virtual std::string eth_gasPrice(); - virtual Json::Value eth_getMessages(int const& _id); + virtual Json::Value eth_filterLogs(int const& _id); + virtual Json::Value eth_logs(Json::Value const& _json); virtual bool eth_listening(); virtual bool eth_mining(); virtual int eth_newFilter(Json::Value const& _json); @@ -87,8 +88,11 @@ public: virtual bool eth_setDefaultBlock(int const& _block); virtual bool eth_setListening(bool const& _listening); virtual std::string eth_lll(std::string const& _s); + virtual std::string eth_serpent(std::string const& _s); virtual bool eth_setMining(bool const& _mining); + virtual std::string eth_solidity(std::string const& _code); virtual std::string eth_stateAt(std::string const& _address, std::string const& _storage); + virtual Json::Value eth_storageAt(std::string const& _address); virtual std::string eth_transact(Json::Value const& _json); virtual Json::Value eth_transactionByHash(std::string const& _hash, int const& _i); virtual Json::Value eth_transactionByNumber(int const& _number, int const& _i); diff --git a/libweb3jsonrpc/abstractwebthreestubserver.h b/libweb3jsonrpc/abstractwebthreestubserver.h index dc99ddcc6..a4be6aa45 100644 --- a/libweb3jsonrpc/abstractwebthreestubserver.h +++ b/libweb3jsonrpc/abstractwebthreestubserver.h @@ -1,323 +1,311 @@ /** - * THIS FILE IS GENERATED BY jsonrpcstub, DO NOT CHANGE IT!!!!! + * This file is generated by jsonrpcstub, DO NOT CHANGE IT MANUALLY! */ -#ifndef _ABSTRACTWEBTHREESTUBSERVER_H_ -#define _ABSTRACTWEBTHREESTUBSERVER_H_ +#ifndef JSONRPC_CPP_STUB_ABSTRACTWEBTHREESTUBSERVER_H_ +#define JSONRPC_CPP_STUB_ABSTRACTWEBTHREESTUBSERVER_H_ -#include +#include class AbstractWebThreeStubServer : public jsonrpc::AbstractServer { public: - AbstractWebThreeStubServer(jsonrpc::AbstractServerConnector* conn) : - jsonrpc::AbstractServer(conn) + AbstractWebThreeStubServer(jsonrpc::AbstractServerConnector &conn) : jsonrpc::AbstractServer(conn) { - this->bindAndAddMethod(new jsonrpc::Procedure("db_get", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_STRING, "param1",jsonrpc::JSON_STRING,"param2",jsonrpc::JSON_STRING, NULL), &AbstractWebThreeStubServer::db_getI); - this->bindAndAddMethod(new jsonrpc::Procedure("db_getString", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_STRING, "param1",jsonrpc::JSON_STRING,"param2",jsonrpc::JSON_STRING, NULL), &AbstractWebThreeStubServer::db_getStringI); - this->bindAndAddMethod(new jsonrpc::Procedure("db_put", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_BOOLEAN, "param1",jsonrpc::JSON_STRING,"param2",jsonrpc::JSON_STRING,"param3",jsonrpc::JSON_STRING, NULL), &AbstractWebThreeStubServer::db_putI); - this->bindAndAddMethod(new jsonrpc::Procedure("db_putString", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_BOOLEAN, "param1",jsonrpc::JSON_STRING,"param2",jsonrpc::JSON_STRING,"param3",jsonrpc::JSON_STRING, NULL), &AbstractWebThreeStubServer::db_putStringI); - this->bindAndAddMethod(new jsonrpc::Procedure("eth_accounts", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_ARRAY, NULL), &AbstractWebThreeStubServer::eth_accountsI); - this->bindAndAddMethod(new jsonrpc::Procedure("eth_balanceAt", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_STRING, "param1",jsonrpc::JSON_STRING, NULL), &AbstractWebThreeStubServer::eth_balanceAtI); - this->bindAndAddMethod(new jsonrpc::Procedure("eth_blockByHash", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_OBJECT, "param1",jsonrpc::JSON_STRING, NULL), &AbstractWebThreeStubServer::eth_blockByHashI); - this->bindAndAddMethod(new jsonrpc::Procedure("eth_blockByNumber", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_OBJECT, "param1",jsonrpc::JSON_INTEGER, NULL), &AbstractWebThreeStubServer::eth_blockByNumberI); - this->bindAndAddMethod(new jsonrpc::Procedure("eth_call", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_STRING, "param1",jsonrpc::JSON_OBJECT, NULL), &AbstractWebThreeStubServer::eth_callI); - this->bindAndAddMethod(new jsonrpc::Procedure("eth_changed", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_BOOLEAN, "param1",jsonrpc::JSON_INTEGER, NULL), &AbstractWebThreeStubServer::eth_changedI); - this->bindAndAddMethod(new jsonrpc::Procedure("eth_codeAt", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_STRING, "param1",jsonrpc::JSON_STRING, NULL), &AbstractWebThreeStubServer::eth_codeAtI); this->bindAndAddMethod(new jsonrpc::Procedure("eth_coinbase", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_STRING, NULL), &AbstractWebThreeStubServer::eth_coinbaseI); - this->bindAndAddMethod(new jsonrpc::Procedure("eth_compile", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_STRING, "param1",jsonrpc::JSON_STRING, NULL), &AbstractWebThreeStubServer::eth_compileI); - this->bindAndAddMethod(new jsonrpc::Procedure("eth_countAt", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_REAL, "param1",jsonrpc::JSON_STRING, NULL), &AbstractWebThreeStubServer::eth_countAtI); - this->bindAndAddMethod(new jsonrpc::Procedure("eth_defaultBlock", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_INTEGER, NULL), &AbstractWebThreeStubServer::eth_defaultBlockI); - this->bindAndAddMethod(new jsonrpc::Procedure("eth_gasPrice", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_STRING, NULL), &AbstractWebThreeStubServer::eth_gasPriceI); - this->bindAndAddMethod(new jsonrpc::Procedure("eth_getMessages", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_ARRAY, "param1",jsonrpc::JSON_INTEGER, NULL), &AbstractWebThreeStubServer::eth_getMessagesI); + this->bindAndAddMethod(new jsonrpc::Procedure("eth_setCoinbase", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_BOOLEAN, "param1",jsonrpc::JSON_STRING, NULL), &AbstractWebThreeStubServer::eth_setCoinbaseI); this->bindAndAddMethod(new jsonrpc::Procedure("eth_listening", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_BOOLEAN, NULL), &AbstractWebThreeStubServer::eth_listeningI); - this->bindAndAddMethod(new jsonrpc::Procedure("eth_lll", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_STRING, "param1",jsonrpc::JSON_STRING, NULL), &AbstractWebThreeStubServer::eth_lllI); + this->bindAndAddMethod(new jsonrpc::Procedure("eth_setListening", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_BOOLEAN, "param1",jsonrpc::JSON_BOOLEAN, NULL), &AbstractWebThreeStubServer::eth_setListeningI); this->bindAndAddMethod(new jsonrpc::Procedure("eth_mining", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_BOOLEAN, NULL), &AbstractWebThreeStubServer::eth_miningI); - this->bindAndAddMethod(new jsonrpc::Procedure("eth_newFilter", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_INTEGER, "param1",jsonrpc::JSON_OBJECT, NULL), &AbstractWebThreeStubServer::eth_newFilterI); - this->bindAndAddMethod(new jsonrpc::Procedure("eth_newFilterString", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_INTEGER, "param1",jsonrpc::JSON_STRING, NULL), &AbstractWebThreeStubServer::eth_newFilterStringI); - this->bindAndAddMethod(new jsonrpc::Procedure("eth_number", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_INTEGER, NULL), &AbstractWebThreeStubServer::eth_numberI); + this->bindAndAddMethod(new jsonrpc::Procedure("eth_setMining", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_BOOLEAN, "param1",jsonrpc::JSON_BOOLEAN, NULL), &AbstractWebThreeStubServer::eth_setMiningI); + this->bindAndAddMethod(new jsonrpc::Procedure("eth_gasPrice", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_STRING, NULL), &AbstractWebThreeStubServer::eth_gasPriceI); + this->bindAndAddMethod(new jsonrpc::Procedure("eth_accounts", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_ARRAY, NULL), &AbstractWebThreeStubServer::eth_accountsI); this->bindAndAddMethod(new jsonrpc::Procedure("eth_peerCount", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_INTEGER, NULL), &AbstractWebThreeStubServer::eth_peerCountI); - this->bindAndAddMethod(new jsonrpc::Procedure("eth_setCoinbase", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_BOOLEAN, "param1",jsonrpc::JSON_STRING, NULL), &AbstractWebThreeStubServer::eth_setCoinbaseI); + this->bindAndAddMethod(new jsonrpc::Procedure("eth_defaultBlock", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_INTEGER, NULL), &AbstractWebThreeStubServer::eth_defaultBlockI); this->bindAndAddMethod(new jsonrpc::Procedure("eth_setDefaultBlock", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_BOOLEAN, "param1",jsonrpc::JSON_INTEGER, NULL), &AbstractWebThreeStubServer::eth_setDefaultBlockI); - this->bindAndAddMethod(new jsonrpc::Procedure("eth_setListening", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_BOOLEAN, "param1",jsonrpc::JSON_BOOLEAN, NULL), &AbstractWebThreeStubServer::eth_setListeningI); - this->bindAndAddMethod(new jsonrpc::Procedure("eth_setMining", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_BOOLEAN, "param1",jsonrpc::JSON_BOOLEAN, NULL), &AbstractWebThreeStubServer::eth_setMiningI); + this->bindAndAddMethod(new jsonrpc::Procedure("eth_number", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_INTEGER, NULL), &AbstractWebThreeStubServer::eth_numberI); + this->bindAndAddMethod(new jsonrpc::Procedure("eth_balanceAt", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_STRING, "param1",jsonrpc::JSON_STRING, NULL), &AbstractWebThreeStubServer::eth_balanceAtI); this->bindAndAddMethod(new jsonrpc::Procedure("eth_stateAt", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_STRING, "param1",jsonrpc::JSON_STRING,"param2",jsonrpc::JSON_STRING, NULL), &AbstractWebThreeStubServer::eth_stateAtI); + this->bindAndAddMethod(new jsonrpc::Procedure("eth_storageAt", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_OBJECT, "param1",jsonrpc::JSON_STRING, NULL), &AbstractWebThreeStubServer::eth_storageAtI); + this->bindAndAddMethod(new jsonrpc::Procedure("eth_countAt", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_REAL, "param1",jsonrpc::JSON_STRING, NULL), &AbstractWebThreeStubServer::eth_countAtI); + this->bindAndAddMethod(new jsonrpc::Procedure("eth_codeAt", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_STRING, "param1",jsonrpc::JSON_STRING, NULL), &AbstractWebThreeStubServer::eth_codeAtI); this->bindAndAddMethod(new jsonrpc::Procedure("eth_transact", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_STRING, "param1",jsonrpc::JSON_OBJECT, NULL), &AbstractWebThreeStubServer::eth_transactI); + this->bindAndAddMethod(new jsonrpc::Procedure("eth_call", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_STRING, "param1",jsonrpc::JSON_OBJECT, NULL), &AbstractWebThreeStubServer::eth_callI); + this->bindAndAddMethod(new jsonrpc::Procedure("eth_blockByHash", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_OBJECT, "param1",jsonrpc::JSON_STRING, NULL), &AbstractWebThreeStubServer::eth_blockByHashI); + this->bindAndAddMethod(new jsonrpc::Procedure("eth_blockByNumber", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_OBJECT, "param1",jsonrpc::JSON_INTEGER, NULL), &AbstractWebThreeStubServer::eth_blockByNumberI); this->bindAndAddMethod(new jsonrpc::Procedure("eth_transactionByHash", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_OBJECT, "param1",jsonrpc::JSON_STRING,"param2",jsonrpc::JSON_INTEGER, NULL), &AbstractWebThreeStubServer::eth_transactionByHashI); this->bindAndAddMethod(new jsonrpc::Procedure("eth_transactionByNumber", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_OBJECT, "param1",jsonrpc::JSON_INTEGER,"param2",jsonrpc::JSON_INTEGER, NULL), &AbstractWebThreeStubServer::eth_transactionByNumberI); this->bindAndAddMethod(new jsonrpc::Procedure("eth_uncleByHash", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_OBJECT, "param1",jsonrpc::JSON_STRING,"param2",jsonrpc::JSON_INTEGER, NULL), &AbstractWebThreeStubServer::eth_uncleByHashI); this->bindAndAddMethod(new jsonrpc::Procedure("eth_uncleByNumber", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_OBJECT, "param1",jsonrpc::JSON_INTEGER,"param2",jsonrpc::JSON_INTEGER, NULL), &AbstractWebThreeStubServer::eth_uncleByNumberI); + this->bindAndAddMethod(new jsonrpc::Procedure("eth_compilers", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_ARRAY, NULL), &AbstractWebThreeStubServer::eth_compilersI); + this->bindAndAddMethod(new jsonrpc::Procedure("eth_lll", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_STRING, "param1",jsonrpc::JSON_STRING, NULL), &AbstractWebThreeStubServer::eth_lllI); + this->bindAndAddMethod(new jsonrpc::Procedure("eth_solidity", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_STRING, "param1",jsonrpc::JSON_STRING, NULL), &AbstractWebThreeStubServer::eth_solidityI); + this->bindAndAddMethod(new jsonrpc::Procedure("eth_serpent", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_STRING, "param1",jsonrpc::JSON_STRING, NULL), &AbstractWebThreeStubServer::eth_serpentI); + this->bindAndAddMethod(new jsonrpc::Procedure("eth_newFilter", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_INTEGER, "param1",jsonrpc::JSON_OBJECT, NULL), &AbstractWebThreeStubServer::eth_newFilterI); + this->bindAndAddMethod(new jsonrpc::Procedure("eth_newFilterString", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_INTEGER, "param1",jsonrpc::JSON_STRING, NULL), &AbstractWebThreeStubServer::eth_newFilterStringI); this->bindAndAddMethod(new jsonrpc::Procedure("eth_uninstallFilter", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_BOOLEAN, "param1",jsonrpc::JSON_INTEGER, NULL), &AbstractWebThreeStubServer::eth_uninstallFilterI); - this->bindAndAddMethod(new jsonrpc::Procedure("shh_addToGroup", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_STRING, "param1",jsonrpc::JSON_STRING,"param2",jsonrpc::JSON_STRING, NULL), &AbstractWebThreeStubServer::shh_addToGroupI); - this->bindAndAddMethod(new jsonrpc::Procedure("shh_changed", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_ARRAY, "param1",jsonrpc::JSON_INTEGER, NULL), &AbstractWebThreeStubServer::shh_changedI); + this->bindAndAddMethod(new jsonrpc::Procedure("eth_changed", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_BOOLEAN, "param1",jsonrpc::JSON_INTEGER, NULL), &AbstractWebThreeStubServer::eth_changedI); + this->bindAndAddMethod(new jsonrpc::Procedure("eth_filterLogs", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_ARRAY, "param1",jsonrpc::JSON_INTEGER, NULL), &AbstractWebThreeStubServer::eth_filterLogsI); + this->bindAndAddMethod(new jsonrpc::Procedure("eth_logs", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_ARRAY, "param1",jsonrpc::JSON_OBJECT, NULL), &AbstractWebThreeStubServer::eth_logsI); + this->bindAndAddMethod(new jsonrpc::Procedure("db_put", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_BOOLEAN, "param1",jsonrpc::JSON_STRING,"param2",jsonrpc::JSON_STRING,"param3",jsonrpc::JSON_STRING, NULL), &AbstractWebThreeStubServer::db_putI); + this->bindAndAddMethod(new jsonrpc::Procedure("db_get", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_STRING, "param1",jsonrpc::JSON_STRING,"param2",jsonrpc::JSON_STRING, NULL), &AbstractWebThreeStubServer::db_getI); + this->bindAndAddMethod(new jsonrpc::Procedure("db_putString", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_BOOLEAN, "param1",jsonrpc::JSON_STRING,"param2",jsonrpc::JSON_STRING,"param3",jsonrpc::JSON_STRING, NULL), &AbstractWebThreeStubServer::db_putStringI); + this->bindAndAddMethod(new jsonrpc::Procedure("db_getString", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_STRING, "param1",jsonrpc::JSON_STRING,"param2",jsonrpc::JSON_STRING, NULL), &AbstractWebThreeStubServer::db_getStringI); + this->bindAndAddMethod(new jsonrpc::Procedure("shh_post", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_BOOLEAN, "param1",jsonrpc::JSON_OBJECT, NULL), &AbstractWebThreeStubServer::shh_postI); + this->bindAndAddMethod(new jsonrpc::Procedure("shh_newIdentity", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_STRING, NULL), &AbstractWebThreeStubServer::shh_newIdentityI); this->bindAndAddMethod(new jsonrpc::Procedure("shh_haveIdentity", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_BOOLEAN, "param1",jsonrpc::JSON_STRING, NULL), &AbstractWebThreeStubServer::shh_haveIdentityI); - this->bindAndAddMethod(new jsonrpc::Procedure("shh_newFilter", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_INTEGER, "param1",jsonrpc::JSON_OBJECT, NULL), &AbstractWebThreeStubServer::shh_newFilterI); this->bindAndAddMethod(new jsonrpc::Procedure("shh_newGroup", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_STRING, "param1",jsonrpc::JSON_STRING,"param2",jsonrpc::JSON_STRING, NULL), &AbstractWebThreeStubServer::shh_newGroupI); - this->bindAndAddMethod(new jsonrpc::Procedure("shh_newIdentity", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_STRING, NULL), &AbstractWebThreeStubServer::shh_newIdentityI); - this->bindAndAddMethod(new jsonrpc::Procedure("shh_post", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_BOOLEAN, "param1",jsonrpc::JSON_OBJECT, NULL), &AbstractWebThreeStubServer::shh_postI); + this->bindAndAddMethod(new jsonrpc::Procedure("shh_addToGroup", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_STRING, "param1",jsonrpc::JSON_STRING,"param2",jsonrpc::JSON_STRING, NULL), &AbstractWebThreeStubServer::shh_addToGroupI); + this->bindAndAddMethod(new jsonrpc::Procedure("shh_newFilter", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_INTEGER, "param1",jsonrpc::JSON_OBJECT, NULL), &AbstractWebThreeStubServer::shh_newFilterI); this->bindAndAddMethod(new jsonrpc::Procedure("shh_uninstallFilter", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_BOOLEAN, "param1",jsonrpc::JSON_INTEGER, NULL), &AbstractWebThreeStubServer::shh_uninstallFilterI); + this->bindAndAddMethod(new jsonrpc::Procedure("shh_changed", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_ARRAY, "param1",jsonrpc::JSON_INTEGER, NULL), &AbstractWebThreeStubServer::shh_changedI); + } + inline virtual void eth_coinbaseI(const Json::Value &request, Json::Value &response) + { + (void)request; + response = this->eth_coinbase(); } - - inline virtual void db_getI(const Json::Value& request, Json::Value& response) + inline virtual void eth_setCoinbaseI(const Json::Value &request, Json::Value &response) { - response = this->db_get(request[0u].asString(), request[1u].asString()); + response = this->eth_setCoinbase(request[0u].asString()); } - - inline virtual void db_getStringI(const Json::Value& request, Json::Value& response) + inline virtual void eth_listeningI(const Json::Value &request, Json::Value &response) { - response = this->db_getString(request[0u].asString(), request[1u].asString()); + (void)request; + response = this->eth_listening(); } - - inline virtual void db_putI(const Json::Value& request, Json::Value& response) + inline virtual void eth_setListeningI(const Json::Value &request, Json::Value &response) { - response = this->db_put(request[0u].asString(), request[1u].asString(), request[2u].asString()); + response = this->eth_setListening(request[0u].asBool()); } - - inline virtual void db_putStringI(const Json::Value& request, Json::Value& response) + inline virtual void eth_miningI(const Json::Value &request, Json::Value &response) { - response = this->db_putString(request[0u].asString(), request[1u].asString(), request[2u].asString()); + (void)request; + response = this->eth_mining(); } - - inline virtual void eth_accountsI(const Json::Value& request, Json::Value& response) + inline virtual void eth_setMiningI(const Json::Value &request, Json::Value &response) { - response = this->eth_accounts(); + response = this->eth_setMining(request[0u].asBool()); } - - inline virtual void eth_balanceAtI(const Json::Value& request, Json::Value& response) + inline virtual void eth_gasPriceI(const Json::Value &request, Json::Value &response) { - response = this->eth_balanceAt(request[0u].asString()); + (void)request; + response = this->eth_gasPrice(); } - - inline virtual void eth_blockByHashI(const Json::Value& request, Json::Value& response) + inline virtual void eth_accountsI(const Json::Value &request, Json::Value &response) { - response = this->eth_blockByHash(request[0u].asString()); + (void)request; + response = this->eth_accounts(); } - - inline virtual void eth_blockByNumberI(const Json::Value& request, Json::Value& response) + inline virtual void eth_peerCountI(const Json::Value &request, Json::Value &response) { - response = this->eth_blockByNumber(request[0u].asInt()); + (void)request; + response = this->eth_peerCount(); } - - inline virtual void eth_callI(const Json::Value& request, Json::Value& response) + inline virtual void eth_defaultBlockI(const Json::Value &request, Json::Value &response) { - response = this->eth_call(request[0u]); + (void)request; + response = this->eth_defaultBlock(); } - - inline virtual void eth_changedI(const Json::Value& request, Json::Value& response) + inline virtual void eth_setDefaultBlockI(const Json::Value &request, Json::Value &response) { - response = this->eth_changed(request[0u].asInt()); + response = this->eth_setDefaultBlock(request[0u].asInt()); } - - inline virtual void eth_codeAtI(const Json::Value& request, Json::Value& response) + inline virtual void eth_numberI(const Json::Value &request, Json::Value &response) { - response = this->eth_codeAt(request[0u].asString()); + (void)request; + response = this->eth_number(); } - - inline virtual void eth_coinbaseI(const Json::Value& request, Json::Value& response) + inline virtual void eth_balanceAtI(const Json::Value &request, Json::Value &response) { - response = this->eth_coinbase(); + response = this->eth_balanceAt(request[0u].asString()); } - - inline virtual void eth_compileI(const Json::Value& request, Json::Value& response) + inline virtual void eth_stateAtI(const Json::Value &request, Json::Value &response) + { + response = this->eth_stateAt(request[0u].asString(), request[1u].asString()); + } + inline virtual void eth_storageAtI(const Json::Value &request, Json::Value &response) { - response = this->eth_compile(request[0u].asString()); + response = this->eth_storageAt(request[0u].asString()); } - - inline virtual void eth_countAtI(const Json::Value& request, Json::Value& response) + inline virtual void eth_countAtI(const Json::Value &request, Json::Value &response) { response = this->eth_countAt(request[0u].asString()); } - - inline virtual void eth_defaultBlockI(const Json::Value& request, Json::Value& response) + inline virtual void eth_codeAtI(const Json::Value &request, Json::Value &response) { - response = this->eth_defaultBlock(); + response = this->eth_codeAt(request[0u].asString()); } - - inline virtual void eth_gasPriceI(const Json::Value& request, Json::Value& response) + inline virtual void eth_transactI(const Json::Value &request, Json::Value &response) { - response = this->eth_gasPrice(); + response = this->eth_transact(request[0u]); } - - inline virtual void eth_getMessagesI(const Json::Value& request, Json::Value& response) + inline virtual void eth_callI(const Json::Value &request, Json::Value &response) { - response = this->eth_getMessages(request[0u].asInt()); + response = this->eth_call(request[0u]); } - - inline virtual void eth_listeningI(const Json::Value& request, Json::Value& response) + inline virtual void eth_blockByHashI(const Json::Value &request, Json::Value &response) { - response = this->eth_listening(); + response = this->eth_blockByHash(request[0u].asString()); } - - inline virtual void eth_lllI(const Json::Value& request, Json::Value& response) + inline virtual void eth_blockByNumberI(const Json::Value &request, Json::Value &response) { - response = this->eth_lll(request[0u].asString()); + response = this->eth_blockByNumber(request[0u].asInt()); } - - inline virtual void eth_miningI(const Json::Value& request, Json::Value& response) + inline virtual void eth_transactionByHashI(const Json::Value &request, Json::Value &response) { - response = this->eth_mining(); + response = this->eth_transactionByHash(request[0u].asString(), request[1u].asInt()); } - - inline virtual void eth_newFilterI(const Json::Value& request, Json::Value& response) + inline virtual void eth_transactionByNumberI(const Json::Value &request, Json::Value &response) { - response = this->eth_newFilter(request[0u]); + response = this->eth_transactionByNumber(request[0u].asInt(), request[1u].asInt()); } - - inline virtual void eth_newFilterStringI(const Json::Value& request, Json::Value& response) + inline virtual void eth_uncleByHashI(const Json::Value &request, Json::Value &response) { - response = this->eth_newFilterString(request[0u].asString()); + response = this->eth_uncleByHash(request[0u].asString(), request[1u].asInt()); } - - inline virtual void eth_numberI(const Json::Value& request, Json::Value& response) + inline virtual void eth_uncleByNumberI(const Json::Value &request, Json::Value &response) { - response = this->eth_number(); + response = this->eth_uncleByNumber(request[0u].asInt(), request[1u].asInt()); } - - inline virtual void eth_peerCountI(const Json::Value& request, Json::Value& response) + inline virtual void eth_compilersI(const Json::Value &request, Json::Value &response) { - response = this->eth_peerCount(); + (void)request; + response = this->eth_compilers(); } - - inline virtual void eth_setCoinbaseI(const Json::Value& request, Json::Value& response) + inline virtual void eth_lllI(const Json::Value &request, Json::Value &response) { - response = this->eth_setCoinbase(request[0u].asString()); + response = this->eth_lll(request[0u].asString()); } - - inline virtual void eth_setDefaultBlockI(const Json::Value& request, Json::Value& response) + inline virtual void eth_solidityI(const Json::Value &request, Json::Value &response) { - response = this->eth_setDefaultBlock(request[0u].asInt()); + response = this->eth_solidity(request[0u].asString()); } - - inline virtual void eth_setListeningI(const Json::Value& request, Json::Value& response) + inline virtual void eth_serpentI(const Json::Value &request, Json::Value &response) { - response = this->eth_setListening(request[0u].asBool()); + response = this->eth_serpent(request[0u].asString()); } - - inline virtual void eth_setMiningI(const Json::Value& request, Json::Value& response) + inline virtual void eth_newFilterI(const Json::Value &request, Json::Value &response) { - response = this->eth_setMining(request[0u].asBool()); + response = this->eth_newFilter(request[0u]); } - - inline virtual void eth_stateAtI(const Json::Value& request, Json::Value& response) + inline virtual void eth_newFilterStringI(const Json::Value &request, Json::Value &response) { - response = this->eth_stateAt(request[0u].asString(), request[1u].asString()); + response = this->eth_newFilterString(request[0u].asString()); } - - inline virtual void eth_transactI(const Json::Value& request, Json::Value& response) + inline virtual void eth_uninstallFilterI(const Json::Value &request, Json::Value &response) { - response = this->eth_transact(request[0u]); + response = this->eth_uninstallFilter(request[0u].asInt()); } - - inline virtual void eth_transactionByHashI(const Json::Value& request, Json::Value& response) + inline virtual void eth_changedI(const Json::Value &request, Json::Value &response) { - response = this->eth_transactionByHash(request[0u].asString(), request[1u].asInt()); + response = this->eth_changed(request[0u].asInt()); } - - inline virtual void eth_transactionByNumberI(const Json::Value& request, Json::Value& response) + inline virtual void eth_filterLogsI(const Json::Value &request, Json::Value &response) { - response = this->eth_transactionByNumber(request[0u].asInt(), request[1u].asInt()); + response = this->eth_filterLogs(request[0u].asInt()); } - - inline virtual void eth_uncleByHashI(const Json::Value& request, Json::Value& response) + inline virtual void eth_logsI(const Json::Value &request, Json::Value &response) { - response = this->eth_uncleByHash(request[0u].asString(), request[1u].asInt()); + response = this->eth_logs(request[0u]); } - - inline virtual void eth_uncleByNumberI(const Json::Value& request, Json::Value& response) + inline virtual void db_putI(const Json::Value &request, Json::Value &response) { - response = this->eth_uncleByNumber(request[0u].asInt(), request[1u].asInt()); + response = this->db_put(request[0u].asString(), request[1u].asString(), request[2u].asString()); } - - inline virtual void eth_uninstallFilterI(const Json::Value& request, Json::Value& response) + inline virtual void db_getI(const Json::Value &request, Json::Value &response) { - response = this->eth_uninstallFilter(request[0u].asInt()); + response = this->db_get(request[0u].asString(), request[1u].asString()); } - - inline virtual void shh_addToGroupI(const Json::Value& request, Json::Value& response) + inline virtual void db_putStringI(const Json::Value &request, Json::Value &response) { - response = this->shh_addToGroup(request[0u].asString(), request[1u].asString()); + response = this->db_putString(request[0u].asString(), request[1u].asString(), request[2u].asString()); } - - inline virtual void shh_changedI(const Json::Value& request, Json::Value& response) + inline virtual void db_getStringI(const Json::Value &request, Json::Value &response) { - response = this->shh_changed(request[0u].asInt()); + response = this->db_getString(request[0u].asString(), request[1u].asString()); } - - inline virtual void shh_haveIdentityI(const Json::Value& request, Json::Value& response) + inline virtual void shh_postI(const Json::Value &request, Json::Value &response) { - response = this->shh_haveIdentity(request[0u].asString()); + response = this->shh_post(request[0u]); } - - inline virtual void shh_newFilterI(const Json::Value& request, Json::Value& response) + inline virtual void shh_newIdentityI(const Json::Value &request, Json::Value &response) { - response = this->shh_newFilter(request[0u]); + (void)request; + response = this->shh_newIdentity(); } - - inline virtual void shh_newGroupI(const Json::Value& request, Json::Value& response) + inline virtual void shh_haveIdentityI(const Json::Value &request, Json::Value &response) + { + response = this->shh_haveIdentity(request[0u].asString()); + } + inline virtual void shh_newGroupI(const Json::Value &request, Json::Value &response) { response = this->shh_newGroup(request[0u].asString(), request[1u].asString()); } - - inline virtual void shh_newIdentityI(const Json::Value& request, Json::Value& response) + inline virtual void shh_addToGroupI(const Json::Value &request, Json::Value &response) { - response = this->shh_newIdentity(); + response = this->shh_addToGroup(request[0u].asString(), request[1u].asString()); } - - inline virtual void shh_postI(const Json::Value& request, Json::Value& response) + inline virtual void shh_newFilterI(const Json::Value &request, Json::Value &response) { - response = this->shh_post(request[0u]); + response = this->shh_newFilter(request[0u]); } - - inline virtual void shh_uninstallFilterI(const Json::Value& request, Json::Value& response) + inline virtual void shh_uninstallFilterI(const Json::Value &request, Json::Value &response) { response = this->shh_uninstallFilter(request[0u].asInt()); } - - - virtual std::string db_get(const std::string& param1, const std::string& param2) = 0; - virtual std::string db_getString(const std::string& param1, const std::string& param2) = 0; - virtual bool db_put(const std::string& param1, const std::string& param2, const std::string& param3) = 0; - virtual bool db_putString(const std::string& param1, const std::string& param2, const std::string& param3) = 0; - virtual Json::Value eth_accounts() = 0; - virtual std::string eth_balanceAt(const std::string& param1) = 0; - virtual Json::Value eth_blockByHash(const std::string& param1) = 0; - virtual Json::Value eth_blockByNumber(const int& param1) = 0; - virtual std::string eth_call(const Json::Value& param1) = 0; - virtual bool eth_changed(const int& param1) = 0; - virtual std::string eth_codeAt(const std::string& param1) = 0; + inline virtual void shh_changedI(const Json::Value &request, Json::Value &response) + { + response = this->shh_changed(request[0u].asInt()); + } virtual std::string eth_coinbase() = 0; - virtual std::string eth_compile(const std::string& param1) = 0; - virtual double eth_countAt(const std::string& param1) = 0; - virtual int eth_defaultBlock() = 0; - virtual std::string eth_gasPrice() = 0; - virtual Json::Value eth_getMessages(const int& param1) = 0; + virtual bool eth_setCoinbase(const std::string& param1) = 0; virtual bool eth_listening() = 0; - virtual std::string eth_lll(const std::string& param1) = 0; + virtual bool eth_setListening(const bool& param1) = 0; virtual bool eth_mining() = 0; - virtual int eth_newFilter(const Json::Value& param1) = 0; - virtual int eth_newFilterString(const std::string& param1) = 0; - virtual int eth_number() = 0; + virtual bool eth_setMining(const bool& param1) = 0; + virtual std::string eth_gasPrice() = 0; + virtual Json::Value eth_accounts() = 0; virtual int eth_peerCount() = 0; - virtual bool eth_setCoinbase(const std::string& param1) = 0; + virtual int eth_defaultBlock() = 0; virtual bool eth_setDefaultBlock(const int& param1) = 0; - virtual bool eth_setListening(const bool& param1) = 0; - virtual bool eth_setMining(const bool& param1) = 0; + virtual int eth_number() = 0; + virtual std::string eth_balanceAt(const std::string& param1) = 0; virtual std::string eth_stateAt(const std::string& param1, const std::string& param2) = 0; + virtual Json::Value eth_storageAt(const std::string& param1) = 0; + virtual double eth_countAt(const std::string& param1) = 0; + virtual std::string eth_codeAt(const std::string& param1) = 0; virtual std::string eth_transact(const Json::Value& param1) = 0; + virtual std::string eth_call(const Json::Value& param1) = 0; + virtual Json::Value eth_blockByHash(const std::string& param1) = 0; + virtual Json::Value eth_blockByNumber(const int& param1) = 0; virtual Json::Value eth_transactionByHash(const std::string& param1, const int& param2) = 0; virtual Json::Value eth_transactionByNumber(const int& param1, const int& param2) = 0; virtual Json::Value eth_uncleByHash(const std::string& param1, const int& param2) = 0; virtual Json::Value eth_uncleByNumber(const int& param1, const int& param2) = 0; + virtual Json::Value eth_compilers() = 0; + virtual std::string eth_lll(const std::string& param1) = 0; + virtual std::string eth_solidity(const std::string& param1) = 0; + virtual std::string eth_serpent(const std::string& param1) = 0; + virtual int eth_newFilter(const Json::Value& param1) = 0; + virtual int eth_newFilterString(const std::string& param1) = 0; virtual bool eth_uninstallFilter(const int& param1) = 0; - virtual std::string shh_addToGroup(const std::string& param1, const std::string& param2) = 0; - virtual Json::Value shh_changed(const int& param1) = 0; + virtual bool eth_changed(const int& param1) = 0; + virtual Json::Value eth_filterLogs(const int& param1) = 0; + virtual Json::Value eth_logs(const Json::Value& param1) = 0; + virtual bool db_put(const std::string& param1, const std::string& param2, const std::string& param3) = 0; + virtual std::string db_get(const std::string& param1, const std::string& param2) = 0; + virtual bool db_putString(const std::string& param1, const std::string& param2, const std::string& param3) = 0; + virtual std::string db_getString(const std::string& param1, const std::string& param2) = 0; + virtual bool shh_post(const Json::Value& param1) = 0; + virtual std::string shh_newIdentity() = 0; virtual bool shh_haveIdentity(const std::string& param1) = 0; - virtual int shh_newFilter(const Json::Value& param1) = 0; virtual std::string shh_newGroup(const std::string& param1, const std::string& param2) = 0; - virtual std::string shh_newIdentity() = 0; - virtual bool shh_post(const Json::Value& param1) = 0; + virtual std::string shh_addToGroup(const std::string& param1, const std::string& param2) = 0; + virtual int shh_newFilter(const Json::Value& param1) = 0; virtual bool shh_uninstallFilter(const int& param1) = 0; - + virtual Json::Value shh_changed(const int& param1) = 0; }; -#endif //_ABSTRACTWEBTHREESTUBSERVER_H_ + +#endif //JSONRPC_CPP_ABSTRACTWEBTHREESTUBSERVER_H_ diff --git a/libweb3jsonrpc/spec.json b/libweb3jsonrpc/spec.json index 47a8b26df..43d8d3f5a 100644 --- a/libweb3jsonrpc/spec.json +++ b/libweb3jsonrpc/spec.json @@ -1,55 +1,59 @@ [ - { "method": "eth_coinbase", "params": [], "order": [], "returns" : "" }, - { "method": "eth_setCoinbase", "params": [""], "order": [], "returns" : true }, - { "method": "eth_listening", "params": [], "order": [], "returns" : false }, - { "method": "eth_setListening", "params": [false], "order" : [], "returns" : true }, - { "method": "eth_mining", "params": [], "order": [], "returns" : false }, - { "method": "eth_setMining", "params": [false], "order" : [], "returns" : true }, - { "method": "eth_gasPrice", "params": [], "order": [], "returns" : "" }, - { "method": "eth_accounts", "params": [], "order": [], "returns" : [] }, - { "method": "eth_peerCount", "params": [], "order": [], "returns" : 0 }, - { "method": "eth_defaultBlock", "params": [], "order": [], "returns" : 0}, - { "method": "eth_setDefaultBlock", "params": [0], "order": [], "returns" : true}, - { "method": "eth_number", "params": [], "order": [], "returns" : 0}, - - { "method": "eth_balanceAt", "params": [""], "order": [], "returns" : ""}, - { "method": "eth_stateAt", "params": ["", ""], "order": [], "returns": ""}, - { "method": "eth_countAt", "params": [""], "order": [], "returns" : 0.0}, - { "method": "eth_codeAt", "params": [""], "order": [], "returns": ""}, - - { "method": "eth_transact", "params": [{}], "order": [], "returns": ""}, - { "method": "eth_call", "params": [{}], "order": [], "returns": ""}, - - { "method": "eth_blockByHash", "params": [""],"order": [], "returns": {}}, - { "method": "eth_blockByNumber", "params": [0],"order": [], "returns": {}}, - { "method": "eth_transactionByHash", "params": ["", 0], "order": [], "returns": {}}, - { "method": "eth_transactionByNumber", "params": [0, 0], "order": [], "returns": {}}, - { "method": "eth_uncleByHash", "params": ["", 0], "order": [], "returns": {}}, - { "method": "eth_uncleByNumber", "params": [0, 0], "order": [], "returns": {}}, - - { "method": "eth_lll", "params": [""], "order": [], "returns": ""}, - { "method": "eth_compile", "params": [""], "order": [], "returns": ""}, - - { "method": "eth_newFilter", "params": [{}], "order": [], "returns": 0}, - { "method": "eth_newFilterString", "params": [""], "order": [], "returns": 0}, - { "method": "eth_uninstallFilter", "params": [0], "order": [], "returns": true}, - { "method": "eth_changed", "params": [0], "order": [], "returns": false}, - { "method": "eth_getMessages", "params": [0], "order": [], "returns": []}, - - { "method": "db_put", "params": ["", "", ""], "order": [], "returns": true}, - { "method": "db_get", "params": ["", ""], "order": [], "returns": ""}, - { "method": "db_putString", "params": ["", "", ""], "order": [], "returns": true}, - { "method": "db_getString", "params": ["", ""], "order": [], "returns": ""}, - - { "method": "shh_post", "params": [{}], "order": [], "returns": true}, - { "method": "shh_newIdentity", "params": [], "order": [], "returns": ""}, - { "method": "shh_haveIdentity", "params": [""], "order": [], "returns": false}, - { "method": "shh_newGroup", "params": ["", ""], "order": [], "returns": ""}, - { "method": "shh_addToGroup", "params": ["", ""], "order": [], "returns": ""}, - - { "method": "shh_newFilter", "params": [{}], "order": [], "returns": 0}, - { "method": "shh_uninstallFilter", "params": [0], "order": [], "returns": true}, - { "method": "shh_changed", "params": [0], "order": [], "returns": []} + { "name": "eth_coinbase", "params": [], "order": [], "returns" : "" }, + { "name": "eth_setCoinbase", "params": [""], "order": [], "returns" : true }, + { "name": "eth_listening", "params": [], "order": [], "returns" : false }, + { "name": "eth_setListening", "params": [false], "order" : [], "returns" : true }, + { "name": "eth_mining", "params": [], "order": [], "returns" : false }, + { "name": "eth_setMining", "params": [false], "order" : [], "returns" : true }, + { "name": "eth_gasPrice", "params": [], "order": [], "returns" : "" }, + { "name": "eth_accounts", "params": [], "order": [], "returns" : [] }, + { "name": "eth_peerCount", "params": [], "order": [], "returns" : 0 }, + { "name": "eth_defaultBlock", "params": [], "order": [], "returns" : 0}, + { "name": "eth_setDefaultBlock", "params": [0], "order": [], "returns" : true}, + { "name": "eth_number", "params": [], "order": [], "returns" : 0}, + + { "name": "eth_balanceAt", "params": [""], "order": [], "returns" : ""}, + { "name": "eth_stateAt", "params": ["", ""], "order": [], "returns": ""}, + { "name": "eth_storageAt", "params": [""], "order": [], "returns": {}}, + { "name": "eth_countAt", "params": [""], "order": [], "returns" : 0.0}, + { "name": "eth_codeAt", "params": [""], "order": [], "returns": ""}, + + { "name": "eth_transact", "params": [{}], "order": [], "returns": ""}, + { "name": "eth_call", "params": [{}], "order": [], "returns": ""}, + + { "name": "eth_blockByHash", "params": [""],"order": [], "returns": {}}, + { "name": "eth_blockByNumber", "params": [0],"order": [], "returns": {}}, + { "name": "eth_transactionByHash", "params": ["", 0], "order": [], "returns": {}}, + { "name": "eth_transactionByNumber", "params": [0, 0], "order": [], "returns": {}}, + { "name": "eth_uncleByHash", "params": ["", 0], "order": [], "returns": {}}, + { "name": "eth_uncleByNumber", "params": [0, 0], "order": [], "returns": {}}, + + { "name": "eth_compilers", "params": [], "order": [], "returns": []}, + { "name": "eth_lll", "params": [""], "order": [], "returns": ""}, + { "name": "eth_solidity", "params": [""], "order": [], "returns": ""}, + { "name": "eth_serpent", "params": [""], "order": [], "returns": ""}, + + + { "name": "eth_newFilter", "params": [{}], "order": [], "returns": 0}, + { "name": "eth_newFilterString", "params": [""], "order": [], "returns": 0}, + { "name": "eth_uninstallFilter", "params": [0], "order": [], "returns": true}, + { "name": "eth_changed", "params": [0], "order": [], "returns": false}, + { "name": "eth_filterLogs", "params": [0], "order": [], "returns": []}, + { "name": "eth_logs", "params": [{}], "order": [], "returns": []}, + + { "name": "db_put", "params": ["", "", ""], "order": [], "returns": true}, + { "name": "db_get", "params": ["", ""], "order": [], "returns": ""}, + { "name": "db_putString", "params": ["", "", ""], "order": [], "returns": true}, + { "name": "db_getString", "params": ["", ""], "order": [], "returns": ""}, + + { "name": "shh_post", "params": [{}], "order": [], "returns": true}, + { "name": "shh_newIdentity", "params": [], "order": [], "returns": ""}, + { "name": "shh_haveIdentity", "params": [""], "order": [], "returns": false}, + { "name": "shh_newGroup", "params": ["", ""], "order": [], "returns": ""}, + { "name": "shh_addToGroup", "params": ["", ""], "order": [], "returns": ""}, + { "name": "shh_newFilter", "params": [{}], "order": [], "returns": 0}, + { "name": "shh_uninstallFilter", "params": [0], "order": [], "returns": true}, + { "name": "shh_changed", "params": [0], "order": [], "returns": []} ] diff --git a/libwebthree/CMakeLists.txt b/libwebthree/CMakeLists.txt index cc1b290f5..1d8f23918 100644 --- a/libwebthree/CMakeLists.txt +++ b/libwebthree/CMakeLists.txt @@ -1,19 +1,30 @@ cmake_policy(SET CMP0015 NEW) +# this policy was introduced in cmake 3.0 +# remove if, once 3.0 will be used on unix +if (${CMAKE_MAJOR_VERSION} GREATER 2) + # old policy do not use MACOSX_RPATH + cmake_policy(SET CMP0042 OLD) +endif() +set(CMAKE_AUTOMOC OFF) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DSTATICLIB") aux_source_directory(. SRC_LIST) +include_directories(${LEVELDB_INCLUDE_DIRS}) +include_directories(..) + set(EXECUTABLE webthree) file(GLOB HEADERS "*.h") -if(ETH_STATIC) + +if (ETH_STATIC) add_library(${EXECUTABLE} STATIC ${SRC_LIST} ${HEADERS}) else() add_library(${EXECUTABLE} SHARED ${SRC_LIST} ${HEADERS}) endif() -include_directories(..) +target_link_libraries(${EXECUTABLE} ${LEVELDB_LIBRARIES}) target_link_libraries(${EXECUTABLE} ethereum) target_link_libraries(${EXECUTABLE} evm) @@ -23,45 +34,6 @@ target_link_libraries(${EXECUTABLE} p2p) target_link_libraries(${EXECUTABLE} ethcore) target_link_libraries(${EXECUTABLE} devcrypto) target_link_libraries(${EXECUTABLE} secp256k1) -if(MINIUPNPC_LS) -target_link_libraries(${EXECUTABLE} ${MINIUPNPC_LS}) -endif() -target_link_libraries(${EXECUTABLE} ${LEVELDB_LS}) -target_link_libraries(${EXECUTABLE} ${CRYPTOPP_LS}) -target_link_libraries(${EXECUTABLE} gmp) - -if("${TARGET_PLATFORM}" STREQUAL "w64") - target_link_libraries(${EXECUTABLE} boost_system-mt-s) - target_link_libraries(${EXECUTABLE} boost_regex-mt-s) - target_link_libraries(${EXECUTABLE} boost_filesystem-mt-s) - target_link_libraries(${EXECUTABLE} boost_thread_win32-mt-s) - target_link_libraries(${EXECUTABLE} iphlpapi) - target_link_libraries(${EXECUTABLE} ws2_32) - target_link_libraries(${EXECUTABLE} mswsock) - target_link_libraries(${EXECUTABLE} shlwapi) -elseif (APPLE) - # Latest mavericks boost libraries only come with -mt - target_link_libraries(${EXECUTABLE} boost_system-mt) - target_link_libraries(${EXECUTABLE} boost_regex-mt) - target_link_libraries(${EXECUTABLE} boost_filesystem-mt) - target_link_libraries(${EXECUTABLE} boost_thread-mt) - find_package(Threads REQUIRED) - target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT}) -elseif (UNIX) - target_link_libraries(${EXECUTABLE} ${Boost_SYSTEM_LIBRARY}) - target_link_libraries(${EXECUTABLE} ${Boost_REGEX_LIBRARY}) - target_link_libraries(${EXECUTABLE} ${Boost_FILESYSTEM_LIBRARY}) - target_link_libraries(${EXECUTABLE} ${Boost_THREAD_LIBRARY}) - target_link_libraries(${EXECUTABLE} ${Boost_DATE_TIME_LIBRARY}) - target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT}) -else () - target_link_libraries(${EXECUTABLE} boost_system) - target_link_libraries(${EXECUTABLE} boost_regex) - target_link_libraries(${EXECUTABLE} boost_filesystem) - target_link_libraries(${EXECUTABLE} boost_thread) - find_package(Threads REQUIRED) - target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT}) -endif () install( TARGETS ${EXECUTABLE} ARCHIVE DESTINATION lib LIBRARY DESTINATION lib ) install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} ) diff --git a/libwebthree/WebThree.cpp b/libwebthree/WebThree.cpp index b5256ac22..c9f9d56e3 100644 --- a/libwebthree/WebThree.cpp +++ b/libwebthree/WebThree.cpp @@ -57,11 +57,11 @@ WebThreeDirect::~WebThreeDirect() // eth::Client (owned by us via a unique_ptr) uses eth::EthereumHost (via a weak_ptr). // Really need to work out a clean way of organising ownership and guaranteeing startup/shutdown is perfect. - // Have to call quit here to get the Host to kill its io_service otherwise we end up with left-over reads, + // Have to call stop here to get the Host to kill its io_service otherwise we end up with left-over reads, // still referencing Sessions getting deleted *after* m_ethereum is reset, causing bad things to happen, since // the guarantee is that m_ethereum is only reset *after* all sessions have ended (sessions are allowed to // use bits of data owned by m_ethereum). - m_net.quit(); + m_net.stop(); m_ethereum.reset(); } diff --git a/libwebthree/WebThree.h b/libwebthree/WebThree.h index a135f77ff..ec7bf2406 100644 --- a/libwebthree/WebThree.h +++ b/libwebthree/WebThree.h @@ -14,7 +14,7 @@ You should have received a copy of the GNU General Public License along with cpp-ethereum. If not, see . */ -/** @file Client.h +/** @file WebThree.h * @author Gav Wood * @date 2014 */ @@ -92,9 +92,6 @@ public: /// Connect to a particular peer. void connect(std::string const& _seedHost, unsigned short _port = 30303); - /// Is the network subsystem up? - bool haveNetwork() { return peerCount() != 0; } - /// Save peers dev::bytes saveNodes(); diff --git a/libwhisper/CMakeLists.txt b/libwhisper/CMakeLists.txt index 364d9759a..79879922e 100644 --- a/libwhisper/CMakeLists.txt +++ b/libwhisper/CMakeLists.txt @@ -1,65 +1,36 @@ cmake_policy(SET CMP0015 NEW) +# this policy was introduced in cmake 3.0 +# remove if, once 3.0 will be used on unix +if (${CMAKE_MAJOR_VERSION} GREATER 2) + # old policy do not use MACOSX_RPATH + cmake_policy(SET CMP0042 OLD) +endif() +set(CMAKE_AUTOMOC OFF) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DSTATICLIB") aux_source_directory(. SRC_LIST) +include_directories(..) +include_directories(${LEVELDB_INCLUDE_DIRS}) + set(EXECUTABLE whisper) file(GLOB HEADERS "*.h") -if(ETH_STATIC) + +if (ETH_STATIC) add_library(${EXECUTABLE} STATIC ${SRC_LIST} ${HEADERS}) else() add_library(${EXECUTABLE} SHARED ${SRC_LIST} ${HEADERS}) endif() -include_directories(..) +target_link_libraries(${EXECUTABLE} ${LEVELDB_LIBRARIES}) target_link_libraries(${EXECUTABLE} ethcore) target_link_libraries(${EXECUTABLE} devcrypto) target_link_libraries(${EXECUTABLE} devcore) target_link_libraries(${EXECUTABLE} p2p) target_link_libraries(${EXECUTABLE} secp256k1) -if(MINIUPNPC_LS) -target_link_libraries(${EXECUTABLE} ${MINIUPNPC_LS}) -endif() -target_link_libraries(${EXECUTABLE} ${LEVELDB_LS}) -target_link_libraries(${EXECUTABLE} ${CRYPTOPP_LS}) -target_link_libraries(${EXECUTABLE} gmp) - -if("${TARGET_PLATFORM}" STREQUAL "w64") - target_link_libraries(${EXECUTABLE} boost_system-mt-s) - target_link_libraries(${EXECUTABLE} boost_regex-mt-s) - target_link_libraries(${EXECUTABLE} boost_filesystem-mt-s) - target_link_libraries(${EXECUTABLE} boost_thread_win32-mt-s) - target_link_libraries(${EXECUTABLE} iphlpapi) - target_link_libraries(${EXECUTABLE} ws2_32) - target_link_libraries(${EXECUTABLE} mswsock) - target_link_libraries(${EXECUTABLE} shlwapi) -elseif (APPLE) - # Latest mavericks boost libraries only come with -mt - target_link_libraries(${EXECUTABLE} boost_system-mt) - target_link_libraries(${EXECUTABLE} boost_regex-mt) - target_link_libraries(${EXECUTABLE} boost_filesystem-mt) - target_link_libraries(${EXECUTABLE} boost_thread-mt) - find_package(Threads REQUIRED) - target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT}) -elseif (UNIX) - target_link_libraries(${EXECUTABLE} ${Boost_SYSTEM_LIBRARY}) - target_link_libraries(${EXECUTABLE} ${Boost_REGEX_LIBRARY}) - target_link_libraries(${EXECUTABLE} ${Boost_FILESYSTEM_LIBRARY}) - target_link_libraries(${EXECUTABLE} ${Boost_THREAD_LIBRARY}) - target_link_libraries(${EXECUTABLE} ${Boost_DATE_TIME_LIBRARY}) - target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT}) -else () - target_link_libraries(${EXECUTABLE} boost_system) - target_link_libraries(${EXECUTABLE} boost_regex) - target_link_libraries(${EXECUTABLE} boost_filesystem) - target_link_libraries(${EXECUTABLE} boost_thread) - find_package(Threads REQUIRED) - target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT}) -endif () install( TARGETS ${EXECUTABLE} ARCHIVE DESTINATION lib LIBRARY DESTINATION lib ) install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} ) - diff --git a/libwhisper/Common.cpp b/libwhisper/Common.cpp index 8f58ae994..afeca48a8 100644 --- a/libwhisper/Common.cpp +++ b/libwhisper/Common.cpp @@ -33,7 +33,7 @@ Topic BuildTopic::toTopic() const Topic ret; ret.reserve(m_parts.size()); for (auto const& h: m_parts) - ret.push_back((TopicPart)u256(h)); + ret.push_back(TopicPart(h)); return ret; } @@ -54,10 +54,16 @@ bool TopicFilter::matches(Envelope const& _e) const { for (TopicMask const& t: m_topicMasks) { - if (_e.topics().size() == t.size()) - for (unsigned i = 0; i < t.size(); ++i) - if (((t[i].first ^ _e.topics()[i]) & t[i].second) != 0) - goto NEXT_TOPICMASK; + for (unsigned i = 0; i < t.size(); ++i) + { + for (auto et: _e.topics()) + if (((t[i].first ^ et) & t[i].second) == 0) + goto NEXT_TOPICPART; + // failed to match topicmask against any topics: move on to next mask + goto NEXT_TOPICMASK; + NEXT_TOPICPART:; + } + // all topicmasks matched. return true; NEXT_TOPICMASK:; } @@ -69,7 +75,7 @@ TopicMask BuildTopicMask::toTopicMask() const TopicMask ret; ret.reserve(m_parts.size()); for (auto const& h: m_parts) - ret.push_back(make_pair((TopicPart)u256(h), h ? ~(uint32_t)0 : 0)); + ret.push_back(make_pair(TopicPart(h), ~TopicPart())); return ret; } diff --git a/libwhisper/Common.h b/libwhisper/Common.h index f47778afe..5ce7d3b1c 100644 --- a/libwhisper/Common.h +++ b/libwhisper/Common.h @@ -59,7 +59,7 @@ enum WhisperPacket PacketCount }; -using TopicPart = uint32_t; +using TopicPart = FixedHash<4>; using Topic = std::vector; @@ -92,7 +92,15 @@ public: TopicFilter() {} TopicFilter(TopicMask const& _m): m_topicMasks(1, _m) {} TopicFilter(TopicMasks const& _m): m_topicMasks(_m) {} - TopicFilter(RLP const& _r): m_topicMasks((TopicMasks)_r) {} + TopicFilter(RLP const& _r)//: m_topicMasks(_r.toVector>()) + { + for (RLP i: _r) + { + m_topicMasks.push_back(TopicMask()); + for (RLP j: i) + m_topicMasks.back().push_back(j.toPair, FixedHash<4>>()); + } + } void streamRLP(RLPStream& _s) const { _s << m_topicMasks; } h256 sha3() const; @@ -106,17 +114,12 @@ private: class BuildTopicMask: BuildTopic { public: - enum EmptyType { Empty }; - - BuildTopicMask() { shift(); } - BuildTopicMask(EmptyType) {} + BuildTopicMask() {} template BuildTopicMask(T const& _t) { shift(_t); } template BuildTopicMask& shift(T const& _r) { BuildTopic::shift(_r); return *this; } BuildTopicMask& shiftRaw(h256 const& _h) { BuildTopic::shiftRaw(_h); return *this; } - BuildTopic& shift() { m_parts.push_back(h256()); return *this; } - BuildTopicMask& operator()() { shift(); return *this; } template BuildTopicMask& operator()(T const& _t) { shift(_t); return *this; } operator TopicMask() const { return toTopicMask(); } diff --git a/libwhisper/Message.cpp b/libwhisper/Message.cpp index 65da72f9d..07620a7cf 100644 --- a/libwhisper/Message.cpp +++ b/libwhisper/Message.cpp @@ -89,6 +89,15 @@ Envelope Message::seal(Secret _from, Topic const& _topic, unsigned _ttl, unsigne return ret; } +Envelope::Envelope(RLP const& _m) +{ + m_expiry = _m[0].toInt(); + m_ttl = _m[1].toInt(); + m_topic = _m[2].toVector>(); + m_data = _m[3].toBytes(); + m_nonce = _m[4].toInt(); +} + Message Envelope::open(Secret const& _s) const { return Message(*this, _s); diff --git a/libwhisper/Message.h b/libwhisper/Message.h index 3b0d14aae..f582b14c7 100644 --- a/libwhisper/Message.h +++ b/libwhisper/Message.h @@ -51,14 +51,7 @@ class Envelope public: Envelope() {} - Envelope(RLP const& _m) - { - m_expiry = _m[0].toInt(); - m_ttl = _m[1].toInt(); - m_topic = (Topic)_m[2]; - m_data = _m[3].toBytes(); - m_nonce = _m[4].toInt(); - } + Envelope(RLP const& _m); operator bool() const { return !!m_expiry; } diff --git a/libwhisper/WhisperHost.cpp b/libwhisper/WhisperHost.cpp index 0fb7a206c..589f8f047 100644 --- a/libwhisper/WhisperHost.cpp +++ b/libwhisper/WhisperHost.cpp @@ -68,7 +68,7 @@ void WhisperHost::inject(Envelope const& _m, WhisperPeer* _p) return; UpgradeGuard ll(l); m_messages[h] = _m; - m_expiryQueue[_m.expiry()] = h; + m_expiryQueue.insert(make_pair(_m.expiry(), h)); } // if (_p) @@ -118,7 +118,6 @@ unsigned WhisperHost::installWatch(shh::TopicFilter const& _f) h256s WhisperHost::watchMessages(unsigned _watchId) { - cleanup(); h256s ret; auto wit = m_watches.find(_watchId); if (wit == m_watches.end()) @@ -156,6 +155,13 @@ void WhisperHost::uninstallWatch(unsigned _i) m_filters.erase(fit); } +void WhisperHost::doWork() +{ + for (auto& i: peers()) + i->cap()->sendMessages(); + cleanup(); +} + void WhisperHost::cleanup() { // remove old messages. diff --git a/libwhisper/WhisperHost.h b/libwhisper/WhisperHost.h index 91934dd98..1a4ec2a71 100644 --- a/libwhisper/WhisperHost.h +++ b/libwhisper/WhisperHost.h @@ -27,6 +27,7 @@ #include #include #include +#include #include #include #include "Common.h" @@ -38,7 +39,7 @@ namespace dev namespace shh { -class WhisperHost: public HostCapability, public Interface +class WhisperHost: public HostCapability, public Interface, public Worker { friend class WhisperPeer; @@ -64,14 +65,20 @@ public: void cleanup(); +protected: + void doWork(); + private: + virtual void onStarting() { startWorking(); } + virtual void onStopping() { stopWorking(); } + void streamMessage(h256 _m, RLPStream& _s) const; void noteChanged(h256 _messageHash, h256 _filter); mutable dev::SharedMutex x_messages; std::map m_messages; - std::map m_expiryQueue; + std::multimap m_expiryQueue; mutable dev::Mutex m_filterLock; std::map m_filters; diff --git a/libwhisper/WhisperPeer.cpp b/libwhisper/WhisperPeer.cpp index 56f4e456e..1dbd6e16e 100644 --- a/libwhisper/WhisperPeer.cpp +++ b/libwhisper/WhisperPeer.cpp @@ -72,7 +72,6 @@ bool WhisperPeer::interpret(unsigned _id, RLP const& _r) for (auto i: _r) if (n++) host()->inject(Envelope(i), this); - sendMessages(); break; } default: @@ -84,27 +83,22 @@ bool WhisperPeer::interpret(unsigned _id, RLP const& _r) void WhisperPeer::sendMessages() { RLPStream amalg; - unsigned n = 0; - + unsigned msgCount = 0; { Guard l(x_unseen); + msgCount = m_unseen.size(); while (m_unseen.size()) { auto p = *m_unseen.begin(); m_unseen.erase(m_unseen.begin()); host()->streamMessage(p.second, amalg); - n++; } } - - if (!n) - // pause for a bit if no messages to send - this is horrible and broken. - // the message subsystem should really just keep pumping out messages while m_unseen.size() and there's bandwidth for them. - this_thread::sleep_for(chrono::milliseconds(20)); - + + if (msgCount) { RLPStream s; - prep(s, MessagesPacket, n).appendRaw(amalg.out(), n); + prep(s, MessagesPacket, msgCount).appendRaw(amalg.out(), msgCount); sealAndSend(s); } } @@ -112,5 +106,5 @@ void WhisperPeer::sendMessages() void WhisperPeer::noteNewMessage(h256 _h, Message const& _m) { Guard l(x_unseen); - m_unseen[rating(_m)] = _h; + m_unseen.insert(make_pair(rating(_m), _h)); } diff --git a/libwhisper/WhisperPeer.h b/libwhisper/WhisperPeer.h index f60de8f01..d21f33725 100644 --- a/libwhisper/WhisperPeer.h +++ b/libwhisper/WhisperPeer.h @@ -67,7 +67,9 @@ private: void noteNewMessage(h256 _h, Message const& _m); mutable dev::Mutex x_unseen; - std::map m_unseen; ///< Rated according to what they want. + std::multimap m_unseen; ///< Rated according to what they want. + + std::chrono::system_clock::time_point m_timer = std::chrono::system_clock::now(); }; } diff --git a/libwhisper/_libwhisper.cpp b/libwhisper/_libwhisper.cpp deleted file mode 100644 index 813c6a657..000000000 --- a/libwhisper/_libwhisper.cpp +++ /dev/null @@ -1,8 +0,0 @@ -#ifdef _MSC_VER -#include "All.h" -#include "Common.cpp" -#include "WhisperPeer.cpp" -#include "WhisperHost.cpp" -#include "Message.cpp" -#include "Interface.cpp" -#endif diff --git a/lllc/CMakeLists.txt b/lllc/CMakeLists.txt index a9b53c74c..2e76aa6ff 100644 --- a/lllc/CMakeLists.txt +++ b/lllc/CMakeLists.txt @@ -1,32 +1,21 @@ cmake_policy(SET CMP0015 NEW) +set(CMAKE_AUTOMOC OFF) aux_source_directory(. SRC_LIST) +include_directories(${Boost_INCLUDE_DIRS}) include_directories(..) set(EXECUTABLE lllc) -add_executable(${EXECUTABLE} ${SRC_LIST}) +file(GLOB HEADERS "*.h") +add_executable(${EXECUTABLE} ${SRC_LIST} ${HEADERS}) + +add_dependencies(${EXECUTABLE} BuildInfo.h) target_link_libraries(${EXECUTABLE} lll) target_link_libraries(${EXECUTABLE} evmcore) target_link_libraries(${EXECUTABLE} devcore) -if ("${TARGET_PLATFORM}" STREQUAL "w64") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -static-libgcc -static-libstdc++") - target_link_libraries(${EXECUTABLE} gcc) - target_link_libraries(${EXECUTABLE} gdi32) - target_link_libraries(${EXECUTABLE} ws2_32) - target_link_libraries(${EXECUTABLE} mswsock) - target_link_libraries(${EXECUTABLE} shlwapi) - target_link_libraries(${EXECUTABLE} iphlpapi) - target_link_libraries(${EXECUTABLE} boost_thread_win32-mt-s) - set(CMAKE_SHARED_LIBRARY_LINK_CXX_FLAGS) -elseif (UNIX) -else () - find_package(Threads REQUIRED) - target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT}) -endif () - install( TARGETS ${EXECUTABLE} DESTINATION bin ) diff --git a/mix/.gitignore b/mix/.gitignore new file mode 100644 index 000000000..f96209dc3 --- /dev/null +++ b/mix/.gitignore @@ -0,0 +1 @@ +*.pro diff --git a/mix/ApplicationCtx.cpp b/mix/ApplicationCtx.cpp new file mode 100644 index 000000000..f97478f3c --- /dev/null +++ b/mix/ApplicationCtx.cpp @@ -0,0 +1,36 @@ +/* + This file is part of cpp-ethereum. + cpp-ethereum is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + cpp-ethereum is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + You should have received a copy of the GNU General Public License + along with cpp-ethereum. If not, see . +*/ +/** @file ApplicationCtx.cpp + * @author Yann yann@ethdev.com + * @date 2014 + * Provide an access to the current QQmlApplicationEngine which is used to add QML file on the fly. + * In the future this class can be extended to add more variable related to the context of the application. + */ + +#include +#include "ApplicationCtx.h" +using namespace dev::mix; + +ApplicationCtx* ApplicationCtx::Instance = nullptr; + +QQmlApplicationEngine* ApplicationCtx::appEngine() +{ + return m_applicationEngine; +} + +void ApplicationCtx::setApplicationContext(QQmlApplicationEngine* _engine) +{ + if (Instance == nullptr) + Instance = new ApplicationCtx(_engine); +} diff --git a/mix/ApplicationCtx.h b/mix/ApplicationCtx.h new file mode 100644 index 000000000..37166ea05 --- /dev/null +++ b/mix/ApplicationCtx.h @@ -0,0 +1,55 @@ +/* + This file is part of cpp-ethereum. + + cpp-ethereum is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + cpp-ethereum is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with cpp-ethereum. If not, see . +*/ +/** @file ApplicationCtx.h + * @author Yann yann@ethdev.com + * @date 2014 + * Provide an access to the current QQmlApplicationEngine which is used to add QML file on the fly. + * In the future this class can be extended to add more variable related to the context of the application. + */ + +#pragma once + +#include + +namespace dev +{ + +namespace mix +{ + +class ApplicationCtx: public QObject +{ + Q_OBJECT + +public: + ApplicationCtx(QQmlApplicationEngine* _engine) { m_applicationEngine = _engine; } + ~ApplicationCtx() { delete m_applicationEngine; } + static ApplicationCtx* getInstance() { return Instance; } + static void setApplicationContext(QQmlApplicationEngine* _engine); + QQmlApplicationEngine* appEngine(); + +private: + static ApplicationCtx* Instance; + QQmlApplicationEngine* m_applicationEngine; + +public slots: + void quitApplication() { delete Instance; } +}; + +} + +} diff --git a/mix/CMakeLists.txt b/mix/CMakeLists.txt new file mode 100644 index 000000000..555f6290f --- /dev/null +++ b/mix/CMakeLists.txt @@ -0,0 +1,48 @@ +cmake_policy(SET CMP0015 NEW) +# let cmake autolink dependencies on windows +cmake_policy(SET CMP0020 NEW) +# this policy was introduced in cmake 3.0 +# remove if, once 3.0 will be used on unix +if (${CMAKE_MAJOR_VERSION} GREATER 2) + cmake_policy(SET CMP0043 OLD) +endif() + +set(CMAKE_INCLUDE_CURRENT_DIR ON) + +aux_source_directory(. SRC_LIST) +include_directories(..) + +qt5_add_resources(UI_RESOURCES qml.qrc) + +file(GLOB HEADERS "*.h") + +set(EXECUTABLE mix) + +# eth_add_executable is defined in cmake/EthExecutableHelper.cmake +eth_add_executable(${EXECUTABLE} + ICON mix + UI_RESOURCES ${UI_RESOURCES} +) + +target_link_libraries(${EXECUTABLE} Qt5::Core) +target_link_libraries(${EXECUTABLE} Qt5::Gui) +target_link_libraries(${EXECUTABLE} webthree) +target_link_libraries(${EXECUTABLE} qethereum) +target_link_libraries(${EXECUTABLE} ethereum) +target_link_libraries(${EXECUTABLE} evm) +target_link_libraries(${EXECUTABLE} ethcore) +target_link_libraries(${EXECUTABLE} devcrypto) +target_link_libraries(${EXECUTABLE} secp256k1) +target_link_libraries(${EXECUTABLE} serpent) +target_link_libraries(${EXECUTABLE} lll) +target_link_libraries(${EXECUTABLE} solidity) +target_link_libraries(${EXECUTABLE} evmcore) +target_link_libraries(${EXECUTABLE} devcore) +target_link_libraries(${EXECUTABLE} web3jsonrpc) +target_link_libraries(${EXECUTABLE} jsqrc) + +# eth_install_executable is defined in cmake/EthExecutableHelper.cmake +eth_install_executable(${EXECUTABLE} + QMLDIR ${CMAKE_CURRENT_SOURCE_DIR}/qml +) + diff --git a/mix/CodeEditorExtensionManager.cpp b/mix/CodeEditorExtensionManager.cpp new file mode 100644 index 000000000..c778d466f --- /dev/null +++ b/mix/CodeEditorExtensionManager.cpp @@ -0,0 +1,88 @@ +/* + This file is part of cpp-ethereum. + + cpp-ethereum is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + cpp-ethereum is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with cpp-ethereum. If not, see . +*/ +/** @file CodeEditorExtensionMan.cpp + * @author Yann yann@ethdev.com + * @date 2014 + * Ethereum IDE client. + */ + +#include +#include +#include +#include +#include +#include +#include "ConstantCompilationCtrl.h" +#include "ApplicationCtx.h" +#include "CodeEditorExtensionManager.h" +using namespace dev::mix; + +CodeEditorExtensionManager::~CodeEditorExtensionManager() +{ + m_features.clear(); +} + +void CodeEditorExtensionManager::loadEditor(QQuickItem* _editor) +{ + if (!_editor) + return; + try + { + QVariant doc = _editor->property("textDocument"); + if (doc.canConvert()) + { + QQuickTextDocument* qqdoc = doc.value(); + if (qqdoc) + m_doc = qqdoc->textDocument(); + } + } + catch (...) + { + qDebug() << "unable to load editor: "; + } +} + +void CodeEditorExtensionManager::initExtensions() +{ + //only one for now + std::shared_ptr constantCompilation = std::make_shared(m_doc); + if (constantCompilation.get()->contentUrl() != "") + { + try + { + constantCompilation.get()->addContentOn(m_tabView); + } + catch (...) + { + qDebug() << "Exception when adding content into view."; + return; + } + } + constantCompilation.get()->start(); + m_features.append(constantCompilation); +} + +void CodeEditorExtensionManager::setEditor(QQuickItem* _editor) +{ + this->loadEditor(_editor); + this->initExtensions(); +} + +void CodeEditorExtensionManager::setTabView(QQuickItem* _tabView) +{ + m_tabView = _tabView; +} diff --git a/mix/CodeEditorExtensionManager.h b/mix/CodeEditorExtensionManager.h new file mode 100644 index 000000000..2b8402bf2 --- /dev/null +++ b/mix/CodeEditorExtensionManager.h @@ -0,0 +1,61 @@ +/* + This file is part of cpp-ethereum. + + cpp-ethereum is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + cpp-ethereum is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with cpp-ethereum. If not, see . +*/ +/** @file CodeEditorExtensionMan.h + * @author Yann yann@ethdev.com + * @date 2014 + * Ethereum IDE client. + */ + +#pragma once + +#include "memory" +#include +#include +#include +#include "ConstantCompilationCtrl.h" + +namespace dev +{ + +namespace mix +{ + +class CodeEditorExtensionManager: public QObject +{ + Q_OBJECT + + Q_PROPERTY(QQuickItem* editor MEMBER m_editor WRITE setEditor) + Q_PROPERTY(QQuickItem* tabView MEMBER m_tabView WRITE setTabView) + +public: + CodeEditorExtensionManager() {} + ~CodeEditorExtensionManager(); + void initExtensions(); + void setEditor(QQuickItem*); + void setTabView(QQuickItem*); + +private: + QQuickItem* m_editor; + QVector> m_features; + QQuickItem* m_tabView; + QTextDocument* m_doc; + void loadEditor(QQuickItem*); +}; + +} + +} diff --git a/mix/ConstantCompilationCtrl.cpp b/mix/ConstantCompilationCtrl.cpp new file mode 100644 index 000000000..06b9c0284 --- /dev/null +++ b/mix/ConstantCompilationCtrl.cpp @@ -0,0 +1,97 @@ +/* + This file is part of cpp-ethereum. + + cpp-ethereum is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + cpp-ethereum is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with cpp-ethereum. If not, see . +*/ +/** @file ConstantCompilation.cpp + * @author Yann yann@ethdev.com + * @date 2014 + * Ethereum IDE client. + */ + +#include +#include +#include +#include +#include +#include +#include "ConstantCompilationCtrl.h" +#include "ConstantCompilationModel.h" +using namespace dev::mix; + +ConstantCompilationCtrl::ConstantCompilationCtrl(QTextDocument* _doc) +{ + m_editor = _doc; + m_compilationModel = new ConstantCompilationModel(); +} + +ConstantCompilationCtrl::~ConstantCompilationCtrl() +{ + delete m_compilationModel; +} + +QString ConstantCompilationCtrl::contentUrl() const +{ + return QStringLiteral("qrc:/qml/BasicContent.qml"); +} + +QString ConstantCompilationCtrl::title() const +{ + return "compiler"; +} + +void ConstantCompilationCtrl::start() const +{ + connect(m_editor, SIGNAL(contentsChange(int,int,int)), this, SLOT(compile())); +} + +void ConstantCompilationCtrl::compile() +{ + QString codeContent = m_editor->toPlainText().replace("\n", ""); + if (codeContent.isEmpty()) + { + resetOutPut(); + return; + } + CompilerResult res = m_compilationModel->compile(m_editor->toPlainText()); + writeOutPut(res); +} + +void ConstantCompilationCtrl::resetOutPut() +{ + QObject* status = m_view->findChild("status", Qt::FindChildrenRecursively); + QObject* content = m_view->findChild("content", Qt::FindChildrenRecursively); + status->setProperty("text", ""); + content->setProperty("text", ""); +} + +void ConstantCompilationCtrl::writeOutPut(CompilerResult const& _res) +{ + QObject* status = m_view->findChild("status", Qt::FindChildrenRecursively); + QObject* content = m_view->findChild("content", Qt::FindChildrenRecursively); + if (_res.success) + { + status->setProperty("text", "succeeded"); + status->setProperty("color", "green"); + content->setProperty("text", _res.hexCode); + qDebug() << QString("compile succeeded " + _res.hexCode); + } + else + { + status->setProperty("text", "failure"); + status->setProperty("color", "red"); + content->setProperty("text", _res.comment); + qDebug() << QString("compile failed " + _res.comment); + } +} diff --git a/mix/ConstantCompilationCtrl.h b/mix/ConstantCompilationCtrl.h new file mode 100644 index 000000000..e4661c800 --- /dev/null +++ b/mix/ConstantCompilationCtrl.h @@ -0,0 +1,55 @@ +/* + This file is part of cpp-ethereum. + cpp-ethereum is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + cpp-ethereum is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + You should have received a copy of the GNU General Public License + along with cpp-ethereum. If not, see . +*/ +/** @file ConstantCompilation.h + * @author Yann yann@ethdev.com + * @date 2014 + * Ethereum IDE client. + */ + +#pragma once + +#include +#include "ConstantCompilationModel.h" +#include "Extension.h" + +namespace dev +{ + +namespace mix +{ + +class ConstantCompilationCtrl: public Extension +{ + Q_OBJECT + +public: + ConstantCompilationCtrl(QTextDocument*); + ~ConstantCompilationCtrl(); + void start() const override; + QString title() const override; + QString contentUrl() const override; + +private: + QTextDocument* m_editor; + ConstantCompilationModel* m_compilationModel; + void writeOutPut(CompilerResult const&); + void resetOutPut(); + +public Q_SLOTS: + void compile(); +}; + +} + +} diff --git a/mix/ConstantCompilationModel.cpp b/mix/ConstantCompilationModel.cpp new file mode 100644 index 000000000..ea12a267c --- /dev/null +++ b/mix/ConstantCompilationModel.cpp @@ -0,0 +1,61 @@ +/* + This file is part of cpp-ethereum. + + cpp-ethereum is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + cpp-ethereum is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with cpp-ethereum. If not, see . +*/ +/** @file ApplicationCtx.h + * @author Yann yann@ethdev.com + * @date 2014 + * Ethereum IDE client. + */ + +#include +#include +#include +#include +#include +#include "ConstantCompilationModel.h" +using namespace std; +using namespace dev; +using namespace dev::eth; +using namespace dev::mix; + +CompilerResult ConstantCompilationModel::compile(QString _code) +{ + dev::solidity::CompilerStack compiler; + dev::bytes m_data; + CompilerResult res; + try + { + m_data = compiler.compile(_code.toStdString(), true); + res.success = true; + res.comment = "ok"; + res.hexCode = QString::fromStdString(dev::eth::disassemble(m_data)); + } + catch (dev::Exception const& _exception) + { + ostringstream error; + solidity::SourceReferenceFormatter::printExceptionInformation(error, _exception, "Error", compiler); + res.success = false; + res.comment = QString::fromStdString(error.str()).toHtmlEscaped(); + res.hexCode = ""; + } + catch (...) + { + res.success = false; + res.comment = "Uncaught exception."; + res.hexCode = ""; + } + return res; +} diff --git a/windows/stdafx.cpp b/mix/ConstantCompilationModel.h similarity index 64% rename from windows/stdafx.cpp rename to mix/ConstantCompilationModel.h index d3c5fc299..4a17853f6 100644 --- a/windows/stdafx.cpp +++ b/mix/ConstantCompilationModel.h @@ -14,8 +14,38 @@ You should have received a copy of the GNU General Public License along with cpp-ethereum. If not, see . */ -/** @file stdafx.cpp - * @author Tim Hughes +/** @file ApplicationCtx.h + * @author Yann yann@ethdev.com * @date 2014 + * Ethereum IDE client. */ +#pragma once + +#include + +namespace dev +{ + +namespace mix +{ + +struct CompilerResult +{ + QString hexCode; + QString comment; + bool success; +}; + +class ConstantCompilationModel +{ + +public: + ConstantCompilationModel() {} + ~ConstantCompilationModel() {} + CompilerResult compile(QString code); +}; + +} + +} diff --git a/mix/Extension.cpp b/mix/Extension.cpp new file mode 100644 index 000000000..5aeb0cc17 --- /dev/null +++ b/mix/Extension.cpp @@ -0,0 +1,44 @@ +/* + This file is part of cpp-ethereum. + cpp-ethereum is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + cpp-ethereum is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + You should have received a copy of the GNU General Public License + along with cpp-ethereum. If not, see . +*/ +/** @file Feature.cpp + * @author Yann yann@ethdev.com + * @date 2014 + * Ethereum IDE client. + */ + +#include +#include +#include +#include "Extension.h" +#include "ApplicationCtx.h" +using namespace dev; +using namespace dev::mix; + +void Extension::addContentOn(QObject* _tabView) +{ + if (contentUrl() == "") + return; + + QVariant returnValue; + QQmlComponent* component = new QQmlComponent( + ApplicationCtx::getInstance()->appEngine(), + QUrl(this->contentUrl()), _tabView); + + QMetaObject::invokeMethod(_tabView, "addTab", + Q_RETURN_ARG(QVariant, returnValue), + Q_ARG(QVariant, this->title()), + Q_ARG(QVariant, QVariant::fromValue(component))); + + m_view = qvariant_cast(returnValue); +} diff --git a/libethcore/CryptoHeaders.h b/mix/Extension.h similarity index 59% rename from libethcore/CryptoHeaders.h rename to mix/Extension.h index 4ff63f1d7..f8fef0aa6 100644 --- a/libethcore/CryptoHeaders.h +++ b/mix/Extension.h @@ -1,36 +1,48 @@ /* This file is part of cpp-ethereum. - cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - cpp-ethereum is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. - You should have received a copy of the GNU General Public License along with cpp-ethereum. If not, see . */ -/** @file CryptoHeaders.h - * @author Tim Hughes +/** @file Feature.h + * @author Yann yann@ethdev.com * @date 2014 + * Ethereum IDE client. */ + #pragma once -// need to leave this one disabled -#pragma GCC diagnostic ignored "-Wunused-function" - -#pragma warning(push) -#pragma warning(disable:4100 4244) -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wconversion" -#pragma GCC diagnostic ignored "-Wunused-parameter" -#include -#include -#include -#include -#pragma warning(pop) -#pragma GCC diagnostic pop +#include +#include + +namespace dev +{ + +namespace mix +{ + +class Extension: public QObject +{ + Q_OBJECT + +public: + Extension() {} + virtual QString contentUrl() const { return ""; } + virtual QString title() const { return ""; } + virtual void start() const {} + void addContentOn(QObject* tabView); + +protected: + QObject* m_view; +}; + +} + +} diff --git a/mix/MixApplication.cpp b/mix/MixApplication.cpp new file mode 100644 index 000000000..e67ca1b12 --- /dev/null +++ b/mix/MixApplication.cpp @@ -0,0 +1,45 @@ +/* + This file is part of cpp-ethereum. + + cpp-ethereum is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + cpp-ethereum is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with cpp-ethereum. If not, see . +*/ +/** @file main.cpp + * @author Yann yann@ethdev.com + * @date 2014 + */ + +#include +#include "MixApplication.h" +using namespace dev::mix; + +MixApplication::MixApplication(int _argc, char *_argv[]): QApplication(_argc, _argv) +{ +} + +bool MixApplication::notify(QObject* _receiver, QEvent* _event) +{ + try + { + return MixApplication::notify(_receiver, _event); + } + catch (std::exception& _ex) + { + qDebug() << "std::exception was caught " << _ex.what(); + } + catch (...) + { + qDebug() << "uncaught exception "; + } + return false; +} diff --git a/mix/MixApplication.h b/mix/MixApplication.h new file mode 100644 index 000000000..fdc506268 --- /dev/null +++ b/mix/MixApplication.h @@ -0,0 +1,46 @@ +/* + This file is part of cpp-ethereum. + + cpp-ethereum is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + cpp-ethereum is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with cpp-ethereum. If not, see . +*/ +/** @file main.cpp + * @author Yann yann@ethdev.com + * @date 2014 + * This class will be use instead of QApplication to launch the application. the method 'notify' allows to catch all exceptions. + * Not use for now: TODO. + */ + +#pragma once + +#include + +namespace dev +{ + +namespace mix +{ + +class MixApplication: public QApplication +{ + Q_OBJECT + +public: + MixApplication(int _argc, char* _argv[]); + virtual ~MixApplication() {} + virtual bool notify(QObject* _receiver, QEvent* _event); +}; + +} + +} diff --git a/mix/main.cpp b/mix/main.cpp new file mode 100644 index 000000000..537941290 --- /dev/null +++ b/mix/main.cpp @@ -0,0 +1,40 @@ +/* + This file is part of cpp-ethereum. + + cpp-ethereum is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + cpp-ethereum is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with cpp-ethereum. If not, see . +*/ +/** @file main.cpp + * @author Yann yann@ethdev.com + * @date 2014 + * Ethereum IDE client. + */ + +#include +#include +#include +#include "CodeEditorExtensionManager.h" +#include "ApplicationCtx.h" +#include "MixApplication.h" +using namespace dev::mix; + +int main(int _argc, char *_argv[]) +{ + QApplication app(_argc, _argv); + qmlRegisterType("CodeEditorExtensionManager", 1, 0, "CodeEditorExtensionManager"); + QQmlApplicationEngine* engine = new QQmlApplicationEngine(); + ApplicationCtx::setApplicationContext(engine); + QObject::connect(&app, SIGNAL(lastWindowClosed()), ApplicationCtx::getInstance(), SLOT(quitApplication())); //use to kill ApplicationContext and other stuff + engine->load(QUrl(QStringLiteral("qrc:/qml/main.qml"))); + return app.exec(); +} diff --git a/mix/qml.qrc b/mix/qml.qrc new file mode 100644 index 000000000..267427ce5 --- /dev/null +++ b/mix/qml.qrc @@ -0,0 +1,8 @@ + + + qml/BasicContent.qml + qml/main.qml + qml/MainContent.qml + qml/TabStyle.qml + + diff --git a/mix/qml/BasicContent.qml b/mix/qml/BasicContent.qml new file mode 100644 index 000000000..ea1017186 --- /dev/null +++ b/mix/qml/BasicContent.qml @@ -0,0 +1,35 @@ +import QtQuick 2.2 +import QtQuick.Controls 1.1 + +Rectangle { + anchors.fill: parent + width: parent.width + height: parent.height + color: "lightgray" + Text { + font.pointSize: 7 + anchors.left: parent.left + anchors.top: parent.top + anchors.topMargin: 3 + anchors.leftMargin: 3 + height: 9 + font.family: "Sego UI light" + objectName: "status" + id: status + } + TextArea { + readOnly: true + anchors.left: parent.left + anchors.leftMargin: 10 + anchors.top: status.bottom + anchors.topMargin: 3 + font.pointSize: 7 + font.family: "Sego UI light" + height: parent.height * 0.8 + width: parent.width - 20 + wrapMode: Text.Wrap + backgroundVisible: false + objectName: "content" + id: content + } +} diff --git a/mix/qml/MainContent.qml b/mix/qml/MainContent.qml new file mode 100644 index 000000000..bd4737c3b --- /dev/null +++ b/mix/qml/MainContent.qml @@ -0,0 +1,54 @@ +import QtQuick 2.2 +import QtQuick.Controls 1.1 +import QtQuick.Layouts 1.0 +import QtQuick.Controls.Styles 1.1 +import CodeEditorExtensionManager 1.0 + +Rectangle { + anchors.fill: parent + height: parent.height + width: parent.width; + id:root + SplitView { + anchors.fill: parent + orientation: Qt.Vertical + Rectangle { + anchors.top: parent.top + id: contentView + width: parent.width + height: parent.height * 0.7 + TextArea { + id: codeEditor + height: parent.height + font.family: "Verdana" + font.pointSize: 9 + width: parent.width + anchors.centerIn: parent + tabChangesFocus: false + Keys.onPressed: { + if (event.key === Qt.Key_Tab) { + codeEditor.insert(codeEditor.cursorPosition, "\t"); + event.accepted = true; + } + } + } + } + Rectangle { + anchors.bottom: parent.bottom + id: contextualView + width: parent.width + Layout.minimumHeight: 20 + height: parent.height * 0.3 + TabView { + id: contextualTabs + antialiasing: true + anchors.fill: parent + style: TabStyle {} + } + } + CodeEditorExtensionManager{ + tabView: contextualTabs + editor: codeEditor + } + } +} diff --git a/mix/qml/TabStyle.qml b/mix/qml/TabStyle.qml new file mode 100644 index 000000000..cbae6e25e --- /dev/null +++ b/mix/qml/TabStyle.qml @@ -0,0 +1,23 @@ +import QtQuick 2.2 +import QtQuick.Controls 1.1 +import QtQuick.Controls.Styles 1.1 + +TabViewStyle { + frameOverlap: 1 + tabBar: Rectangle { + color: "lightgray" + } + tab: Rectangle { + color: "lightsteelblue" + implicitWidth: Math.max(text.width + 4, 80) + implicitHeight: 20 + radius: 2 + Text { + id: text + anchors.centerIn: parent + text: styleData.title + color: styleData.selected ? "white" : "black" + } + } + frame: Rectangle { color: "steelblue" } +} diff --git a/mix/qml/main.qml b/mix/qml/main.qml new file mode 100644 index 000000000..3553f7710 --- /dev/null +++ b/mix/qml/main.qml @@ -0,0 +1,24 @@ +import QtQuick 2.2 +import QtQuick.Controls 1.1 +import QtQuick.Controls.Styles 1.1 +import CodeEditorExtensionManager 1.0 + +ApplicationWindow { + visible: true + width: 1000 + height: 480 + minimumWidth: 400 + minimumHeight: 300 + title: qsTr("mix") + menuBar: MenuBar { + Menu { + title: qsTr("File") + MenuItem { + text: qsTr("Exit") + onTriggered: Qt.quit(); + } + } + } + MainContent{ + } +} diff --git a/neth/CMakeLists.txt b/neth/CMakeLists.txt index ac275f663..4db3d2cf4 100644 --- a/neth/CMakeLists.txt +++ b/neth/CMakeLists.txt @@ -2,52 +2,27 @@ cmake_policy(SET CMP0015 NEW) aux_source_directory(. SRC_LIST) +include_directories(${JSON_RPC_CPP_INCLUDE_DIRS}) +include_directories(${LEVELDB_INCLUDE_DIRS}) include_directories(..) -include_directories(${LEVELDB_ID}) set(EXECUTABLE neth) add_executable(${EXECUTABLE} ${SRC_LIST}) +add_dependencies(${EXECUTABLE} BuildInfo.h) + +target_link_libraries(${EXECUTABLE} ${LEVELDB_LIBRARIES}) + +if (JSONRPC) + target_link_libraries(${EXECUTABLE} web3jsonrpc) +endif() + target_link_libraries(${EXECUTABLE} webthree) target_link_libraries(${EXECUTABLE} ethereum) target_link_libraries(${EXECUTABLE} secp256k1) -target_link_libraries(${EXECUTABLE} gmp) -if(MINIUPNPC_LS) -target_link_libraries(${EXECUTABLE} ${MINIUPNPC_LS}) -endif() -target_link_libraries(${EXECUTABLE} ${LEVELDB_LS}) -target_link_libraries(${EXECUTABLE} ${CRYPTOPP_LS}) -if(JSONRPC_LS) -target_link_libraries(${EXECUTABLE} web3jsonrpc) -endif() - -if ("${TARGET_PLATFORM}" STREQUAL "w64") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -static-libgcc -static-libstdc++") - target_link_libraries(${EXECUTABLE} gcc) - target_link_libraries(${EXECUTABLE} gdi32) - target_link_libraries(${EXECUTABLE} ws2_32) - target_link_libraries(${EXECUTABLE} mswsock) - target_link_libraries(${EXECUTABLE} shlwapi) - target_link_libraries(${EXECUTABLE} iphlpapi) - target_link_libraries(${EXECUTABLE} cryptopp) - target_link_libraries(${EXECUTABLE} ncurses) - target_link_libraries(${EXECUTABLE} form) - target_link_libraries(${EXECUTABLE} boost_system-mt-s) - target_link_libraries(${EXECUTABLE} boost_filesystem-mt-s) - target_link_libraries(${EXECUTABLE} boost_thread_win32-mt-s) - set(CMAKE_SHARED_LIBRARY_LINK_CXX_FLAGS) -elseif (UNIX) - target_link_libraries(${EXECUTABLE} ncurses) - target_link_libraries(${EXECUTABLE} form) -else () - target_link_libraries(${EXECUTABLE} boost_system) - target_link_libraries(${EXECUTABLE} boost_filesystem) - target_link_libraries(${EXECUTABLE} ncurses) - target_link_libraries(${EXECUTABLE} form) - find_package(Threads REQUIRED) - target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT}) -endif () +target_link_libraries(${EXECUTABLE} ncurses) +target_link_libraries(${EXECUTABLE} form) install( TARGETS ${EXECUTABLE} DESTINATION bin ) diff --git a/neth/main.cpp b/neth/main.cpp index 6be555fbb..1eac7fb1f 100644 --- a/neth/main.cpp +++ b/neth/main.cpp @@ -26,16 +26,12 @@ #include #include #include -#if ETH_JSONRPC -#include -#endif #include #include #include #if ETH_JSONRPC #include -#include -#include +#include #endif #include #include "BuildInfo.h" @@ -475,10 +471,12 @@ int main(int argc, char** argv) c.startMining(); #if ETH_JSONRPC - auto_ptr jsonrpcServer; + shared_ptr jsonrpcServer; + unique_ptr jsonrpcConnector; if (jsonrpc > -1) { - jsonrpcServer = auto_ptr(new WebThreeStubServer(new jsonrpc::HttpServer(jsonrpc), web3, {us})); + jsonrpcConnector = unique_ptr(new jsonrpc::HttpServer(jsonrpc)); + jsonrpcServer = shared_ptr(new WebThreeStubServer(*jsonrpcConnector.get(), web3, vector({us}))); jsonrpcServer->setIdentities({us}); jsonrpcServer->StartListening(); } @@ -552,7 +550,8 @@ int main(int argc, char** argv) { if (jsonrpc < 0) jsonrpc = 8080; - jsonrpcServer = auto_ptr(new WebThreeStubServer(new jsonrpc::HttpServer(jsonrpc), web3, {us})); + jsonrpcConnector = unique_ptr(new jsonrpc::HttpServer(jsonrpc)); + jsonrpcServer = shared_ptr(new WebThreeStubServer(*jsonrpcConnector.get(), web3, vector({us}))); jsonrpcServer->setIdentities({us}); jsonrpcServer->StartListening(); } @@ -603,7 +602,7 @@ int main(int argc, char** argv) vector l; l.push_back("Amount"); stringstream label; - label << "Gas price (" << info.minGasPrice << ")"; + label << "Gas price"; l.push_back(label.str()); l.push_back("Gas"); vector b; @@ -646,14 +645,12 @@ int main(int argc, char** argv) ssbd << bbd; cnote << ssbd.str(); int ssize = fields[4].length(); - u256 minGas = (u256)Client::txGas(data.size(), 0); + u256 minGas = (u256)Client::txGas(data, 0); if (size < 40) { if (size > 0) cwarn << "Invalid address length:" << size; } - else if (gasPrice < info.minGasPrice) - cwarn << "Minimum gas price is" << info.minGasPrice; else if (gas < minGas) cwarn << "Minimum gas amount is" << minGas; else if (ssize < 40) @@ -702,9 +699,9 @@ int main(int argc, char** argv) auto h = bc.currentHash(); auto blockData = bc.block(h); BlockInfo info(blockData); - u256 minGas = (u256)Client::txGas(0, 0); + u256 minGas = (u256)Client::txGas(bytes(), 0); Address dest = h160(fromHex(fields[0])); - c.transact(us.secret(), amount, dest, bytes(), minGas, info.minGasPrice); + c.transact(us.secret(), amount, dest, bytes(), minGas); } } } @@ -718,7 +715,7 @@ int main(int argc, char** argv) vector l; l.push_back("Endowment"); stringstream label; - label << "Gas price (" << info.minGasPrice << ")"; + label << "Gas price"; l.push_back(label.str()); l.push_back("Gas"); vector b; @@ -763,16 +760,14 @@ int main(int argc, char** argv) cnote << "Init:"; cnote << ssc.str(); } - u256 minGas = (u256)Client::txGas(init.size(), 0); + u256 minGas = (u256)Client::txGas(init, 0); if (endowment < 0) cwarn << "Invalid endowment"; - else if (gasPrice < info.minGasPrice) - cwarn << "Minimum gas price is" << info.minGasPrice; else if (gas < minGas) cwarn << "Minimum gas amount is" << minGas; else { - c.transact(us.secret(), endowment, init, gas, gasPrice); + c.transact(us.secret(), endowment, init, gas); } } } diff --git a/sc/CMakeLists.txt b/sc/CMakeLists.txt index 9aa23b03b..2adde060e 100644 --- a/sc/CMakeLists.txt +++ b/sc/CMakeLists.txt @@ -13,22 +13,5 @@ target_link_libraries(${EXECUTABLE} lll) target_link_libraries(${EXECUTABLE} evmcore) target_link_libraries(${EXECUTABLE} devcore) -if ("${TARGET_PLATFORM}" STREQUAL "w64") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -static-libgcc -static-libstdc++") - target_link_libraries(${EXECUTABLE} gcc) - target_link_libraries(${EXECUTABLE} gdi32) - target_link_libraries(${EXECUTABLE} ws2_32) - target_link_libraries(${EXECUTABLE} mswsock) - target_link_libraries(${EXECUTABLE} shlwapi) - target_link_libraries(${EXECUTABLE} iphlpapi) - target_link_libraries(${EXECUTABLE} boost_thread_win32-mt-s) - set(CMAKE_SHARED_LIBRARY_LINK_CXX_FLAGS) -elseif (UNIX) -else () - find_package(Threads REQUIRED) - target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT}) -endif () - install( TARGETS ${EXECUTABLE} DESTINATION bin ) -cmake_policy(SET CMP0015 NEW) diff --git a/secp256k1/CMakeLists.txt b/secp256k1/CMakeLists.txt index 9b017f15f..8dbe175d5 100644 --- a/secp256k1/CMakeLists.txt +++ b/secp256k1/CMakeLists.txt @@ -1,48 +1,40 @@ cmake_policy(SET CMP0015 NEW) +# this policy was introduced in cmake 3.0 +# remove if, once 3.0 will be used on unix +if (${CMAKE_MAJOR_VERSION} GREATER 2) + # old policy do not use MACOSX_RPATH + cmake_policy(SET CMP0042 OLD) +endif() +set(CMAKE_AUTOMOC OFF) set(CMAKE_ASM_COMPILER "yasm") set(EXECUTABLE secp256k1) - file(GLOB HEADERS "*.h") -if ("${TARGET_PLATFORM}" STREQUAL "w64") - add_custom_command( - OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/field_5x52_asm.o - COMMAND yasm -f win64 -o ${CMAKE_CURRENT_BINARY_DIR}/field_5x52_asm.o ${CMAKE_CURRENT_SOURCE_DIR}/field_5x52_asm.asm - ) - add_custom_target( - asmOut ALL - DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/field_5x52_asm.o - ) - if(ETH_STATIC) - add_library(${EXECUTABLE} STATIC ${EXECUTABLE}.c ${CMAKE_CURRENT_BINARY_DIR}/field_5x52_asm.o) - else() - add_library(${EXECUTABLE} SHARED ${EXECUTABLE}.c ${CMAKE_CURRENT_BINARY_DIR}/field_5x52_asm.o) - endif() - set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=gnu99 -DUSE_FIELD_5X52 -DUSE_FIELD_5X52_ASM -DUSE_NUM_GMP -DUSE_FIELD_INV_NUM") -elseif(APPLE) - if(ETH_STATIC) +if (APPLE OR UNIX) + + if (ETH_STATIC) add_library(${EXECUTABLE} STATIC ${EXECUTABLE}.c field_5x52_asm.asm) else() - find_library(GMP_LS gmp /usr/local/lib) add_library(${EXECUTABLE} SHARED ${EXECUTABLE}.c field_5x52_asm.asm) endif() set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c99 -DUSE_FIELD_GMP -DUSE_NUM_GMP -DUSE_FIELD_INV_NUM") + target_link_libraries(${EXECUTABLE} ${GMP_LIBRARIES}) else() - if(ETH_STATIC) - add_library(${EXECUTABLE} STATIC ${EXECUTABLE}.c field_5x52_asm.asm) + + include_directories(${Boost_INCLUDE_DIRS}) + + if (ETH_STATIC) + add_library(${EXECUTABLE} STATIC ${EXECUTABLE}.c) else() - add_library(${EXECUTABLE} SHARED ${EXECUTABLE}.c field_5x52_asm.asm) + add_library(${EXECUTABLE} SHARED ${EXECUTABLE}.c) endif() - set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c99 -DUSE_FIELD_GMP -DUSE_NUM_GMP -DUSE_FIELD_INV_NUM") + # /TP - compile project as cpp project + set_target_properties(${EXECUTABLE} PROPERTIES COMPILE_FLAGS "/TP") + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DUSE_NUM_BOOST -DUSE_FIELD_10X26 -DUSE_FIELD_INV_BUILTIN") + endif() -if (NOT GMP_LS) - set(GMP_LS gmp) -endif () - -target_link_libraries(${EXECUTABLE} ${GMP_LS}) - install( TARGETS ${EXECUTABLE} ARCHIVE DESTINATION lib LIBRARY DESTINATION lib ) install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} ) diff --git a/solc/CMakeLists.txt b/solc/CMakeLists.txt index 386d4a1a8..cf1e42572 100644 --- a/solc/CMakeLists.txt +++ b/solc/CMakeLists.txt @@ -1,13 +1,18 @@ cmake_policy(SET CMP0015 NEW) +set(CMAKE_AUTOMOC OFF) aux_source_directory(. SRC_LIST) +include_directories(${Boost_INCLUDE_DIRS}) include_directories(..) set(EXECUTABLE solc) -add_executable(${EXECUTABLE} ${SRC_LIST}) +file(GLOB HEADERS "*.h") +add_executable(${EXECUTABLE} ${SRC_LIST} ${HEADERS}) +target_link_libraries(${EXECUTABLE} ${Boost_FILESYSTEM_LIBRARY_RELEASE}) +target_link_libraries(${EXECUTABLE} ${Boost_PROGRAM_OPTIONS_LIBRARY_RELEASE}) target_link_libraries(${EXECUTABLE} solidity) install( TARGETS ${EXECUTABLE} DESTINATION bin ) diff --git a/solc/CommandLineInterface.cpp b/solc/CommandLineInterface.cpp new file mode 100644 index 000000000..6ace332f7 --- /dev/null +++ b/solc/CommandLineInterface.cpp @@ -0,0 +1,383 @@ +/* + This file is part of cpp-ethereum. + + cpp-ethereum is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + cpp-ethereum is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with cpp-ethereum. If not, see . +*/ +/** + * @author Lefteris + * @date 2014 + * Solidity command line interface. + */ +#include "CommandLineInterface.h" + +#include +#include +#include + +#include + +#include "BuildInfo.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace std; +namespace po = boost::program_options; + +namespace dev +{ +namespace solidity +{ + +static void version() +{ + cout << "solc, the solidity complier commandline interface " << dev::Version << endl + << " by Christian and Lefteris , (c) 2014." << endl + << "Build: " << DEV_QUOTED(ETH_BUILD_PLATFORM) << "/" << DEV_QUOTED(ETH_BUILD_TYPE) << endl; + exit(0); +} + +static inline bool argToStdout(po::variables_map const& _args, const char* _name) +{ + return _args.count(_name) && _args[_name].as() != OutputType::FILE; +} + +static bool needStdout(po::variables_map const& _args) +{ + return argToStdout(_args, "abi") || argToStdout(_args, "natspec-user") || argToStdout(_args, "natspec-dev") || + argToStdout(_args, "asm") || argToStdout(_args, "opcodes") || argToStdout(_args, "binary"); +} + +static inline bool outputToFile(OutputType type) +{ + return type == OutputType::FILE || type == OutputType::BOTH; +} + +static inline bool outputToStdout(OutputType type) +{ + return type == OutputType::STDOUT || type == OutputType::BOTH; +} + +static std::istream& operator>>(std::istream& _in, OutputType& io_output) +{ + std::string token; + _in >> token; + if (token == "stdout") + io_output = OutputType::STDOUT; + else if (token == "file") + io_output = OutputType::FILE; + else if (token == "both") + io_output = OutputType::BOTH; + else + throw boost::program_options::invalid_option_value(token); + return _in; +} + +void CommandLineInterface::handleBinary(string const& _contract) +{ + auto choice = m_args["binary"].as(); + if (outputToStdout(choice)) + { + cout << "Binary: " << endl; + cout << toHex(m_compiler.getBytecode(_contract)) << endl; + } + + if (outputToFile(choice)) + { + ofstream outFile(_contract + ".binary"); + outFile << toHex(m_compiler.getBytecode(_contract)); + outFile.close(); + } +} + +void CommandLineInterface::handleOpcode(string const& _contract) +{ + // TODO: Figure out why the wrong operator << (from boost) is used here + auto choice = m_args["opcode"].as(); + if (outputToStdout(choice)) + { + cout << "Opcodes: " << endl; + dev::operator<<(cout, m_compiler.getBytecode(_contract)); + cout << endl; + } + + if (outputToFile(choice)) + { + ofstream outFile(_contract + ".opcode"); + dev::operator<<(outFile, m_compiler.getBytecode(_contract)); + outFile.close(); + } +} + +void CommandLineInterface::handleBytecode(string const& _contract) +{ + if (m_args.count("opcodes")) + handleOpcode(_contract); + if (m_args.count("binary")) + handleBinary(_contract); +} + +void CommandLineInterface::handleJson(DocumentationType _type, + string const& _contract) +{ + std::string argName; + std::string suffix; + std::string title; + switch(_type) + { + case DocumentationType::ABI_INTERFACE: + argName = "abi"; + suffix = ".abi"; + title = "Contract ABI"; + break; + case DocumentationType::NATSPEC_USER: + argName = "natspec-user"; + suffix = ".docuser"; + title = "User Documentation"; + break; + case DocumentationType::NATSPEC_DEV: + argName = "natspec-dev"; + suffix = ".docdev"; + title = "Developer Documentation"; + break; + default: + // should never happen + BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unknown documentation _type")); + } + + if (m_args.count(argName)) + { + auto choice = m_args[argName].as(); + if (outputToStdout(choice)) + { + cout << title << endl; + cout << m_compiler.getJsonDocumentation(_contract, _type); + } + + if (outputToFile(choice)) + { + ofstream outFile(_contract + suffix); + outFile << m_compiler.getJsonDocumentation(_contract, _type); + outFile.close(); + } + } +} + +bool CommandLineInterface::parseArguments(int argc, char** argv) +{ +#define OUTPUT_TYPE_STR "Legal values:\n" \ + "\tstdout: Print it to standard output\n" \ + "\tfile: Print it to a file with same name\n" \ + "\tboth: Print both to a file and the stdout\n" + // Declare the supported options. + po::options_description desc("Allowed options"); + desc.add_options() + ("help", "Show help message and exit") + ("version", "Show version and exit") + ("optimize", po::value()->default_value(false), "Optimize bytecode for size") + ("input-file", po::value>(), "input file") + ("ast", po::value(), + "Request to output the AST of the contract. " OUTPUT_TYPE_STR) + ("asm", po::value(), + "Request to output the EVM assembly of the contract. " OUTPUT_TYPE_STR) + ("opcodes", po::value(), + "Request to output the Opcodes of the contract. " OUTPUT_TYPE_STR) + ("binary", po::value(), + "Request to output the contract in binary (hexadecimal). " OUTPUT_TYPE_STR) + ("abi", po::value(), + "Request to output the contract's ABI interface. " OUTPUT_TYPE_STR) + ("natspec-user", po::value(), + "Request to output the contract's Natspec user documentation. " OUTPUT_TYPE_STR) + ("natspec-dev", po::value(), + "Request to output the contract's Natspec developer documentation. " OUTPUT_TYPE_STR); +#undef OUTPUT_TYPE_STR + + // All positional options should be interpreted as input files + po::positional_options_description p; + p.add("input-file", -1); + + // parse the compiler arguments + try + { + po::store(po::command_line_parser(argc, argv).options(desc).positional(p).allow_unregistered().run(), m_args); + } + catch (po::error const& exception) + { + cout << exception.what() << endl; + return false; + } + po::notify(m_args); + + if (m_args.count("help")) + { + cout << desc; + return false; + } + + if (m_args.count("version")) + { + version(); + return false; + } + + return true; +} + +bool CommandLineInterface::processInput() +{ + if (!m_args.count("input-file")) + { + string s; + while (!cin.eof()) + { + getline(cin, s); + m_sourceCodes[""].append(s); + } + } + else + for (string const& infile: m_args["input-file"].as>()) + { + auto path = boost::filesystem::path(infile); + if (!boost::filesystem::exists(path)) + { + cout << "Skipping non existant input file \"" << infile << "\"" << endl; + continue; + } + + if (!boost::filesystem::is_regular_file(path)) + { + cout << "\"" << infile << "\" is not a valid file. Skipping" << endl; + continue; + } + + m_sourceCodes[infile] = asString(dev::contents(infile)); + } + + try + { + for (auto const& sourceCode: m_sourceCodes) + m_compiler.addSource(sourceCode.first, sourceCode.second); + // TODO: Perhaps we should not compile unless requested + m_compiler.compile(m_args["optimize"].as()); + } + catch (ParserError const& exception) + { + SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Parser error", m_compiler); + return false; + } + catch (DeclarationError const& exception) + { + SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Declaration error", m_compiler); + return false; + } + catch (TypeError const& exception) + { + SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Type error", m_compiler); + return false; + } + catch (CompilerError const& exception) + { + SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Compiler error", m_compiler); + return false; + } + catch (InternalCompilerError const& exception) + { + SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Internal compiler error", m_compiler); + return false; + } + catch (Exception const& exception) + { + cerr << "Exception during compilation: " << boost::diagnostic_information(exception) << endl; + return false; + } + catch (...) + { + cerr << "Unknown exception during compilation." << endl; + return false; + } + + return true; +} + +void CommandLineInterface::actOnInput() +{ + // do we need AST output? + if (m_args.count("ast")) + { + auto choice = m_args["ast"].as(); + if (outputToStdout(choice)) + { + cout << "Syntax trees:" << endl << endl; + for (auto const& sourceCode: m_sourceCodes) + { + cout << endl << "======= " << sourceCode.first << " =======" << endl; + ASTPrinter printer(m_compiler.getAST(sourceCode.first), sourceCode.second); + printer.print(cout); + } + } + + if (outputToFile(choice)) + { + for (auto const& sourceCode: m_sourceCodes) + { + boost::filesystem::path p(sourceCode.first); + ofstream outFile(p.stem().string() + ".ast"); + ASTPrinter printer(m_compiler.getAST(sourceCode.first), sourceCode.second); + printer.print(outFile); + outFile.close(); + } + } + } + + vector contracts = m_compiler.getContractNames(); + for (string const& contract: contracts) + { + if (needStdout(m_args)) + cout << endl << "======= " << contract << " =======" << endl; + + // do we need EVM assembly? + if (m_args.count("asm")) + { + auto choice = m_args["asm"].as(); + if (outputToStdout(choice)) + { + cout << "EVM assembly:" << endl; + m_compiler.streamAssembly(cout, contract); + } + + if (outputToFile(choice)) + { + ofstream outFile(contract + ".evm"); + m_compiler.streamAssembly(outFile, contract); + outFile.close(); + } + } + + handleBytecode(contract); + handleJson(DocumentationType::ABI_INTERFACE, contract); + handleJson(DocumentationType::NATSPEC_DEV, contract); + handleJson(DocumentationType::NATSPEC_USER, contract); + } // end of contracts iteration +} + +} +} diff --git a/solc/CommandLineInterface.h b/solc/CommandLineInterface.h new file mode 100644 index 000000000..7e3ad2502 --- /dev/null +++ b/solc/CommandLineInterface.h @@ -0,0 +1,71 @@ +/* + This file is part of cpp-ethereum. + + cpp-ethereum is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + cpp-ethereum is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with cpp-ethereum. If not, see . +*/ +/** + * @author Lefteris + * @date 2014 + * Solidity command line interface. + */ +#pragma once + +#include + +#include + +namespace dev +{ +namespace solidity +{ + +//forward declaration +enum class DocumentationType: uint8_t; + +enum class OutputType: uint8_t +{ + STDOUT, + FILE, + BOTH +}; + +class CommandLineInterface +{ +public: + CommandLineInterface() {} + + /// Parse command line arguments and return false if we should not continue + bool parseArguments(int argc, char** argv); + /// Parse the files and create source code objects + bool processInput(); + /// Perform actions on the input depending on provided compiler arguments + void actOnInput(); + +private: + void handleBinary(std::string const& _contract); + void handleOpcode(std::string const& _contract); + void handleBytecode(std::string const& _contract); + void handleJson(DocumentationType _type, + std::string const& _contract); + + /// Compiler arguments variable map + boost::program_options::variables_map m_args; + /// map of input files to source code strings + std::map m_sourceCodes; + /// Solidity compiler stack + dev::solidity::CompilerStack m_compiler; +}; + +} +} diff --git a/solc/main.cpp b/solc/main.cpp index 04fdc0ee1..c5f72980d 100644 --- a/solc/main.cpp +++ b/solc/main.cpp @@ -20,131 +20,16 @@ * Solidity commandline compiler. */ -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace std; -using namespace dev; -using namespace solidity; - -void help() -{ - cout << "Usage solc [OPTIONS] " << endl - << "Options:" << endl - << " -o,--optimize Optimize the bytecode for size." << endl - << " -h,--help Show this help message and exit." << endl - << " -V,--version Show the version and exit." << endl; - exit(0); -} - -void version() -{ - cout << "solc, the solidity complier commandline interface " << dev::Version << endl - << " by Christian , (c) 2014." << endl - << "Build: " << DEV_QUOTED(ETH_BUILD_PLATFORM) << "/" << DEV_QUOTED(ETH_BUILD_TYPE) << endl; - exit(0); -} +#include "CommandLineInterface.h" int main(int argc, char** argv) { - string infile; - bool optimize = false; - for (int i = 1; i < argc; ++i) - { - string arg = argv[i]; - if (arg == "-o" || arg == "--optimize") - optimize = true; - else if (arg == "-h" || arg == "--help") - help(); - else if (arg == "-V" || arg == "--version") - version(); - else - infile = argv[i]; - } - string sourceCode; - if (infile.empty()) - { - string s; - while (!cin.eof()) - { - getline(cin, s); - sourceCode.append(s); - } - } - else - sourceCode = asString(dev::contents(infile)); - - ASTPointer ast; - shared_ptr scanner = make_shared(CharStream(sourceCode)); - Parser parser; - bytes instructions; - Compiler compiler; - try - { - ast = parser.parse(scanner); - - NameAndTypeResolver resolver; - resolver.resolveNamesAndTypes(*ast.get()); - - cout << "Syntax tree for the contract:" << endl; - dev::solidity::ASTPrinter printer(ast, sourceCode); - printer.print(cout); - - compiler.compileContract(*ast); - instructions = compiler.getAssembledBytecode(optimize); - } - catch (ParserError const& exception) - { - SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Parser error", *scanner); - return -1; - } - catch (DeclarationError const& exception) - { - SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Declaration error", *scanner); - return -1; - } - catch (TypeError const& exception) - { - SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Type error", *scanner); - return -1; - } - catch (CompilerError const& exception) - { - SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Compiler error", *scanner); - return -1; - } - catch (InternalCompilerError const& exception) - { - cerr << "Internal compiler error: " << boost::diagnostic_information(exception) << endl; - return -1; - } - catch (Exception const& exception) - { - cerr << "Exception during compilation: " << boost::diagnostic_information(exception) << endl; - return -1; - } - catch (...) - { - cerr << "Unknown exception during compilation." << endl; - return -1; - } - - cout << "EVM assembly:" << endl; - compiler.streamAssembly(cout); - cout << "Opcodes:" << endl; - cout << eth::disassemble(instructions) << endl; - cout << "Binary: " << toHex(instructions) << endl; + dev::solidity::CommandLineInterface cli; + if (!cli.parseArguments(argc, argv)) + return 1; + if (!cli.processInput()) + return 1; + cli.actOnInput(); return 0; } diff --git a/stdserv.js b/stdserv.js index 55ae90d86..676aaa949 100644 --- a/stdserv.js +++ b/stdserv.js @@ -1,67 +1,41 @@ -eth = web3.eth; - -env.note('Creating Config...') -var configCode = eth.lll(" -{ - [[69]] (caller) - (returnlll { - (when (&& (= (calldatasize) 64) (= (caller) @@69)) - (for {} (< @i (calldatasize)) [i](+ @i 64) - [[ (calldataload @i) ]] (calldataload (+ @i 32)) - ) - ) - (return @@ $0) - }) -} -") -env.note('Config code: ' + configCode) -var config; -eth.transact({ 'code': configCode }, function(a) { config = a; }); - -env.note('Config at address ' + config) - -var nameRegCode = eth.lll(" -{ - [[(address)]] 'NameReg - [['NameReg]] (address) - [[config]] 'Config - [['Config]] config - [[69]] (caller) - (returnlll { - (when (= $0 'register) { - (when @@ $32 (stop)) - (when @@(caller) [[@@(caller)]] 0) - [[$32]] (caller) - [[(caller)]] $32 - (stop) - }) - (when (&& (= $0 'unregister) @@(caller)) { - [[@@(caller)]] 0 - [[(caller)]] 0 - (stop) - }) - (when (&& (= $0 'kill) (= (caller) @@69)) (suicide (caller))) - (return @@ $0) - }) -} -"); -env.note('NameReg code: ' + nameRegCode) - -var nameReg; - -env.note('Create NameReg...') -eth.transact({ 'code': nameRegCode }, function(a) { nameReg = a; }); - -env.note('Register NameReg...') -eth.transact({ 'to': config, 'data': ['0', nameReg] }); - +var compile = function(name) { return web3.eth.lll(env.contents("../../dapp-bin/" + name + "/" + name + ".lll")); }; +var create = function(code) { return web3.eth.transact({ 'code': code }); }; +var send = function(from, val, to) { return web3.eth.transact({ 'from': from, 'value': val, 'to': to }); }; +var initService = function(name, index, dep) { return dep.then(function(){ var ret = compile(name).then(create); register(ret, index); return ret; }); }; + +var config = compile("config").then(create); +var register = function(address, index) { return web3.eth.transact({ 'to': config, 'gas': '10000', 'data': [index + '', address] }); }; +var nameReg = initService("namereg", 0, config); +var regName = function(account, name) { return web3.eth.transact({ 'from': account, 'to': nameReg, 'gas': '10000', 'data': [ web3.fromAscii('register'), web3.fromAscii(name) ] }); }; +var coins = initService("coins", 1, nameReg); +var coin = initService("coin", 2, coins); +var approve = function(account, approvedAddress) { web3.eth.transact({ 'from': account, 'to': coin, 'gas': '10000', 'data': [ web3.fromAscii('approve'), approvedAddress ] }); }; +var exchange = initService("exchange", 3, coin); +var offer = function(account, haveCoin, haveVal, wantCoin, wantVal) { web3.eth.transact({ 'from': account, 'to': exchange, 'gas': '10000', 'data': [web3.fromAscii('new'), haveCoin, haveVal, wantCoin, wantVal] }); }; + +config.then(function() { + web3.eth.accounts.then(function(accounts) + { + var funded = send(accounts[0], '100000000000000000000', accounts[1]); + funded.then(function(){ regName(accounts[1], 'Gav Would'); approve(accounts[1], exchange); }); + regName(accounts[0], 'Gav'); + approve(accounts[0], exchange).then(function(){ offer(accounts[0], coin, '5000', '0', '5000000000000000000'); }); + + // TODO: once we have a new implementation of DNSReg. + // env.note('Register gav.eth...') + // eth.transact({ 'to': dnsReg, 'data': [web3.fromAscii('register'), web3.fromAscii('gav'), web3.fromAscii('opensecrecy.com')] }); + }); +}); + +// TODO +/* var nameRegJeff; env.note('Create NameRegJeff...') eth.transact({ 'code': nameRegCode }, function(a) { nameRegJeff = a; }); env.note('Register NameRegJeff...') -eth.transact({ 'to': config, 'data': ['4', nameReg] }); +eth.transact({ 'to': config, 'data': ['4', nameRegJeff] }); var dnsRegCode = '0x60006000546000600053602001546000600053604001546020604060206020600073661005d2720d855f1d9976f88bb10c1a3398c77f6103e8f17f7265676973746572000000000000000000000000000000000000000000000000600053606001600060200201547f446e735265670000000000000000000000000000000000000000000000000000600053606001600160200201546000600060006000604060606000600053604001536103e8f1327f6f776e65720000000000000000000000000000000000000000000000000000005761011663000000e46000396101166000f20060006000547f72656769737465720000000000000000000000000000000000000000000000006000602002350e0f630000006d596000600160200235560e0f630000006c59600032560e0f0f6300000057596000325657600260200235600160200235576001602002353257007f64657265676973746572000000000000000000000000000000000000000000006000602002350e0f63000000b95960016020023532560e0f63000000b959600032576000600160200235577f6b696c6c000000000000000000000000000000000000000000000000000000006000602002350e0f630000011559327f6f776e6572000000000000000000000000000000000000000000000000000000560e0f63000001155932ff00'; @@ -73,240 +47,6 @@ env.note('DnsReg at address ' + dnsReg) env.note('Register DnsReg...') eth.transact({ 'to': config, 'data': ['4', dnsReg] }); - -var coinRegCode = eth.lll(" -{ -(regname 'CoinReg) -(returnlll { - (def 'name $0) - (def 'denom $32) - (def 'address (caller)) - (when (|| (& 0xffffffffffffffffffffffffff name) @@name) (stop)) - (set 'n (+ @@0 1)) - [[0]] @n - [[@n]] name - [[name]] address - [[(sha3 name)]] denom -}) -} -"); - -var coinReg; -env.note('Create CoinReg...') -eth.transact({ 'code': coinRegCode }, function(a) { coinReg = a; }); - -env.note('Register CoinReg...') -eth.transact({ 'to': config, 'data': ['1', coinReg] }); - -var gavCoinCode = eth.lll(" -{ -[[ (caller) ]] 0x1000000 -[[ 0x69 ]] (caller) -[[ 0x42 ]] (number) - -(regname 'GavCoin) -(regcoin 'GAV 1000) - -(returnlll { - (when (&& (= $0 'kill) (= (caller) @@0x69)) (suicide (caller))) - (when (= $0 'balance) (return @@$32)) - (when (= $0 'approved) (return @@ (sha3pair (if (= (calldatasize) 64) (caller) $64) $32)) ) - - (when (= $0 'approve) { - [[(sha3pair (caller) $32)]] $32 - (stop) - }) - - (when (= $0 'send) { - (set 'fromVar (if (= (calldatasize) 96) - (caller) - { - (when (! @@ (sha3pair (origin) (caller))) (return 0)) - (origin) - } - )) - (def 'to $32) - (def 'value $64) - (def 'from (get 'fromVar)) - (set 'fromBal @@from) - (when (< @fromBal value) (return 0)) - [[ from ]]: (- @fromBal value) - [[ to ]]: (+ @@to value) - (return 1) - }) - - (set 'n @@0x42) - (when (&& (|| (= $0 'mine) (! (calldatasize))) (> (number) @n)) { - (set 'b (- (number) @n)) - [[(coinbase)]] (+ @@(coinbase) (* 1000 @b)) - [[(caller)]] (+ @@(caller) (* 1000 @b)) - [[0x42]] (number) - (return @b) - }) - - (return @@ $0) -}) -} -"); - -var gavCoin; -env.note('Create GavCoin...') -eth.transact({ 'code': gavCoinCode }, function(a) { gavCoin = a; }); - -env.note('Register GavCoin...') -eth.transact({ 'to': config, 'data': ['2', gavCoin] }); - - -var exchangeCode = eth.lll(" -{ -(regname 'Exchange) - -(def 'min (a b) (if (< a b) a b)) - -(def 'head (_list) @@ _list) -(def 'next (_item) @@ _item) -(def 'inc (itemref) [itemref]: (next @itemref)) -(def 'rateof (_item) @@ (+ _item 1)) -(def 'idof (_item) @@ (+ _item 2)) -(def 'wantof (_item) @@ (+ _item 3)) -(def 'newitem (rate who want list) { - (set 'pos (sha3trip rate who list)) - [[ (+ @pos 1) ]] rate - [[ (+ @pos 2) ]] who - [[ (+ @pos 3) ]] want - @pos -}) -(def 'stitchitem (parent pos) { - [[ pos ]] @@ parent - [[ parent ]] pos -}) -(def 'addwant (_item amount) [[ (+ _item 3) ]] (+ @@ (+ _item 3) amount)) -(def 'deductwant (_item amount) [[ (+ _item 3) ]] (- @@ (+ _item 3) amount)) - -(def 'xfer (contract to amount) - (if contract { - [0] 'send - [32] to - [64] amount - (msg allgas contract 0 0 96) - } - (send to amount) - ) -) - -(def 'fpdiv (a b) (/ (+ (/ b 2) (* a (exp 2 128))) b)) -(def 'fpmul (a b) (/ (* a b) (exp 2 128)) ) - -(returnlll { - (when (= $0 'new) { - (set 'offer $32) - (set 'xoffer (if @offer $64 (callvalue))) - (set 'want $96) - (set 'xwant $128) - (set 'rate (fpdiv @xoffer @xwant)) - (set 'irate (fpdiv @xwant @xoffer)) - - (unless (&& @rate @irate @xoffer @xwant) (stop)) - - (when @offer { - (set 'arg1 'send) - (set 'arg2 (address)) - (set 'arg3 @xoffer) - (set 'arg4 (caller)) - (unless (msg allgas @offer 0 arg1 128) (stop)) - }) - (set 'list (sha3pair @offer @want)) - (set 'ilist (sha3pair @want @offer)) - - (set 'last @ilist) - (set 'item @@ @last) - - (for {} (&& @item (>= (rateof @item) @irate)) {} { - (set 'offerA (min @xoffer (wantof @item))) - (set 'wantA (fpmul @offerA (rateof @item))) - - (set 'xoffer (- @xoffer @offerA)) - (set 'xwant (- @xwant @wantA)) - - (deductwant @item @offerA) - - (xfer @offer (idof @item) @offerA) - (xfer @want (caller) @wantA) - - (unless @xoffer (stop)) - - (set 'item @@ @item) - [[ @last ]] @item - }) - - (set 'last @list) - (set 'item @@ @last) - - (set 'newpos (newitem @rate (caller) @xwant @list)) - - (for {} (&& @item (!= @item @newpos) (>= (rateof @item) @rate)) { (set 'last @item) (inc item) } {}) - (if (= @item @newpos) - (addwant @item @wantx) - (stitchitem @last @newpos) - ) - (stop) - }) - (when (= $0 'delete) { - (set 'offer $32) - (set 'want $64) - (set 'rate $96) - (set 'list (sha3pair @offer @want)) - (set 'last @list) - (set 'item @@ @last) - (for {} (&& @item (!= (idof @item) (caller)) (!= (rateof @item) @rate)) { (set 'last @item) (inc item) } {}) - (when @item { - (set 'xoffer (fpmul (wantof @item) (rateof @item))) - [[ @last ]] @@ @item - (xfer @offer (caller) @xoffer) - }) - (stop) - }) - (when (= $0 'price) { - (set 'offer $32) - (set 'want $96) - (set 'item (head (sha3pair @offer @want))) - (return (if @item (rateof @list) 0)) - }) -}) -} -"); - -var exchange; -env.note('Create Exchange...') -eth.transact({ 'code': exchangeCode }, function(a) { exchange = a; }); - -env.note('Register Exchange...') -eth.transact({ 'to': config, 'data': ['3', exchange] }); - - - - -env.note('Register my name...') -eth.transact({ 'to': nameReg, 'data': [ web3.fromAscii('register'), web3.fromAscii('Gav') ] }); - -env.note('Dole out ETH to other address...') -eth.transact({ 'value': '100000000000000000000', 'to': eth.accounts[1] }); - -env.note('Register my other name...') -eth.transact({ 'from': eth.keys[1], 'to': nameReg, 'data': [ web3.fromAscii('register'), web3.fromAscii("Gav Would") ] }); - -env.note('Approve Exchange...') -eth.transact({ 'to': gavCoin, 'data': [ web3.fromAscii('approve'), exchange ] }); - -env.note('Approve Exchange on other address...') -eth.transact({ 'from': eth.keys[1], 'to': gavCoin, 'data': [ web3.fromAscii('approve'), exchange ] }); - -env.note('Make offer 5000GAV/5ETH...') -eth.transact({ 'to': exchange, 'data': [web3.fromAscii('new'), gavCoin, '5000', '0', '5000000000000000000'] }); - -env.note('Register gav.eth...') -eth.transact({ 'to': dnsReg, 'data': [web3.fromAscii('register'), web3.fromAscii('gav'), web3.fromAscii('opensecrecy.com')] }); - -env.note('All done.') +*/ // env.load('/home/gav/Eth/cpp-ethereum/stdserv.js') diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index f292361d5..7e618f7ea 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -3,45 +3,28 @@ cmake_policy(SET CMP0015 NEW) aux_source_directory(. SRC_LIST) list(REMOVE_ITEM SRC_LIST "./createRandomTest.cpp") +include_directories(${CRYPTOPP_INCLUDE_DIRS}) +include_directories(${JSONCPP_INCLUDE_DIRS}) +include_directories(${JSON_RPC_CPP_INCLUDE_DIRS}) include_directories(..) file(GLOB HEADERS "*.h") add_executable(testeth ${SRC_LIST} ${HEADERS}) add_executable(createRandomTest createRandomTest.cpp vm.cpp TestHelper.cpp) +target_link_libraries(testeth ${Boost_UNIT_TEST_FRAMEWORK_LIBRARY_RELEASE}) +target_link_libraries(testeth ${CURL_LIBRARIES}) target_link_libraries(testeth ethereum) target_link_libraries(testeth ethcore) target_link_libraries(testeth secp256k1) -target_link_libraries(testeth gmp) target_link_libraries(testeth solidity) -target_link_libraries(testeth ${CRYPTOPP_LS}) target_link_libraries(testeth webthree) -if(JSONRPC_LS) -target_link_libraries(testeth web3jsonrpc) + +if (JSONRPC) + target_link_libraries(testeth web3jsonrpc) + target_link_libraries(testeth ${JSON_RPC_CPP_CLIENT_LIBRARIES}) endif() +target_link_libraries(createRandomTest ${Boost_UNIT_TEST_FRAMEWORK_LIBRARY_RELEASE}) target_link_libraries(createRandomTest ethereum) target_link_libraries(createRandomTest ethcore) -target_link_libraries(createRandomTest boost_chrono) -target_link_libraries(createRandomTest boost_unit_test_framework) - -if ("${TARGET_PLATFORM}" STREQUAL "w64") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -static-libgcc -static-libstdc++") - target_link_libraries(testeth boost_system-mt-s) - target_link_libraries(testeth boost_filesystem-mt-s) - target_link_libraries(testeth boost_thread_win32-mt-s) - target_link_libraries(testeth gcc) - target_link_libraries(testeth gdi32) - target_link_libraries(testeth ws2_32) - target_link_libraries(testeth mswsock) - target_link_libraries(testeth shlwapi) - target_link_libraries(testeth iphlpapi) - set(CMAKE_SHARED_LIBRARY_LINK_CXX_FLAGS) -elseif (UNIX) - find_package(Boost 1.53 REQUIRED COMPONENTS unit_test_framework) -else () - target_link_libraries(testeth boost_system) - target_link_libraries(testeth boost_filesystem) - find_package(Threads REQUIRED) - target_link_libraries(testeth ${CMAKE_THREAD_LIBS_INIT}) -endif () diff --git a/test/TestHelper.cpp b/test/TestHelper.cpp index 1b13f9e82..0c1ee290f 100644 --- a/test/TestHelper.cpp +++ b/test/TestHelper.cpp @@ -72,6 +72,7 @@ ImportTest::ImportTest(json_spirit::mObject& _o, bool isFiller): m_TestObject(_o if (!isFiller) { importState(_o["post"].get_obj(), m_statePost); + m_environment.sub.logs = importLog(_o["logs"].get_array()); } } @@ -108,9 +109,6 @@ void ImportTest::importState(json_spirit::mObject& _o, State& _state) Address address = Address(i.first); - for (auto const& j: o["storage"].get_obj()) - _state.setStorage(address, toInt(j.first), toInt(j.second)); - bytes code = importCode(o); if (code.size()) @@ -121,6 +119,9 @@ void ImportTest::importState(json_spirit::mObject& _o, State& _state) else _state.m_cache[address] = Account(toInt(o["balance"]), Account::NormalCreation); + for (auto const& j: o["storage"].get_obj()) + _state.setStorage(address, toInt(j.first), toInt(j.second)); + for(int i=0; i 0); + assert(o.count("topics") > 0); + assert(o.count("data") > 0); + assert(o.count("bloom") > 0); + LogEntry log; + log.address = Address(o["address"].get_str()); + for (auto const& t: o["topics"].get_array()) + log.topics.push_back(h256(t.get_str())); + log.data = importData(o); + logEntries.push_back(log); + } + return logEntries; +} + +json_spirit::mArray exportLog(eth::LogEntries _logs) +{ + json_spirit::mArray ret; + if (_logs.size() == 0) return ret; + for (LogEntry const& l: _logs) + { + json_spirit::mObject o; + o["address"] = toString(l.address); + json_spirit::mArray topics; + for (auto const& t: l.topics) + topics.push_back(toString(t)); + o["topics"] = topics; + o["data"] = "0x" + toHex(l.data); + o["bloom"] = toString(l.bloom()); + ret.push_back(o); + } + return ret; +} + void checkOutput(bytes const& _output, json_spirit::mObject& _o) { int j = 0; @@ -285,6 +329,24 @@ void checkStorage(map _expectedStore, map _resultStore, BOOST_CHECK_MESSAGE(expectedStoreValue == resultStoreValue, _expectedAddr << ": store[" << expectedStoreKey << "] = " << resultStoreValue << ", expected " << expectedStoreValue); } } + BOOST_CHECK_EQUAL(_resultStore.size(), _expectedStore.size()); +#ifndef __WIN32__ + for (auto&& resultStorePair : _resultStore) + if (!_expectedStore.count(resultStorePair.first)) + BOOST_ERROR(_expectedAddr << ": unexpected store key " << resultStorePair.first); +#endif +} + +void checkLog(LogEntries _resultLogs, LogEntries _expectedLogs) +{ + BOOST_REQUIRE_EQUAL(_resultLogs.size(), _expectedLogs.size()); + + for (size_t i = 0; i < _resultLogs.size(); ++i) + { + BOOST_CHECK_EQUAL(_resultLogs[i].address, _expectedLogs[i].address); + BOOST_CHECK_EQUAL(_resultLogs[i].topics, _expectedLogs[i].topics); + BOOST_CHECK(_resultLogs[i].data == _expectedLogs[i].data); + } } std::string getTestPath() @@ -310,12 +372,13 @@ void userDefinedTest(string testTypeFlag, std::function= boost::unit_test::framework::master_test_suite().argc) + if (boost::unit_test::framework::master_test_suite().argc <= i + 2) { - cnote << "Missing filename\nUsage: testeth " << testTypeFlag << " \n"; + cnote << "Missing filename\nUsage: testeth " << testTypeFlag << " \n"; return; } string filename = boost::unit_test::framework::master_test_suite().argv[i + 1]; + string testname = boost::unit_test::framework::master_test_suite().argv[i + 2]; int currentVerbosity = g_logVerbosity; g_logVerbosity = 12; try @@ -325,7 +388,19 @@ void userDefinedTest(string testTypeFlag, std::function 0, "Contents of " + filename + " is empty. "); json_spirit::read_string(s, v); - doTests(v, false); + json_spirit::mObject oSingleTest; + + json_spirit::mObject::const_iterator pos = v.get_obj().find(testname); + if (pos == v.get_obj().end()) + { + cnote << "Could not find test: " << testname << " in " << filename << "\n"; + return; + } + else + oSingleTest[pos->first] = pos->second; + + json_spirit::mValue v_singleTest(oSingleTest); + doTests(v_singleTest, false); } catch (Exception const& _e) { @@ -374,6 +449,7 @@ void executeTests(const string& _name, const string& _testPathAppendix, std::fun { BOOST_ERROR("Failed test with Exception: " << _e.what()); } + break; } } diff --git a/test/TestHelper.h b/test/TestHelper.h index ef67d52fb..3203eae83 100644 --- a/test/TestHelper.h +++ b/test/TestHelper.h @@ -25,6 +25,7 @@ #include #include "JsonSpiritHeaders.h" #include +#include namespace dev { @@ -67,8 +68,11 @@ u256 toInt(json_spirit::mValue const& _v); byte toByte(json_spirit::mValue const& _v); bytes importCode(json_spirit::mObject& _o); bytes importData(json_spirit::mObject& _o); +eth::LogEntries importLog(json_spirit::mArray& _o); +json_spirit::mArray exportLog(eth::LogEntries _logs); void checkOutput(bytes const& _output, json_spirit::mObject& _o); void checkStorage(std::map _expectedStore, std::map _resultStore, Address _expectedAddr); +void checkLog(eth::LogEntries _resultLogs, eth::LogEntries _expectedLogs); void executeTests(const std::string& _name, const std::string& _testPathAppendix, std::function doTests); std::string getTestPath(); void userDefinedTest(std::string testTypeFlag, std::function doTests); diff --git a/test/TestHelperCrypto.h b/test/TestHelperCrypto.h deleted file mode 100644 index 01e97c21f..000000000 --- a/test/TestHelperCrypto.h +++ /dev/null @@ -1,51 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - cpp-ethereum is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with cpp-ethereum. If not, see . - */ -/** @file TestHelperCrypto.h - * @author Alex Leverington - * @date 2014 - */ - -#pragma once - -#include - -using namespace std; -using namespace CryptoPP; - -void SavePrivateKey(const PrivateKey& key, const string& file = "ecies.private.key") -{ - FileSink sink(file.c_str()); - key.Save(sink); -} - -void SavePublicKey(const PublicKey& key, const string& file = "ecies.public.key") -{ - FileSink sink(file.c_str()); - key.Save(sink); -} - -void LoadPrivateKey(PrivateKey& key, const string& file = "ecies.private.key") -{ - FileSource source(file.c_str(), true); - key.Load(source); -} - -void LoadPublicKey(PublicKey& key, const string& file = "ecies.public.key") -{ - FileSource source(file.c_str(), true); - key.Load(source); -} diff --git a/test/createRandomTest.cpp b/test/createRandomTest.cpp index 60a2039c8..a11688457 100644 --- a/test/createRandomTest.cpp +++ b/test/createRandomTest.cpp @@ -32,7 +32,7 @@ #include #include #include -#include +#include #include "vm.h" using namespace std; @@ -121,14 +121,14 @@ void doMyTests(json_spirit::mValue& v) { for (auto& i: v.get_obj()) { + cnote << i.first; mObject& o = i.second.get_obj(); assert(o.count("env") > 0); assert(o.count("pre") > 0); assert(o.count("exec") > 0); - eth::VM vm; - test::FakeExtVM fev; + dev::test::FakeExtVM fev; fev.importEnv(o["env"].get_obj()); fev.importState(o["pre"].get_obj()); @@ -141,17 +141,20 @@ void doMyTests(json_spirit::mValue& v) fev.code = fev.thisTxCode; } - vm.reset(fev.gas); bytes output; + auto vm = eth::VMFactory::create(fev.gas); + u256 gas; + bool vmExceptionOccured = false; try { - output = vm.go(fev).toBytes(); + output = vm->go(fev, fev.simpleTrace()).toBytes(); + gas = vm->gas(); } catch (eth::VMException const& _e) { cnote << "VM did throw an exception: " << diagnostic_information(_e); - gas = 0; + vmExceptionOccured = true; } catch (Exception const& _e) { @@ -180,9 +183,13 @@ void doMyTests(json_spirit::mValue& v) o["env"] = mValue(fev.exportEnv()); o["exec"] = mValue(fev.exportExec()); - o["post"] = mValue(fev.exportState()); - o["callcreates"] = fev.exportCallCreates(); - o["out"] = "0x" + toHex(output); - fev.push(o, "gas", gas); + if (!vmExceptionOccured) + { + o["post"] = mValue(fev.exportState()); + o["callcreates"] = fev.exportCallCreates(); + o["out"] = "0x" + toHex(output); + fev.push(o, "gas", gas); + o["logs"] = test::exportLog(fev.sub.logs); + } } } diff --git a/test/crypto.cpp b/test/crypto.cpp index 06e55658a..291893f59 100644 --- a/test/crypto.cpp +++ b/test/crypto.cpp @@ -27,9 +27,9 @@ #include #include #include -#include -#include -#include "TestHelperCrypto.h" +#include +#include +#include using namespace std; using namespace dev; @@ -38,9 +38,41 @@ using namespace CryptoPP; BOOST_AUTO_TEST_SUITE(devcrypto) +static Secp256k1 s_secp256k1; +static CryptoPP::AutoSeededRandomPool s_rng; +static CryptoPP::OID s_curveOID(CryptoPP::ASN1::secp256k1()); +static CryptoPP::DL_GroupParameters_EC s_params(s_curveOID); +static CryptoPP::DL_GroupParameters_EC::EllipticCurve s_curve(s_params.GetCurve()); + +BOOST_AUTO_TEST_CASE(emptySHA3Types) +{ + h256 emptyListSHA3(fromHex("1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347")); + BOOST_REQUIRE_EQUAL(emptyListSHA3, EmptyListSHA3); + + h256 emptySHA3(fromHex("c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470")); + BOOST_REQUIRE_EQUAL(emptySHA3, EmptySHA3); +} + +BOOST_AUTO_TEST_CASE(cryptopp_patch) +{ + KeyPair k = KeyPair::create(); + bytes io_text; + s_secp256k1.decrypt(k.sec(), io_text); + BOOST_REQUIRE_EQUAL(io_text.size(), 0); +} + +BOOST_AUTO_TEST_CASE(verify_secert) +{ + h256 empty; + KeyPair kNot(empty); + BOOST_REQUIRE(!kNot.address()); + KeyPair k(sha3(empty)); + BOOST_REQUIRE(k.address()); +} + BOOST_AUTO_TEST_CASE(common_encrypt_decrypt) { - string message("Now is the time for all good persons to come to the aide of humanity."); + string message("Now is the time for all good persons to come to the aid of humanity."); bytes m = asBytes(message); bytesConstRef bcr(&m); @@ -56,103 +88,50 @@ BOOST_AUTO_TEST_CASE(common_encrypt_decrypt) BOOST_REQUIRE(plain == asBytes(message)); } -BOOST_AUTO_TEST_CASE(cryptopp_vs_secp256k1) -{ - ECIES::Decryptor d(pp::PRNG, pp::secp256k1Curve); - ECIES::Encryptor e(d.GetKey()); - - Secret s; - pp::exportPrivateKey(d.GetKey(), s); - - Public p; - pp::exportPublicKey(e.GetKey(), p); - - BOOST_REQUIRE(dev::toAddress(s) == right160(dev::sha3(p.ref()))); - - Secret previous = s; - for (auto i = 0; i < 2; i++) - { - ECIES::Decryptor d(pp::PRNG, pp::secp256k1Curve); - ECIES::Encryptor e(d.GetKey()); - - Secret s; - pp::exportPrivateKey(d.GetKey(), s); - BOOST_REQUIRE(s != previous); - - Public p; - pp::exportPublicKey(e.GetKey(), p); - - h160 secp256k1Addr = dev::toAddress(s); - h160 cryptoppAddr = right160(dev::sha3(p.ref())); - if (secp256k1Addr != cryptoppAddr) - { - BOOST_REQUIRE(secp256k1Addr == cryptoppAddr); - break; - } - } -} - BOOST_AUTO_TEST_CASE(cryptopp_cryptopp_secp256k1libport) { - // cryptopp implementation of secp256k1lib sign_compact w/recid parameter and recovery of public key from signature - + secp256k1_start(); + // base secret Secret secret(sha3("privacy")); // we get ec params from signer - const CryptoPP::DL_GroupParameters_EC params = pp::secp256k1Params; ECDSA::Signer signer; // e := sha3(msg) bytes e(fromHex("0x01")); e.resize(32); - int tests = 2; // Oct 29: successful @ 1500 + int tests = 2; while (sha3(&e, &e), secret = sha3(secret.asBytes()), tests--) { KeyPair key(secret); Public pkey = key.pub(); - pp::initializeDLScheme(secret, signer); + signer.AccessKey().Initialize(s_params, secretToExponent(secret)); h256 he(sha3(e)); Integer heInt(he.asBytes().data(), 32); h256 k(crypto::kdf(secret, he)); Integer kInt(k.asBytes().data(), 32); - kInt %= params.GetSubgroupOrder()-1; + kInt %= s_params.GetSubgroupOrder()-1; - ECP::Point rp = params.ExponentiateBase(kInt); - Integer const& q = params.GetGroupOrder(); - Integer r = params.ConvertElementToInteger(rp); - int recid = ((r >= q) ? 2 : 0) | (rp.y.IsOdd() ? 1 : 0); + ECP::Point rp = s_params.ExponentiateBase(kInt); + Integer const& q = s_params.GetGroupOrder(); + Integer r = s_params.ConvertElementToInteger(rp); Integer kInv = kInt.InverseMod(q); Integer s = (kInv * (Integer(secret.asBytes().data(), 32)*r + heInt)) % q; BOOST_REQUIRE(!!r && !!s); - -/* - // For future reference: - // According to maths, this codepath can't be reached, however, it's in secp256k1. - // Commenting this out diverges from codebase implementation. - // To be removed after upstream PR and proof are evaulated. - - if (s > params.GetSubgroupOrder()) - { - // note: this rarely happens - s = params.GetGroupOrder() - s; - if (recid) - recid ^= 1; - } - */ Signature sig; + sig[64] = rp.y.IsOdd() ? 1 : 0; r.Encode(sig.data(), 32); s.Encode(sig.data() + 32, 32); - sig[64] = recid; Public p = dev::recover(sig, he); BOOST_REQUIRE(p == pkey); // verify w/cryptopp - BOOST_REQUIRE(crypto::verify(pkey, sig, bytesConstRef(&e))); + BOOST_REQUIRE(s_secp256k1.verify(pkey, sig, bytesConstRef(&e))); // verify with secp256k1lib byte encpub[65] = {0x04}; @@ -166,16 +145,18 @@ BOOST_AUTO_TEST_CASE(cryptopp_cryptopp_secp256k1libport) BOOST_AUTO_TEST_CASE(cryptopp_ecdsa_sipaseckp256k1) { + secp256k1_start(); + // cryptopp integer encoding Integer nHex("f2ee15ea639b73fa3db9b34a245bdfa015c260c598b211bf05a1ecc4b3e3b4f2H"); Integer nB(fromHex("f2ee15ea639b73fa3db9b34a245bdfa015c260c598b211bf05a1ecc4b3e3b4f2").data(), 32); BOOST_REQUIRE(nHex == nB); - bytes sbytes(fromHex("0x01")); - Secret secret(sha3(sbytes)); // 5fe7f977e71dba2ea1a68e21057beebb9be2ac30c6410aa38d4f3fbe41dcffd2 + bytes sbytes(fromHex("0xFFFF")); + Secret secret(sha3(sbytes)); KeyPair key(secret); - bytes m(fromHex("0x01")); + bytes m(1, 0xff); int tests = 2; while (m[0]++, tests--) { @@ -183,45 +164,45 @@ BOOST_AUTO_TEST_CASE(cryptopp_ecdsa_sipaseckp256k1) Integer hInt(hm.asBytes().data(), 32); h256 k(hm ^ key.sec()); Integer kInt(k.asBytes().data(), 32); - + // raw sign w/cryptopp (doesn't pass through cryptopp hash filter) ECDSA::Signer signer; - pp::initializeDLScheme(key.sec(), signer); + signer.AccessKey().Initialize(s_params, secretToExponent(key.sec())); Integer r, s; signer.RawSign(kInt, hInt, r, s); // verify cryptopp raw-signature w/cryptopp ECDSA::Verifier verifier; - pp::initializeDLScheme(key.pub(), verifier); + verifier.AccessKey().Initialize(s_params, publicToPoint(key.pub())); Signature sigppraw; r.Encode(sigppraw.data(), 32); s.Encode(sigppraw.data() + 32, 32); BOOST_REQUIRE(verifier.VerifyMessage(m.data(), m.size(), sigppraw.data(), 64)); - BOOST_REQUIRE(crypto::verify(key.pub(), sigppraw, bytesConstRef(&m))); +// BOOST_REQUIRE(crypto::verify(key.pub(), sigppraw, bytesConstRef(&m))); BOOST_REQUIRE(dev::verify(key.pub(), sigppraw, hm)); // sign with cryptopp, verify, recover w/sec256lib Signature seclibsig(dev::sign(key.sec(), hm)); BOOST_REQUIRE(verifier.VerifyMessage(m.data(), m.size(), seclibsig.data(), 64)); - BOOST_REQUIRE(crypto::verify(key.pub(), seclibsig, bytesConstRef(&m))); +// BOOST_REQUIRE(crypto::verify(key.pub(), seclibsig, bytesConstRef(&m))); BOOST_REQUIRE(dev::verify(key.pub(), seclibsig, hm)); BOOST_REQUIRE(dev::recover(seclibsig, hm) == key.pub()); // sign with cryptopp (w/hash filter?), verify with cryptopp bytes sigppb(signer.MaxSignatureLength()); - size_t ssz = signer.SignMessage(pp::PRNG, m.data(), m.size(), sigppb.data()); + size_t ssz = signer.SignMessage(s_rng, m.data(), m.size(), sigppb.data()); Signature sigpp; memcpy(sigpp.data(), sigppb.data(), 64); BOOST_REQUIRE(verifier.VerifyMessage(m.data(), m.size(), sigppb.data(), ssz)); - BOOST_REQUIRE(crypto::verify(key.pub(), sigpp, bytesConstRef(&m))); +// BOOST_REQUIRE(crypto::verify(key.pub(), sigpp, bytesConstRef(&m))); BOOST_REQUIRE(dev::verify(key.pub(), sigpp, hm)); // sign with cryptopp and stringsource hash filter string sigstr; - StringSource ssrc(asString(m), true, new SignerFilter(pp::PRNG, signer, new StringSink(sigstr))); + StringSource ssrc(asString(m), true, new SignerFilter(s_rng, signer, new StringSink(sigstr))); FixedHash retsig((byte const*)sigstr.data(), Signature::ConstructFromPointer); BOOST_REQUIRE(verifier.VerifyMessage(m.data(), m.size(), retsig.data(), 64)); - BOOST_REQUIRE(crypto::verify(key.pub(), retsig, bytesConstRef(&m))); +// BOOST_REQUIRE(crypto::verify(key.pub(), retsig, bytesConstRef(&m))); BOOST_REQUIRE(dev::verify(key.pub(), retsig, hm)); /// verification w/sec256lib @@ -247,92 +228,102 @@ BOOST_AUTO_TEST_CASE(cryptopp_ecdsa_sipaseckp256k1) } } -BOOST_AUTO_TEST_CASE(cryptopp_public_export_import) -{ - ECIES::Decryptor d(pp::PRNG, pp::secp256k1Curve); - ECIES::Encryptor e(d.GetKey()); - - Secret s; - pp::exportPrivateKey(d.GetKey(), s); - Public p; - pp::exportPublicKey(e.GetKey(), p); - Address addr = right160(dev::sha3(p.ref())); - BOOST_REQUIRE(toAddress(s) == addr); - - KeyPair l(s); - BOOST_REQUIRE(l.address() == addr); -} - BOOST_AUTO_TEST_CASE(ecies_eckeypair) { KeyPair k = KeyPair::create(); - string message("Now is the time for all good persons to come to the aide of humanity."); + string message("Now is the time for all good persons to come to the aid of humanity."); string original = message; bytes b = asBytes(message); - encrypt(k.pub(), b); + s_secp256k1.encrypt(k.pub(), b); BOOST_REQUIRE(b != asBytes(original)); - decrypt(k.sec(), b); + s_secp256k1.decrypt(k.sec(), b); BOOST_REQUIRE(b == asBytes(original)); } -BOOST_AUTO_TEST_CASE(ecdhe_aes128_ctr_sha3mac) +BOOST_AUTO_TEST_CASE(ecdh) { - // New connections require new ECDH keypairs - // Every new connection requires a new EC keypair - // Every new trust requires a new EC keypair - // All connections should share seed for PRF (or PRNG) for nonces + cnote << "Testing ecdh..."; + + ECDH::Domain dhLocal(s_curveOID); + SecByteBlock privLocal(dhLocal.PrivateKeyLength()); + SecByteBlock pubLocal(dhLocal.PublicKeyLength()); + dhLocal.GenerateKeyPair(s_rng, privLocal, pubLocal); + + ECDH::Domain dhRemote(s_curveOID); + SecByteBlock privRemote(dhRemote.PrivateKeyLength()); + SecByteBlock pubRemote(dhRemote.PublicKeyLength()); + dhRemote.GenerateKeyPair(s_rng, privRemote, pubRemote); + + assert(dhLocal.AgreedValueLength() == dhRemote.AgreedValueLength()); + + // local: send public to remote; remote: send public to local + + // Local + SecByteBlock sharedLocal(dhLocal.AgreedValueLength()); + assert(dhLocal.Agree(sharedLocal, privLocal, pubRemote)); + + // Remote + SecByteBlock sharedRemote(dhRemote.AgreedValueLength()); + assert(dhRemote.Agree(sharedRemote, privRemote, pubLocal)); + + // Test + Integer ssLocal, ssRemote; + ssLocal.Decode(sharedLocal.BytePtr(), sharedLocal.SizeInBytes()); + ssRemote.Decode(sharedRemote.BytePtr(), sharedRemote.SizeInBytes()); + + assert(ssLocal != 0); + assert(ssLocal == ssRemote); + + + // Now use our keys + KeyPair a = KeyPair::create(); + byte puba[65] = {0x04}; + memcpy(&puba[1], a.pub().data(), 64); + KeyPair b = KeyPair::create(); + byte pubb[65] = {0x04}; + memcpy(&pubb[1], b.pub().data(), 64); + ECDH::Domain dhA(s_curveOID); + Secret shared; + BOOST_REQUIRE(dhA.Agree(shared.data(), a.sec().data(), pubb)); + BOOST_REQUIRE(shared); } -BOOST_AUTO_TEST_CASE(cryptopp_ecies_message) +BOOST_AUTO_TEST_CASE(ecdhe) { - cnote << "Testing cryptopp_ecies_message..."; - - string const message("Now is the time for all good persons to come to the aide of humanity."); - - ECIES::Decryptor localDecryptor(pp::PRNG, pp::secp256k1Curve); - SavePrivateKey(localDecryptor.GetPrivateKey()); + cnote << "Testing ecdhe..."; - ECIES::Encryptor localEncryptor(localDecryptor); - SavePublicKey(localEncryptor.GetPublicKey()); - - ECIES::Decryptor futureDecryptor; - LoadPrivateKey(futureDecryptor.AccessPrivateKey()); - futureDecryptor.GetPrivateKey().ThrowIfInvalid(pp::PRNG, 3); + ECDHE a, b; + BOOST_CHECK_NE(a.pubkey(), b.pubkey()); - ECIES::Encryptor futureEncryptor; - LoadPublicKey(futureEncryptor.AccessPublicKey()); - futureEncryptor.GetPublicKey().ThrowIfInvalid(pp::PRNG, 3); - - // encrypt/decrypt with local - string cipherLocal; - StringSource ss1 (message, true, new PK_EncryptorFilter(pp::PRNG, localEncryptor, new StringSink(cipherLocal) ) ); - string plainLocal; - StringSource ss2 (cipherLocal, true, new PK_DecryptorFilter(pp::PRNG, localDecryptor, new StringSink(plainLocal) ) ); - - // encrypt/decrypt with future - string cipherFuture; - StringSource ss3 (message, true, new PK_EncryptorFilter(pp::PRNG, futureEncryptor, new StringSink(cipherFuture) ) ); - string plainFuture; - StringSource ss4 (cipherFuture, true, new PK_DecryptorFilter(pp::PRNG, futureDecryptor, new StringSink(plainFuture) ) ); + ECDHE local; + ECDHE remote; - // decrypt local w/future - string plainFutureFromLocal; - StringSource ss5 (cipherLocal, true, new PK_DecryptorFilter(pp::PRNG, futureDecryptor, new StringSink(plainFutureFromLocal) ) ); + // local tx pubkey -> remote + Secret sremote; + remote.agree(local.pubkey(), sremote); - // decrypt future w/local - string plainLocalFromFuture; - StringSource ss6 (cipherFuture, true, new PK_DecryptorFilter(pp::PRNG, localDecryptor, new StringSink(plainLocalFromFuture) ) ); + // remote tx pbukey -> local + Secret slocal; + local.agree(remote.pubkey(), slocal); + + BOOST_REQUIRE(sremote); + BOOST_REQUIRE(slocal); + BOOST_REQUIRE_EQUAL(sremote, slocal); +} + +BOOST_AUTO_TEST_CASE(ecdhe_aes128_ctr_sha3mac) +{ + // New connections require new ECDH keypairs + // Every new connection requires a new EC keypair + // Every new trust requires a new EC keypair + // All connections should share seed for PRF (or PRNG) for nonces - BOOST_REQUIRE(plainLocal == message); - BOOST_REQUIRE(plainFuture == plainLocal); - BOOST_REQUIRE(plainFutureFromLocal == plainLocal); - BOOST_REQUIRE(plainLocalFromFuture == plainLocal); } BOOST_AUTO_TEST_CASE(cryptopp_aes128_ctr) @@ -346,21 +337,28 @@ BOOST_AUTO_TEST_CASE(cryptopp_aes128_ctr) rng.GenerateBlock(key, key.size()); // cryptopp uses IV as nonce/counter which is same as using nonce w/0 ctr - byte ctr[AES::BLOCKSIZE]; - rng.GenerateBlock(ctr, sizeof(ctr)); + FixedHash ctr; + rng.GenerateBlock(ctr.data(), sizeof(ctr)); + + // used for decrypt + FixedHash ctrcopy(ctr); - string text = "Now is the time for all good persons to come to the aide of humanity."; - // c++11 ftw + string text = "Now is the time for all good persons to come to the aid of humanity."; unsigned char const* in = (unsigned char*)&text[0]; unsigned char* out = (unsigned char*)&text[0]; string original = text; + string doublespeak = text + text; string cipherCopy; try { CTR_Mode::Encryption e; - e.SetKeyWithIV(key, key.size(), ctr); + e.SetKeyWithIV(key, key.size(), ctr.data()); + + // 68 % 255 should be difference of counter e.ProcessData(out, in, text.size()); + ctr = h128(u128(ctr) + text.size() % 16); + BOOST_REQUIRE(text != original); cipherCopy = text; } @@ -372,7 +370,7 @@ BOOST_AUTO_TEST_CASE(cryptopp_aes128_ctr) try { CTR_Mode< AES >::Decryption d; - d.SetKeyWithIV(key, key.size(), ctr); + d.SetKeyWithIV(key, key.size(), ctrcopy.data()); d.ProcessData(out, in, text.size()); BOOST_REQUIRE(text == original); } @@ -390,7 +388,7 @@ BOOST_AUTO_TEST_CASE(cryptopp_aes128_ctr) out = (unsigned char*)&cipherCopy[0]; CTR_Mode::Encryption e; - e.SetKeyWithIV(key, key.size(), ctr); + e.SetKeyWithIV(key, key.size(), ctrcopy.data()); e.ProcessData(out, in, text.size()); // yep, ctr mode. diff --git a/test/genesis.cpp b/test/genesis.cpp index 6839d42e2..1b354dab8 100644 --- a/test/genesis.cpp +++ b/test/genesis.cpp @@ -36,6 +36,15 @@ namespace js = json_spirit; BOOST_AUTO_TEST_SUITE(BasicTests) +BOOST_AUTO_TEST_CASE(emptySHA3Types) +{ + h256 emptyListSHA3(fromHex("1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347")); + BOOST_REQUIRE_EQUAL(emptyListSHA3, EmptyListSHA3); + + h256 emptySHA3(fromHex("c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470")); + BOOST_REQUIRE_EQUAL(emptySHA3, EmptySHA3); +} + BOOST_AUTO_TEST_CASE(genesis_tests) { string testPath = test::getTestPath(); @@ -51,7 +60,7 @@ BOOST_AUTO_TEST_CASE(genesis_tests) BOOST_CHECK_EQUAL(BlockChain::genesis().stateRoot, h256(o["genesis_state_root"].get_str())); BOOST_CHECK_EQUAL(toHex(BlockChain::createGenesisBlock()), toHex(fromHex(o["genesis_rlp_hex"].get_str()))); - BOOST_CHECK_EQUAL(sha3(BlockChain::createGenesisBlock()), h256(o["genesis_hash"].get_str())); + BOOST_CHECK_EQUAL(BlockInfo::headerHash(BlockChain::createGenesisBlock()), h256(o["genesis_hash"].get_str())); } BOOST_AUTO_TEST_SUITE_END() diff --git a/test/jsonrpc.cpp b/test/jsonrpc.cpp index 4c748a954..37377407c 100644 --- a/test/jsonrpc.cpp +++ b/test/jsonrpc.cpp @@ -19,7 +19,7 @@ * @date 2014 */ -#if ETH_JSONRPC +#if ETH_JSONRPC && 0 #include #include @@ -29,8 +29,9 @@ #include #include #include -#include -#include +#include +#include +#include #include #include "JsonSpiritHeaders.h" #include "TestHelper.h" @@ -43,7 +44,7 @@ using namespace dev; using namespace dev::eth; namespace js = json_spirit; -WebThreeDirect *web3; +WebThreeDirect* web3; unique_ptr jsonrpcServer; unique_ptr jsonrpcClient; @@ -61,11 +62,12 @@ struct Setup web3->setIdealPeerCount(5); web3->ethereum()->setForceMining(true); - jsonrpcServer = unique_ptr(new WebThreeStubServer(new jsonrpc::CorsHttpServer(8080), *web3, {})); + auto server = new jsonrpc::HttpServer(8080); + jsonrpcServer = unique_ptr(new WebThreeStubServer(*server, *web3, {})); jsonrpcServer->setIdentities({}); jsonrpcServer->StartListening(); - - jsonrpcClient = unique_ptr(new WebThreeStubClient(new jsonrpc::HttpClient("http://localhost:8080"))); + auto client = new jsonrpc::HttpClient("http://localhost:8080"); + jsonrpcClient = unique_ptr(new WebThreeStubClient(*client)); } }; @@ -237,7 +239,76 @@ BOOST_AUTO_TEST_CASE(jsonrpc_transact) BOOST_CHECK_EQUAL(jsToDecimal(balanceString2), "750000000000000000"); BOOST_CHECK_EQUAL(txAmount, balance2); } + + +BOOST_AUTO_TEST_CASE(simple_contract) +{ + cnote << "Testing jsonrpc contract..."; + KeyPair kp = KeyPair::create(); + web3->ethereum()->setAddress(kp.address()); + jsonrpcServer->setAccounts({kp}); + + dev::eth::mine(*(web3->ethereum()), 1); + + char const* sourceCode = "contract test {\n" + " function f(uint a) returns(uint d) { return a * 7; }\n" + "}\n"; + + string compiled = jsonrpcClient->eth_solidity(sourceCode); + + Json::Value create; + create["code"] = compiled; + string contractAddress = jsonrpcClient->eth_transact(create); + dev::eth::mine(*(web3->ethereum()), 1); + + Json::Value call; + call["to"] = contractAddress; + call["data"] = "0x00000000000000000000000000000000000000000000000000000000000000001"; + string result = jsonrpcClient->eth_call(call); + BOOST_CHECK_EQUAL(result, "0x0000000000000000000000000000000000000000000000000000000000000007"); +} + +BOOST_AUTO_TEST_CASE(contract_storage) +{ + cnote << "Testing jsonrpc contract storage..."; + KeyPair kp = KeyPair::create(); + web3->ethereum()->setAddress(kp.address()); + jsonrpcServer->setAccounts({kp}); + + dev::eth::mine(*(web3->ethereum()), 1); + + char const* sourceCode = R"( + contract test { + uint hello; + function writeHello(uint value) returns(bool d){ + hello = value; + return true; + } + } + )"; + + string compiled = jsonrpcClient->eth_solidity(sourceCode); + + Json::Value create; + create["code"] = compiled; + string contractAddress = jsonrpcClient->eth_transact(create); + dev::eth::mine(*(web3->ethereum()), 1); + Json::Value transact; + transact["to"] = contractAddress; + transact["data"] = "0x00000000000000000000000000000000000000000000000000000000000000003"; + jsonrpcClient->eth_transact(transact); + dev::eth::mine(*(web3->ethereum()), 1); + + Json::Value storage = jsonrpcClient->eth_storageAt(contractAddress); + BOOST_CHECK_EQUAL(storage.getMemberNames().size(), 1); + // bracers are required, cause msvc couldnt handle this macro in for statement + for (auto name: storage.getMemberNames()) + { + BOOST_CHECK_EQUAL(storage[name].asString(), "0x03"); + } +} + BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE_END() diff --git a/test/solidityCompiler.cpp b/test/solidityCompiler.cpp index ba2db67e6..eae8f3142 100644 --- a/test/solidityCompiler.cpp +++ b/test/solidityCompiler.cpp @@ -46,16 +46,23 @@ namespace bytes compileContract(const string& _sourceCode) { Parser parser; - ASTPointer contract; - BOOST_REQUIRE_NO_THROW(contract = parser.parse(make_shared(CharStream(_sourceCode)))); - NameAndTypeResolver resolver; - BOOST_REQUIRE_NO_THROW(resolver.resolveNamesAndTypes(*contract)); - - Compiler compiler; - compiler.compileContract(*contract); - // debug - //compiler.streamAssembly(cout); - return compiler.getAssembledBytecode(); + ASTPointer sourceUnit; + BOOST_REQUIRE_NO_THROW(sourceUnit = parser.parse(make_shared(CharStream(_sourceCode)))); + NameAndTypeResolver resolver({}); + resolver.registerDeclarations(*sourceUnit); + for (ASTPointer const& node: sourceUnit->getNodes()) + if (ContractDefinition* contract = dynamic_cast(node.get())) + { + BOOST_REQUIRE_NO_THROW(resolver.resolveNamesAndTypes(*contract)); + + Compiler compiler; + compiler.compileContract(*contract, {}); + // debug + //compiler.streamAssembly(cout); + return compiler.getAssembledBytecode(); + } + BOOST_FAIL("No contract found in source."); + return bytes(); } /// Checks that @a _compiledCode is present starting from offset @a _offset in @a _expectation. @@ -80,7 +87,7 @@ BOOST_AUTO_TEST_CASE(smoke_test) "}\n"; bytes code = compileContract(sourceCode); - unsigned boilerplateSize = 51; + unsigned boilerplateSize = 40; bytes expectation({byte(Instruction::JUMPDEST), byte(Instruction::PUSH1), 0x0, // initialize local variable x byte(Instruction::PUSH1), 0x2, @@ -100,8 +107,8 @@ BOOST_AUTO_TEST_CASE(different_argument_numbers) "}\n"; bytes code = compileContract(sourceCode); - unsigned shift = 75; - unsigned boilerplateSize = 88; + unsigned shift = 68; + unsigned boilerplateSize = 81; bytes expectation({byte(Instruction::JUMPDEST), byte(Instruction::PUSH1), 0x0, // initialize return variable d byte(Instruction::DUP3), @@ -118,8 +125,8 @@ BOOST_AUTO_TEST_CASE(different_argument_numbers) byte(Instruction::JUMP), // end of f byte(Instruction::JUMPDEST), // beginning of g byte(Instruction::PUSH1), 0x0, - byte(Instruction::DUP1), // initialized e and h - byte(Instruction::PUSH1), byte(0x29 + shift), // ret address + byte(Instruction::PUSH1), 0x0, // initialized e and h + byte(Instruction::PUSH1), byte(0x2a + shift), // ret address byte(Instruction::PUSH1), 0x1, byte(Instruction::PUSH1), 0xff, byte(Instruction::AND), byte(Instruction::PUSH1), 0x2, byte(Instruction::PUSH1), 0xff, byte(Instruction::AND), byte(Instruction::PUSH1), 0x3, byte(Instruction::PUSH1), 0xff, byte(Instruction::AND), @@ -128,8 +135,6 @@ BOOST_AUTO_TEST_CASE(different_argument_numbers) byte(Instruction::JUMP), byte(Instruction::JUMPDEST), // stack here: ret e h f(1,2,3) - byte(Instruction::DUP2), - byte(Instruction::POP), byte(Instruction::SWAP1), // stack here: ret e f(1,2,3) h byte(Instruction::POP), @@ -153,8 +158,8 @@ BOOST_AUTO_TEST_CASE(ifStatement) "}\n"; bytes code = compileContract(sourceCode); - unsigned shift = 38; - unsigned boilerplateSize = 51; + unsigned shift = 27; + unsigned boilerplateSize = 40; bytes expectation({byte(Instruction::JUMPDEST), byte(Instruction::PUSH1), 0x0, byte(Instruction::DUP1), @@ -195,8 +200,8 @@ BOOST_AUTO_TEST_CASE(loops) "}\n"; bytes code = compileContract(sourceCode); - unsigned shift = 38; - unsigned boilerplateSize = 51; + unsigned shift = 27; + unsigned boilerplateSize = 40; bytes expectation({byte(Instruction::JUMPDEST), byte(Instruction::JUMPDEST), byte(Instruction::PUSH1), 0x1, diff --git a/test/solidityEndToEndTest.cpp b/test/solidityEndToEndTest.cpp index 796adcb15..0970c4f4b 100644 --- a/test/solidityEndToEndTest.cpp +++ b/test/solidityEndToEndTest.cpp @@ -22,10 +22,10 @@ */ #include +#include #include -#include -#include -#include +#include +#include using namespace std; @@ -36,74 +36,6 @@ namespace solidity namespace test { -class ExecutionFramework -{ -public: - ExecutionFramework() { g_logVerbosity = 0; } - - bytes const& compileAndRun(std::string const& _sourceCode) - { - bytes code = dev::solidity::CompilerStack::compile(_sourceCode); - sendMessage(code, true); - BOOST_REQUIRE(!m_output.empty()); - return m_output; - } - - bytes const& callFunction(byte _index, bytes const& _data) - { - sendMessage(bytes(1, _index) + _data, false); - return m_output; - } - - bytes const& callFunction(byte _index, u256 const& _argument1) - { - return callFunction(_index, toBigEndian(_argument1)); - } - - bool testSolidityAgainstCpp(byte _index, std::function const& _cppfun, u256 const& _argument1) - { - return toBigEndian(_cppfun(_argument1)) == callFunction(_index, toBigEndian(_argument1)); - } - - bool testSolidityAgainstCpp(byte _index, std::function const& _cppfun) - { - return toBigEndian(_cppfun()) == callFunction(_index, bytes()); - } - -private: - void sendMessage(bytes const& _data, bool _isCreation) - { - eth::Executive executive(m_state); - eth::Transaction t = _isCreation ? eth::Transaction(0, m_gasPrice, m_gas, _data, 0, KeyPair::create().sec()) - : eth::Transaction(0, m_gasPrice, m_gas, m_contractAddress, _data, 0, KeyPair::create().sec()); - bytes transactionRLP = t.rlp(); - try - { - // this will throw since the transaction is invalid, but it should nevertheless store the transaction - executive.setup(&transactionRLP); - } - catch (...) {} - if (_isCreation) - { - BOOST_REQUIRE(!executive.create(Address(), 0, m_gasPrice, m_gas, &_data, Address())); - m_contractAddress = executive.newAddress(); - BOOST_REQUIRE(m_contractAddress); - BOOST_REQUIRE(m_state.addressHasCode(m_contractAddress)); - } - else - BOOST_REQUIRE(!executive.call(m_contractAddress, Address(), 0, m_gasPrice, &_data, m_gas, Address())); - BOOST_REQUIRE(executive.go()); - executive.finalize(); - m_output = executive.out().toVector(); - } - - Address m_contractAddress; - eth::State m_state; - u256 const m_gasPrice = 100 * eth::szabo; - u256 const m_gas = 1000000; - bytes m_output; -}; - BOOST_FIXTURE_TEST_SUITE(SolidityCompilerEndToEndTest, ExecutionFramework) BOOST_AUTO_TEST_CASE(smoke_test) @@ -112,8 +44,7 @@ BOOST_AUTO_TEST_CASE(smoke_test) " function f(uint a) returns(uint d) { return a * 7; }\n" "}\n"; compileAndRun(sourceCode); - u256 a = 0x200030004; - BOOST_CHECK(callFunction(0, a) == toBigEndian(a * 7)); + testSolidityAgainstCppOnRange(0, [](u256 const& a) -> u256 { return a * 7; }, 0, 100); } BOOST_AUTO_TEST_CASE(empty_contract) @@ -121,7 +52,7 @@ BOOST_AUTO_TEST_CASE(empty_contract) char const* sourceCode = "contract test {\n" "}\n"; compileAndRun(sourceCode); - BOOST_CHECK(callFunction(0, bytes()).empty()); + BOOST_CHECK(callContractFunction(0, bytes()).empty()); } BOOST_AUTO_TEST_CASE(recursive_calls) @@ -133,7 +64,7 @@ BOOST_AUTO_TEST_CASE(recursive_calls) " }\n" "}\n"; compileAndRun(sourceCode); - std::function recursive_calls_cpp = [&recursive_calls_cpp](u256 const& n) -> u256 + function recursive_calls_cpp = [&recursive_calls_cpp](u256 const& n) -> u256 { if (n <= 1) return 1; @@ -141,11 +72,23 @@ BOOST_AUTO_TEST_CASE(recursive_calls) return n * recursive_calls_cpp(n - 1); }; - BOOST_CHECK(testSolidityAgainstCpp(0, recursive_calls_cpp, u256(0))); - BOOST_CHECK(testSolidityAgainstCpp(0, recursive_calls_cpp, u256(1))); - BOOST_CHECK(testSolidityAgainstCpp(0, recursive_calls_cpp, u256(2))); - BOOST_CHECK(testSolidityAgainstCpp(0, recursive_calls_cpp, u256(3))); - BOOST_CHECK(testSolidityAgainstCpp(0, recursive_calls_cpp, u256(4))); + testSolidityAgainstCppOnRange(0, recursive_calls_cpp, 0, 5); +} + +BOOST_AUTO_TEST_CASE(multiple_functions) +{ + char const* sourceCode = "contract test {\n" + " function a() returns(uint n) { return 0; }\n" + " function b() returns(uint n) { return 1; }\n" + " function c() returns(uint n) { return 2; }\n" + " function f() returns(uint n) { return 3; }\n" + "}\n"; + compileAndRun(sourceCode); + BOOST_CHECK(callContractFunction(0, bytes()) == toBigEndian(u256(0))); + BOOST_CHECK(callContractFunction(1, bytes()) == toBigEndian(u256(1))); + BOOST_CHECK(callContractFunction(2, bytes()) == toBigEndian(u256(2))); + BOOST_CHECK(callContractFunction(3, bytes()) == toBigEndian(u256(3))); + BOOST_CHECK(callContractFunction(4, bytes()) == bytes()); } BOOST_AUTO_TEST_CASE(while_loop) @@ -169,11 +112,7 @@ BOOST_AUTO_TEST_CASE(while_loop) return nfac; }; - BOOST_CHECK(testSolidityAgainstCpp(0, while_loop_cpp, u256(0))); - BOOST_CHECK(testSolidityAgainstCpp(0, while_loop_cpp, u256(1))); - BOOST_CHECK(testSolidityAgainstCpp(0, while_loop_cpp, u256(2))); - BOOST_CHECK(testSolidityAgainstCpp(0, while_loop_cpp, u256(3))); - BOOST_CHECK(testSolidityAgainstCpp(0, while_loop_cpp, u256(4))); + testSolidityAgainstCppOnRange(0, while_loop_cpp, 0, 5); } BOOST_AUTO_TEST_CASE(break_outside_loop) @@ -184,9 +123,8 @@ BOOST_AUTO_TEST_CASE(break_outside_loop) " break; continue; return 2;\n" " }\n" "}\n"; - ExecutionFramework framework; - framework.compileAndRun(sourceCode); - BOOST_CHECK(framework.callFunction(0, u256(0)) == toBigEndian(u256(2))); + compileAndRun(sourceCode); + testSolidityAgainstCpp(0, [](u256 const&) -> u256 { return 2; }, u256(0)); } BOOST_AUTO_TEST_CASE(nested_loops) @@ -209,8 +147,7 @@ BOOST_AUTO_TEST_CASE(nested_loops) " return x;\n" " }\n" "}\n"; - ExecutionFramework framework; - framework.compileAndRun(sourceCode); + compileAndRun(sourceCode); auto nested_loops_cpp = [](u256 n) -> u256 { @@ -236,18 +173,7 @@ BOOST_AUTO_TEST_CASE(nested_loops) return n; }; - BOOST_CHECK(framework.testSolidityAgainstCpp(0, nested_loops_cpp, u256(0))); - BOOST_CHECK(framework.testSolidityAgainstCpp(0, nested_loops_cpp, u256(1))); - BOOST_CHECK(framework.testSolidityAgainstCpp(0, nested_loops_cpp, u256(2))); - BOOST_CHECK(framework.testSolidityAgainstCpp(0, nested_loops_cpp, u256(3))); - BOOST_CHECK(framework.testSolidityAgainstCpp(0, nested_loops_cpp, u256(4))); - BOOST_CHECK(framework.testSolidityAgainstCpp(0, nested_loops_cpp, u256(5))); - BOOST_CHECK(framework.testSolidityAgainstCpp(0, nested_loops_cpp, u256(6))); - BOOST_CHECK(framework.testSolidityAgainstCpp(0, nested_loops_cpp, u256(7))); - BOOST_CHECK(framework.testSolidityAgainstCpp(0, nested_loops_cpp, u256(8))); - BOOST_CHECK(framework.testSolidityAgainstCpp(0, nested_loops_cpp, u256(9))); - BOOST_CHECK(framework.testSolidityAgainstCpp(0, nested_loops_cpp, u256(10))); - BOOST_CHECK(framework.testSolidityAgainstCpp(0, nested_loops_cpp, u256(11))); + testSolidityAgainstCppOnRange(0, nested_loops_cpp, 0, 12); } BOOST_AUTO_TEST_CASE(calling_other_functions) @@ -279,7 +205,8 @@ BOOST_AUTO_TEST_CASE(calling_other_functions) return 3 * n + 1; }; - auto collatz_cpp = [&evenStep_cpp, &oddStep_cpp] (u256 n) -> u256 { + auto collatz_cpp = [&evenStep_cpp, &oddStep_cpp](u256 n) -> u256 + { u256 y; while ((y = n) > 1) { @@ -291,11 +218,11 @@ BOOST_AUTO_TEST_CASE(calling_other_functions) return y; }; - BOOST_CHECK(testSolidityAgainstCpp(2, collatz_cpp, u256(0))); - BOOST_CHECK(testSolidityAgainstCpp(2, collatz_cpp, u256(1))); - BOOST_CHECK(testSolidityAgainstCpp(2, collatz_cpp, u256(2))); - BOOST_CHECK(testSolidityAgainstCpp(2, collatz_cpp, u256(8))); - BOOST_CHECK(testSolidityAgainstCpp(2, collatz_cpp, u256(127))); + testSolidityAgainstCpp(2, collatz_cpp, u256(0)); + testSolidityAgainstCpp(2, collatz_cpp, u256(1)); + testSolidityAgainstCpp(2, collatz_cpp, u256(2)); + testSolidityAgainstCpp(2, collatz_cpp, u256(8)); + testSolidityAgainstCpp(2, collatz_cpp, u256(127)); } BOOST_AUTO_TEST_CASE(many_local_variables) @@ -308,8 +235,15 @@ BOOST_AUTO_TEST_CASE(many_local_variables) " }\n" "}\n"; compileAndRun(sourceCode); - BOOST_CHECK(callFunction(0, toBigEndian(u256(0x1000)) + toBigEndian(u256(0x10000)) + toBigEndian(u256(0x100000))) - == toBigEndian(u256(0x121121))); + auto f = [](u256 const& x1, u256 const& x2, u256 const& x3) -> u256 + { + u256 a = 0x1; + u256 b = 0x10; + u256 c = 0x100; + u256 y = a + b + c + x1 + x2 + x3; + return y + b + x2; + }; + testSolidityAgainstCpp(0, f, u256(0x1000), u256(0x10000), u256(0x100000)); } BOOST_AUTO_TEST_CASE(packing_unpacking_types) @@ -322,7 +256,7 @@ BOOST_AUTO_TEST_CASE(packing_unpacking_types) " }\n" "}\n"; compileAndRun(sourceCode); - BOOST_CHECK(callFunction(0, fromHex("01""0f0f0f0f""f0f0f0f0f0f0f0f0")) + BOOST_CHECK(callContractFunction(0, fromHex("01""0f0f0f0f""f0f0f0f0f0f0f0f0")) == fromHex("00000000000000000000000000000000000000""01""f0f0f0f0""0f0f0f0f0f0f0f0f")); } @@ -334,7 +268,7 @@ BOOST_AUTO_TEST_CASE(multiple_return_values) " }\n" "}\n"; compileAndRun(sourceCode); - BOOST_CHECK(callFunction(0, bytes(1, 1) + toBigEndian(u256(0xcd))) + BOOST_CHECK(callContractFunction(0, bytes(1, 1) + toBigEndian(u256(0xcd))) == toBigEndian(u256(0xcd)) + bytes(1, 1) + toBigEndian(u256(0))); } @@ -354,8 +288,7 @@ BOOST_AUTO_TEST_CASE(short_circuiting) return n; }; - BOOST_CHECK(testSolidityAgainstCpp(0, short_circuiting_cpp, u256(0))); - BOOST_CHECK(testSolidityAgainstCpp(0, short_circuiting_cpp, u256(1))); + testSolidityAgainstCppOnRange(0, short_circuiting_cpp, 0, 2); } BOOST_AUTO_TEST_CASE(high_bits_cleaning) @@ -375,7 +308,7 @@ BOOST_AUTO_TEST_CASE(high_bits_cleaning) return 0; return x; }; - BOOST_CHECK(testSolidityAgainstCpp(0, high_bits_cleaning_cpp)); + testSolidityAgainstCpp(0, high_bits_cleaning_cpp); } BOOST_AUTO_TEST_CASE(sign_extension) @@ -395,7 +328,7 @@ BOOST_AUTO_TEST_CASE(sign_extension) return 0; return u256(x) * -1; }; - BOOST_CHECK(testSolidityAgainstCpp(0, sign_extension_cpp)); + testSolidityAgainstCpp(0, sign_extension_cpp); } BOOST_AUTO_TEST_CASE(small_unsigned_types) @@ -412,7 +345,7 @@ BOOST_AUTO_TEST_CASE(small_unsigned_types) uint32_t x = uint32_t(0xffffff) * 0xffffff; return x / 0x100; }; - BOOST_CHECK(testSolidityAgainstCpp(0, small_unsigned_types_cpp)); + testSolidityAgainstCpp(0, small_unsigned_types_cpp); } BOOST_AUTO_TEST_CASE(small_signed_types) @@ -427,7 +360,49 @@ BOOST_AUTO_TEST_CASE(small_signed_types) { return -int32_t(10) * -int64_t(20); }; - BOOST_CHECK(testSolidityAgainstCpp(0, small_signed_types_cpp)); + testSolidityAgainstCpp(0, small_signed_types_cpp); +} + +BOOST_AUTO_TEST_CASE(strings) +{ + char const* sourceCode = "contract test {\n" + " function fixed() returns(string32 ret) {\n" + " return \"abc\\x00\\xff__\";\n" + " }\n" + " function pipeThrough(string2 small, bool one) returns(string16 large, bool oneRet) {\n" + " oneRet = one;\n" + " large = small;\n" + " }\n" + "}\n"; + compileAndRun(sourceCode); + bytes expectation(32, 0); + expectation[0] = byte('a'); + expectation[1] = byte('b'); + expectation[2] = byte('c'); + expectation[3] = byte(0); + expectation[4] = byte(0xff); + expectation[5] = byte('_'); + expectation[6] = byte('_'); + BOOST_CHECK(callContractFunction(0, bytes()) == expectation); + expectation = bytes(17, 0); + expectation[0] = 0; + expectation[1] = 2; + expectation[16] = 1; + BOOST_CHECK(callContractFunction(1, bytes({0x00, 0x02, 0x01})) == expectation); +} + +BOOST_AUTO_TEST_CASE(empty_string_on_stack) +{ + char const* sourceCode = "contract test {\n" + " function run(string0 empty, uint8 inp) returns(uint16 a, string0 b, string4 c) {\n" + " var x = \"abc\";\n" + " var y = \"\";\n" + " var z = inp;\n" + " a = z; b = y; c = x;" + " }\n" + "}\n"; + compileAndRun(sourceCode); + BOOST_CHECK(callContractFunction(0, bytes({0x02})) == bytes({0x00, 0x02, (byte)'a', (byte)'b', (byte)'c', 0x00})); } BOOST_AUTO_TEST_CASE(state_smoke_test) @@ -445,14 +420,596 @@ BOOST_AUTO_TEST_CASE(state_smoke_test) " }\n" "}\n"; compileAndRun(sourceCode); - BOOST_CHECK(callFunction(0, bytes(1, 0x00)) == toBigEndian(u256(0))); - BOOST_CHECK(callFunction(0, bytes(1, 0x01)) == toBigEndian(u256(0))); - BOOST_CHECK(callFunction(1, bytes(1, 0x00) + toBigEndian(u256(0x1234))) == bytes()); - BOOST_CHECK(callFunction(1, bytes(1, 0x01) + toBigEndian(u256(0x8765))) == bytes()); - BOOST_CHECK(callFunction(0, bytes(1, 0x00)) == toBigEndian(u256(0x1234))); - BOOST_CHECK(callFunction(0, bytes(1, 0x01)) == toBigEndian(u256(0x8765))); - BOOST_CHECK(callFunction(1, bytes(1, 0x00) + toBigEndian(u256(0x3))) == bytes()); - BOOST_CHECK(callFunction(0, bytes(1, 0x00)) == toBigEndian(u256(0x3))); + BOOST_CHECK(callContractFunction(0, bytes(1, 0x00)) == toBigEndian(u256(0))); + BOOST_CHECK(callContractFunction(0, bytes(1, 0x01)) == toBigEndian(u256(0))); + BOOST_CHECK(callContractFunction(1, bytes(1, 0x00) + toBigEndian(u256(0x1234))) == bytes()); + BOOST_CHECK(callContractFunction(1, bytes(1, 0x01) + toBigEndian(u256(0x8765))) == bytes()); + BOOST_CHECK(callContractFunction(0, bytes(1, 0x00)) == toBigEndian(u256(0x1234))); + BOOST_CHECK(callContractFunction(0, bytes(1, 0x01)) == toBigEndian(u256(0x8765))); + BOOST_CHECK(callContractFunction(1, bytes(1, 0x00) + toBigEndian(u256(0x3))) == bytes()); + BOOST_CHECK(callContractFunction(0, bytes(1, 0x00)) == toBigEndian(u256(0x3))); +} + +BOOST_AUTO_TEST_CASE(simple_mapping) +{ + char const* sourceCode = "contract test {\n" + " mapping(uint8 => uint8) table;\n" + " function get(uint8 k) returns (uint8 v) {\n" + " return table[k];\n" + " }\n" + " function set(uint8 k, uint8 v) {\n" + " table[k] = v;\n" + " }\n" + "}"; + compileAndRun(sourceCode); + + // msvc seems to have problems with initializer-list, when there is only 1 param in the list + BOOST_CHECK(callContractFunction(0, bytes(1, 0x00)) == bytes(1, 0x00)); + BOOST_CHECK(callContractFunction(0, bytes(1, 0x01)) == bytes(1, 0x00)); + BOOST_CHECK(callContractFunction(0, bytes(1, 0xa7)) == bytes(1, 0x00)); + callContractFunction(1, bytes({0x01, 0xa1})); + BOOST_CHECK(callContractFunction(0, bytes(1, 0x00)) == bytes(1, 0x00)); + BOOST_CHECK(callContractFunction(0, bytes(1, 0x01)) == bytes(1, 0xa1)); + BOOST_CHECK(callContractFunction(0, bytes(1, 0xa7)) == bytes(1, 0x00)); + callContractFunction(1, bytes({0x00, 0xef})); + BOOST_CHECK(callContractFunction(0, bytes(1, 0x00)) == bytes(1, 0xef)); + BOOST_CHECK(callContractFunction(0, bytes(1, 0x01)) == bytes(1, 0xa1)); + BOOST_CHECK(callContractFunction(0, bytes(1, 0xa7)) == bytes(1, 0x00)); + callContractFunction(1, bytes({0x01, 0x05})); + BOOST_CHECK(callContractFunction(0, bytes(1, 0x00)) == bytes(1, 0xef)); + BOOST_CHECK(callContractFunction(0, bytes(1, 0x01)) == bytes(1, 0x05)); + BOOST_CHECK(callContractFunction(0, bytes(1, 0xa7)) == bytes(1, 0x00)); +} + +BOOST_AUTO_TEST_CASE(mapping_state) +{ + char const* sourceCode = "contract Ballot {\n" + " mapping(address => bool) canVote;\n" + " mapping(address => uint) voteCount;\n" + " mapping(address => bool) voted;\n" + " function getVoteCount(address addr) returns (uint retVoteCount) {\n" + " return voteCount[addr];\n" + " }\n" + " function grantVoteRight(address addr) {\n" + " canVote[addr] = true;\n" + " }\n" + " function vote(address voter, address vote) returns (bool success) {\n" + " if (!canVote[voter] || voted[voter]) return false;\n" + " voted[voter] = true;\n" + " voteCount[vote] = voteCount[vote] + 1;\n" + " return true;\n" + " }\n" + "}\n"; + compileAndRun(sourceCode); + class Ballot + { + public: + u256 getVoteCount(u160 _address) { return m_voteCount[_address]; } + void grantVoteRight(u160 _address) { m_canVote[_address] = true; } + bool vote(u160 _voter, u160 _vote) + { + if (!m_canVote[_voter] || m_voted[_voter]) return false; + m_voted[_voter] = true; + m_voteCount[_vote]++; + return true; + } + private: + map m_canVote; + map m_voteCount; + map m_voted; + } ballot; + + auto getVoteCount = bind(&Ballot::getVoteCount, &ballot, _1); + auto grantVoteRight = bind(&Ballot::grantVoteRight, &ballot, _1); + auto vote = bind(&Ballot::vote, &ballot, _1, _2); + testSolidityAgainstCpp(0, getVoteCount, u160(0)); + testSolidityAgainstCpp(0, getVoteCount, u160(1)); + testSolidityAgainstCpp(0, getVoteCount, u160(2)); + // voting without vote right shourd be rejected + testSolidityAgainstCpp(2, vote, u160(0), u160(2)); + testSolidityAgainstCpp(0, getVoteCount, u160(0)); + testSolidityAgainstCpp(0, getVoteCount, u160(1)); + testSolidityAgainstCpp(0, getVoteCount, u160(2)); + // grant vote rights + testSolidityAgainstCpp(1, grantVoteRight, u160(0)); + testSolidityAgainstCpp(1, grantVoteRight, u160(1)); + // vote, should increase 2's vote count + testSolidityAgainstCpp(2, vote, u160(0), u160(2)); + testSolidityAgainstCpp(0, getVoteCount, u160(0)); + testSolidityAgainstCpp(0, getVoteCount, u160(1)); + testSolidityAgainstCpp(0, getVoteCount, u160(2)); + // vote again, should be rejected + testSolidityAgainstCpp(2, vote, u160(0), u160(1)); + testSolidityAgainstCpp(0, getVoteCount, u160(0)); + testSolidityAgainstCpp(0, getVoteCount, u160(1)); + testSolidityAgainstCpp(0, getVoteCount, u160(2)); + // vote without right to vote + testSolidityAgainstCpp(2, vote, u160(2), u160(1)); + testSolidityAgainstCpp(0, getVoteCount, u160(0)); + testSolidityAgainstCpp(0, getVoteCount, u160(1)); + testSolidityAgainstCpp(0, getVoteCount, u160(2)); + // grant vote right and now vote again + testSolidityAgainstCpp(1, grantVoteRight, u160(2)); + testSolidityAgainstCpp(2, vote, u160(2), u160(1)); + testSolidityAgainstCpp(0, getVoteCount, u160(0)); + testSolidityAgainstCpp(0, getVoteCount, u160(1)); + testSolidityAgainstCpp(0, getVoteCount, u160(2)); +} + +BOOST_AUTO_TEST_CASE(mapping_state_inc_dec) +{ + char const* sourceCode = "contract test {\n" + " uint value;\n" + " mapping(uint => uint) table;\n" + " function f(uint x) returns (uint y) {\n" + " value = x;\n" + " if (x > 0) table[++value] = 8;\n" + " if (x > 1) value--;\n" + " if (x > 2) table[value]++;\n" + " return --table[value++];\n" + " }\n" + "}\n"; + compileAndRun(sourceCode); + + u256 value = 0; + map table; + auto f = [&](u256 const& _x) -> u256 + { + value = _x; + if (_x > 0) + table[++value] = 8; + if (_x > 1) + value --; + if (_x > 2) + table[value]++; + return --table[value++]; + }; + testSolidityAgainstCppOnRange(0, f, 0, 5); +} + +BOOST_AUTO_TEST_CASE(multi_level_mapping) +{ + char const* sourceCode = "contract test {\n" + " mapping(uint => mapping(uint => uint)) table;\n" + " function f(uint x, uint y, uint z) returns (uint w) {\n" + " if (z == 0) return table[x][y];\n" + " else return table[x][y] = z;\n" + " }\n" + "}\n"; + compileAndRun(sourceCode); + + map> table; + auto f = [&](u256 const& _x, u256 const& _y, u256 const& _z) -> u256 + { + if (_z == 0) return table[_x][_y]; + else return table[_x][_y] = _z; + }; + testSolidityAgainstCpp(0, f, u256(4), u256(5), u256(0)); + testSolidityAgainstCpp(0, f, u256(5), u256(4), u256(0)); + testSolidityAgainstCpp(0, f, u256(4), u256(5), u256(9)); + testSolidityAgainstCpp(0, f, u256(4), u256(5), u256(0)); + testSolidityAgainstCpp(0, f, u256(5), u256(4), u256(0)); + testSolidityAgainstCpp(0, f, u256(5), u256(4), u256(7)); + testSolidityAgainstCpp(0, f, u256(4), u256(5), u256(0)); + testSolidityAgainstCpp(0, f, u256(5), u256(4), u256(0)); +} + +BOOST_AUTO_TEST_CASE(structs) +{ + char const* sourceCode = "contract test {\n" + " struct s1 {\n" + " uint8 x;\n" + " bool y;\n" + " }\n" + " struct s2 {\n" + " uint32 z;\n" + " s1 s1data;\n" + " mapping(uint8 => s2) recursive;\n" + " }\n" + " s2 data;\n" + " function check() returns (bool ok) {\n" + " return data.z == 1 && data.s1data.x == 2 && \n" + " data.s1data.y == true && \n" + " data.recursive[3].recursive[4].z == 5 && \n" + " data.recursive[4].recursive[3].z == 6 && \n" + " data.recursive[0].s1data.y == false && \n" + " data.recursive[4].z == 9;\n" + " }\n" + " function set() {\n" + " data.z = 1;\n" + " data.s1data.x = 2;\n" + " data.s1data.y = true;\n" + " data.recursive[3].recursive[4].z = 5;\n" + " data.recursive[4].recursive[3].z = 6;\n" + " data.recursive[0].s1data.y = false;\n" + " data.recursive[4].z = 9;\n" + " }\n" + "}\n"; + compileAndRun(sourceCode); + BOOST_CHECK(callContractFunction(0) == bytes(1, 0x00)); + BOOST_CHECK(callContractFunction(1) == bytes()); + BOOST_CHECK(callContractFunction(0) == bytes(1, 0x01)); +} + +BOOST_AUTO_TEST_CASE(struct_reference) +{ + char const* sourceCode = "contract test {\n" + " struct s2 {\n" + " uint32 z;\n" + " mapping(uint8 => s2) recursive;\n" + " }\n" + " s2 data;\n" + " function check() returns (bool ok) {\n" + " return data.z == 2 && \n" + " data.recursive[0].z == 3 && \n" + " data.recursive[0].recursive[1].z == 0 && \n" + " data.recursive[0].recursive[0].z == 1;\n" + " }\n" + " function set() {\n" + " data.z = 2;\n" + " var map = data.recursive;\n" + " s2 inner = map[0];\n" + " inner.z = 3;\n" + " inner.recursive[0].z = inner.recursive[1].z + 1;\n" + " }\n" + "}\n"; + compileAndRun(sourceCode); + BOOST_CHECK(callContractFunction(0) == bytes(1, 0x00)); + BOOST_CHECK(callContractFunction(1) == bytes()); + BOOST_CHECK(callContractFunction(0) == bytes(1, 0x01)); +} + +BOOST_AUTO_TEST_CASE(constructor) +{ + char const* sourceCode = "contract test {\n" + " mapping(uint => uint) data;\n" + " function test() {\n" + " data[7] = 8;\n" + " }\n" + " function get(uint key) returns (uint value) {\n" + " return data[key];" + " }\n" + "}\n"; + compileAndRun(sourceCode); + map data; + data[7] = 8; + auto get = [&](u256 const& _x) -> u256 + { + return data[_x]; + }; + testSolidityAgainstCpp(0, get, u256(6)); + testSolidityAgainstCpp(0, get, u256(7)); +} + +BOOST_AUTO_TEST_CASE(balance) +{ + char const* sourceCode = "contract test {\n" + " function getBalance() returns (uint256 balance) {\n" + " return address(this).balance;\n" + " }\n" + "}\n"; + compileAndRun(sourceCode, 23); + BOOST_CHECK(callContractFunction(0) == toBigEndian(u256(23))); +} + +BOOST_AUTO_TEST_CASE(blockchain) +{ + char const* sourceCode = "contract test {\n" + " function someInfo() returns (uint256 value, address coinbase, uint256 blockNumber) {\n" + " value = msg.value;\n" + " coinbase = block.coinbase;\n" + " blockNumber = block.number;\n" + " }\n" + "}\n"; + compileAndRun(sourceCode, 27); + BOOST_CHECK(callContractFunction(0, bytes{0}, u256(28)) == toBigEndian(u256(28)) + bytes(20, 0) + toBigEndian(u256(1))); +} + +BOOST_AUTO_TEST_CASE(function_types) +{ + char const* sourceCode = "contract test {\n" + " function a(bool selector) returns (uint b) {\n" + " var f = fun1;\n" + " if (selector) f = fun2;\n" + " return f(9);\n" + " }\n" + " function fun1(uint x) returns (uint b) {\n" + " return 11;\n" + " }\n" + " function fun2(uint x) returns (uint b) {\n" + " return 12;\n" + " }\n" + "}\n"; + compileAndRun(sourceCode); + BOOST_CHECK(callContractFunction(0, bytes{0}) == toBigEndian(u256(11))); + BOOST_CHECK(callContractFunction(0, bytes{1}) == toBigEndian(u256(12))); +} + +BOOST_AUTO_TEST_CASE(send_ether) +{ + char const* sourceCode = "contract test {\n" + " function a(address addr, uint amount) returns (uint ret) {\n" + " addr.send(amount);\n" + " return address(this).balance;\n" + " }\n" + "}\n"; + u256 amount(130); + compileAndRun(sourceCode, amount + 1); + u160 address(23); + BOOST_CHECK(callContractFunction(0, address, amount) == toBigEndian(u256(1))); + BOOST_CHECK_EQUAL(m_state.balance(address), amount); +} + +BOOST_AUTO_TEST_CASE(suicide) +{ + char const* sourceCode = "contract test {\n" + " function a(address receiver) returns (uint ret) {\n" + " suicide(receiver);\n" + " return 10;\n" + " }\n" + "}\n"; + u256 amount(130); + compileAndRun(sourceCode, amount); + u160 address(23); + BOOST_CHECK(callContractFunction(0, address) == bytes()); + BOOST_CHECK(!m_state.addressHasCode(m_contractAddress)); + BOOST_CHECK_EQUAL(m_state.balance(address), amount); +} + +BOOST_AUTO_TEST_CASE(sha3) +{ + char const* sourceCode = "contract test {\n" + " function a(hash input) returns (hash sha3hash) {\n" + " return sha3(input);\n" + " }\n" + "}\n"; + compileAndRun(sourceCode); + auto f = [&](u256 const& _x) -> u256 + { + return dev::sha3(toBigEndian(_x)); + }; + testSolidityAgainstCpp(0, f, u256(4)); + testSolidityAgainstCpp(0, f, u256(5)); + testSolidityAgainstCpp(0, f, u256(-1)); +} + +BOOST_AUTO_TEST_CASE(sha256) +{ + char const* sourceCode = "contract test {\n" + " function a(hash input) returns (hash sha256hash) {\n" + " return sha256(input);\n" + " }\n" + "}\n"; + compileAndRun(sourceCode); + auto f = [&](u256 const& _input) -> u256 + { + h256 ret; + dev::sha256(dev::ref(toBigEndian(_input)), bytesRef(&ret[0], 32)); + return ret; + }; + testSolidityAgainstCpp(0, f, u256(4)); + testSolidityAgainstCpp(0, f, u256(5)); + testSolidityAgainstCpp(0, f, u256(-1)); +} + +BOOST_AUTO_TEST_CASE(ripemd) +{ + char const* sourceCode = "contract test {\n" + " function a(hash input) returns (hash sha256hash) {\n" + " return ripemd160(input);\n" + " }\n" + "}\n"; + compileAndRun(sourceCode); + auto f = [&](u256 const& _input) -> u256 + { + h256 ret; + dev::ripemd160(dev::ref(toBigEndian(_input)), bytesRef(&ret[0], 32)); + return u256(ret) >> (256 - 160); + }; + testSolidityAgainstCpp(0, f, u256(4)); + testSolidityAgainstCpp(0, f, u256(5)); + testSolidityAgainstCpp(0, f, u256(-1)); +} + +BOOST_AUTO_TEST_CASE(ecrecover) +{ + char const* sourceCode = "contract test {\n" + " function a(hash h, uint8 v, hash r, hash s) returns (address addr) {\n" + " return ecrecover(h, v, r, s);\n" + " }\n" + "}\n"; + compileAndRun(sourceCode); + u256 h("0x18c547e4f7b0f325ad1e56f57e26c745b09a3e503d86e00e5255ff7f715d3d1c"); + byte v = 28; + u256 r("0x73b1693892219d736caba55bdb67216e485557ea6b6af75f37096c9aa6a5a75f"); + u256 s("0xeeb940b1d03b21e36b0e47e79769f095fe2ab855bd91e3a38756b7d75a9c4549"); + u160 addr("0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b"); + BOOST_CHECK(callContractFunction(0, h, v, r, s) == toBigEndian(addr)); +} + +BOOST_AUTO_TEST_CASE(inter_contract_calls) +{ + char const* sourceCode = R"( + contract Helper { + function multiply(uint a, uint b) returns (uint c) { + return a * b; + } + } + contract Main { + Helper h; + function callHelper(uint a, uint b) returns (uint c) { + return h.multiply(a, b); + } + function getHelper() returns (address haddress) { + return address(h); + } + function setHelper(address haddress) { + h = Helper(haddress); + } + })"; + compileAndRun(sourceCode, 0, "Helper"); + u160 const helperAddress = m_contractAddress; + compileAndRun(sourceCode, 0, "Main"); + BOOST_REQUIRE(callContractFunction(2, helperAddress) == bytes()); + BOOST_REQUIRE(callContractFunction(1, helperAddress) == toBigEndian(helperAddress)); + u256 a(3456789); + u256 b("0x282837623374623234aa74"); + BOOST_REQUIRE(callContractFunction(0, a, b) == toBigEndian(a * b)); +} + +BOOST_AUTO_TEST_CASE(inter_contract_calls_with_complex_parameters) +{ + char const* sourceCode = R"( + contract Helper { + function sel(uint a, bool select, uint b) returns (uint c) { + if (select) return a; else return b; + } + } + contract Main { + Helper h; + function callHelper(uint a, bool select, uint b) returns (uint c) { + return h.sel(a, select, b) * 3; + } + function getHelper() returns (address haddress) { + return address(h); + } + function setHelper(address haddress) { + h = Helper(haddress); + } + })"; + compileAndRun(sourceCode, 0, "Helper"); + u160 const helperAddress = m_contractAddress; + compileAndRun(sourceCode, 0, "Main"); + BOOST_REQUIRE(callContractFunction(2, helperAddress) == bytes()); + BOOST_REQUIRE(callContractFunction(1, helperAddress) == toBigEndian(helperAddress)); + u256 a(3456789); + u256 b("0x282837623374623234aa74"); + BOOST_REQUIRE(callContractFunction(0, a, true, b) == toBigEndian(a * 3)); + BOOST_REQUIRE(callContractFunction(0, a, false, b) == toBigEndian(b * 3)); +} + +BOOST_AUTO_TEST_CASE(inter_contract_calls_accessing_this) +{ + char const* sourceCode = R"( + contract Helper { + function getAddress() returns (address addr) { + return address(this); + } + } + contract Main { + Helper h; + function callHelper() returns (address addr) { + return h.getAddress(); + } + function getHelper() returns (address addr) { + return address(h); + } + function setHelper(address addr) { + h = Helper(addr); + } + })"; + compileAndRun(sourceCode, 0, "Helper"); + u160 const helperAddress = m_contractAddress; + compileAndRun(sourceCode, 0, "Main"); + BOOST_REQUIRE(callContractFunction(2, helperAddress) == bytes()); + BOOST_REQUIRE(callContractFunction(1, helperAddress) == toBigEndian(helperAddress)); + BOOST_REQUIRE(callContractFunction(0) == toBigEndian(helperAddress)); +} + +BOOST_AUTO_TEST_CASE(calls_to_this) +{ + char const* sourceCode = R"( + contract Helper { + function invoke(uint a, uint b) returns (uint c) { + return this.multiply(a, b, 10); + } + function multiply(uint a, uint b, uint8 c) returns (uint ret) { + return a * b + c; + } + } + contract Main { + Helper h; + function callHelper(uint a, uint b) returns (uint ret) { + return h.invoke(a, b); + } + function getHelper() returns (address addr) { + return address(h); + } + function setHelper(address addr) { + h = Helper(addr); + } + })"; + compileAndRun(sourceCode, 0, "Helper"); + u160 const helperAddress = m_contractAddress; + compileAndRun(sourceCode, 0, "Main"); + BOOST_REQUIRE(callContractFunction(2, helperAddress) == bytes()); + BOOST_REQUIRE(callContractFunction(1, helperAddress) == toBigEndian(helperAddress)); + u256 a(3456789); + u256 b("0x282837623374623234aa74"); + BOOST_REQUIRE(callContractFunction(0, a, b) == toBigEndian(a * b + 10)); +} + +BOOST_AUTO_TEST_CASE(inter_contract_calls_with_local_vars) +{ + // note that a reference to another contract's function occupies two stack slots, + // so this tests correct stack slot allocation + char const* sourceCode = R"( + contract Helper { + function multiply(uint a, uint b) returns (uint c) { + return a * b; + } + } + contract Main { + Helper h; + function callHelper(uint a, uint b) returns (uint c) { + var fu = h.multiply; + var y = 9; + var ret = fu(a, b); + return ret + y; + } + function getHelper() returns (address haddress) { + return address(h); + } + function setHelper(address haddress) { + h = Helper(haddress); + } + })"; + compileAndRun(sourceCode, 0, "Helper"); + u160 const helperAddress = m_contractAddress; + compileAndRun(sourceCode, 0, "Main"); + BOOST_REQUIRE(callContractFunction(2, helperAddress) == bytes()); + BOOST_REQUIRE(callContractFunction(1, helperAddress) == toBigEndian(helperAddress)); + u256 a(3456789); + u256 b("0x282837623374623234aa74"); + BOOST_REQUIRE(callContractFunction(0, a, b) == toBigEndian(a * b + 9)); +} + +BOOST_AUTO_TEST_CASE(strings_in_calls) +{ + char const* sourceCode = R"( + contract Helper { + function invoke(string3 x, bool stop) returns (string4 ret) { + return x; + } + } + contract Main { + Helper h; + function callHelper(string2 x, bool stop) returns (string5 ret) { + return h.invoke(x, stop); + } + function getHelper() returns (address addr) { + return address(h); + } + function setHelper(address addr) { + h = Helper(addr); + } + })"; + compileAndRun(sourceCode, 0, "Helper"); + u160 const helperAddress = m_contractAddress; + compileAndRun(sourceCode, 0, "Main"); + BOOST_REQUIRE(callContractFunction(2, helperAddress) == bytes()); + BOOST_REQUIRE(callContractFunction(1, helperAddress) == toBigEndian(helperAddress)); + BOOST_CHECK(callContractFunction(0, bytes({0, 'a', 1})) == bytes({0, 'a', 0, 0, 0})); } BOOST_AUTO_TEST_SUITE_END() diff --git a/test/solidityExecutionFramework.h b/test/solidityExecutionFramework.h new file mode 100644 index 000000000..91ee7ad6a --- /dev/null +++ b/test/solidityExecutionFramework.h @@ -0,0 +1,161 @@ + +/* + This file is part of cpp-ethereum. + + cpp-ethereum is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + cpp-ethereum is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with cpp-ethereum. If not, see . +*/ +/** + * @author Christian + * @date 2014 + * Framework for executing Solidity contracts and testing them against C++ implementation. + */ + +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace dev +{ +/// Provides additional overloads for toBigEndian to encode arguments and return values. +inline bytes toBigEndian(byte _value) { return bytes({_value}); } +inline bytes toBigEndian(bool _value) { return bytes({byte(_value)}); } + +namespace solidity +{ +namespace test +{ + +class ExecutionFramework +{ +public: + ExecutionFramework() { g_logVerbosity = 0; } + + bytes const& compileAndRun(std::string const& _sourceCode, u256 const& _value = 0, std::string const& _contractName = "") + { + dev::solidity::CompilerStack compiler; + compiler.compile(_sourceCode, m_optimize); + bytes code = compiler.getBytecode(_contractName); + sendMessage(code, true, _value); + BOOST_REQUIRE(!m_output.empty()); + return m_output; + } + + bytes const& callContractFunction(byte _index, bytes const& _data = bytes(), u256 const& _value = 0) + { + sendMessage(bytes(1, _index) + _data, false, _value); + return m_output; + } + + template + bytes const& callContractFunction(byte _index, Args const&... _arguments) + { + return callContractFunction(_index, argsToBigEndian(_arguments...)); + } + + template + void testSolidityAgainstCpp(byte _index, CppFunction const& _cppFunction, Args const&... _arguments) + { + bytes solidityResult = callContractFunction(_index, _arguments...); + bytes cppResult = callCppAndEncodeResult(_cppFunction, _arguments...); + BOOST_CHECK_MESSAGE(solidityResult == cppResult, "Computed values do not match." + "\nSolidity: " + toHex(solidityResult) + "\nC++: " + toHex(cppResult)); + } + + template + void testSolidityAgainstCppOnRange(byte _index, CppFunction const& _cppFunction, + u256 const& _rangeStart, u256 const& _rangeEnd) + { + for (u256 argument = _rangeStart; argument < _rangeEnd; ++argument) + { + bytes solidityResult = callContractFunction(_index, argument); + bytes cppResult = callCppAndEncodeResult(_cppFunction, argument); + BOOST_CHECK_MESSAGE(solidityResult == cppResult, "Computed values do not match." + "\nSolidity: " + toHex(solidityResult) + "\nC++: " + toHex(cppResult) + + "\nArgument: " + toHex(toBigEndian(argument))); + } + } + +private: + template + bytes argsToBigEndian(FirstArg const& _firstArg, Args const&... _followingArgs) const + { + return toBigEndian(_firstArg) + argsToBigEndian(_followingArgs...); + } + + bytes argsToBigEndian() const { return bytes(); } + + template + auto callCppAndEncodeResult(CppFunction const& _cppFunction, Args const&... _arguments) + -> typename std::enable_if::value, bytes>::type + { + _cppFunction(_arguments...); + return bytes(); + } + template + auto callCppAndEncodeResult(CppFunction const& _cppFunction, Args const&... _arguments) + -> typename std::enable_if::value, bytes>::type + { + return toBigEndian(_cppFunction(_arguments...)); + } + + void sendMessage(bytes const& _data, bool _isCreation, u256 const& _value = 0) + { + m_state.addBalance(m_sender, _value); // just in case + eth::Executive executive(m_state, 0); + eth::Transaction t = _isCreation ? eth::Transaction(_value, m_gasPrice, m_gas, _data, 0, KeyPair::create().sec()) + : eth::Transaction(_value, m_gasPrice, m_gas, m_contractAddress, _data, 0, KeyPair::create().sec()); + bytes transactionRLP = t.rlp(); + try + { + // this will throw since the transaction is invalid, but it should nevertheless store the transaction + executive.setup(&transactionRLP); + } + catch (...) {} + if (_isCreation) + { + BOOST_REQUIRE(!executive.create(m_sender, _value, m_gasPrice, m_gas, &_data, m_sender)); + m_contractAddress = executive.newAddress(); + BOOST_REQUIRE(m_contractAddress); + BOOST_REQUIRE(m_state.addressHasCode(m_contractAddress)); + } + else + { + BOOST_REQUIRE(m_state.addressHasCode(m_contractAddress)); + BOOST_REQUIRE(!executive.call(m_contractAddress, m_contractAddress, m_sender, _value, m_gasPrice, &_data, m_gas, m_sender)); + } + BOOST_REQUIRE(executive.go()); + m_state.noteSending(m_sender); + executive.finalize(); + m_output = executive.out().toVector(); + } + +protected: + bool m_optimize = false; + Address m_sender; + Address m_contractAddress; + eth::State m_state; + u256 const m_gasPrice = 100 * eth::szabo; + u256 const m_gas = 1000000; + bytes m_output; +}; + +} +} +} // end namespaces + diff --git a/test/solidityExpressionCompiler.cpp b/test/solidityExpressionCompiler.cpp index 59a9e9336..c05db25d4 100644 --- a/test/solidityExpressionCompiler.cpp +++ b/test/solidityExpressionCompiler.cpp @@ -76,8 +76,11 @@ Declaration const& resolveDeclaration(vector const& _namespacedName, NameAndTypeResolver const& _resolver) { Declaration const* declaration = nullptr; + // bracers are required, cause msvc couldnt handle this macro in for statement for (string const& namePart: _namespacedName) + { BOOST_REQUIRE(declaration = _resolver.resolveName(namePart, declaration)); + } BOOST_REQUIRE(declaration); return *declaration; } @@ -86,27 +89,34 @@ bytes compileFirstExpression(const string& _sourceCode, vector> _ vector> _localVariables = {}) { Parser parser; - ASTPointer contract; - BOOST_REQUIRE_NO_THROW(contract = parser.parse(make_shared(CharStream(_sourceCode)))); - NameAndTypeResolver resolver; - BOOST_REQUIRE_NO_THROW(resolver.resolveNamesAndTypes(*contract)); - FirstExpressionExtractor extractor(*contract); - BOOST_REQUIRE(extractor.getExpression() != nullptr); - - CompilerContext context; - for (vector const& function: _functions) - context.addFunction(dynamic_cast(resolveDeclaration(function, resolver))); - for (vector const& variable: _localVariables) - context.addVariable(dynamic_cast(resolveDeclaration(variable, resolver))); - - ExpressionCompiler::compileExpression(context, *extractor.getExpression()); - - for (vector const& function: _functions) - context << context.getFunctionEntryLabel(dynamic_cast(resolveDeclaration(function, resolver))); - bytes instructions = context.getAssembledBytecode(); - // debug - // cout << eth::disassemble(instructions) << endl; - return instructions; + ASTPointer sourceUnit; + BOOST_REQUIRE_NO_THROW(sourceUnit = parser.parse(make_shared(CharStream(_sourceCode)))); + NameAndTypeResolver resolver({}); + resolver.registerDeclarations(*sourceUnit); + for (ASTPointer const& node: sourceUnit->getNodes()) + if (ContractDefinition* contract = dynamic_cast(node.get())) + { + BOOST_REQUIRE_NO_THROW(resolver.resolveNamesAndTypes(*contract)); + FirstExpressionExtractor extractor(*contract); + BOOST_REQUIRE(extractor.getExpression() != nullptr); + + CompilerContext context; + for (vector const& function: _functions) + context.addFunction(dynamic_cast(resolveDeclaration(function, resolver))); + for (vector const& variable: _localVariables) + context.addVariable(dynamic_cast(resolveDeclaration(variable, resolver))); + + ExpressionCompiler::compileExpression(context, *extractor.getExpression()); + + for (vector const& function: _functions) + context << context.getFunctionEntryLabel(dynamic_cast(resolveDeclaration(function, resolver))); + bytes instructions = context.getAssembledBytecode(); + // debug + // cout << eth::disassemble(instructions) << endl; + return instructions; + } + BOOST_FAIL("No contract found in source."); + return bytes(); } } // end anonymous namespace diff --git a/test/solidityJSONInterfaceTest.cpp b/test/solidityJSONInterfaceTest.cpp new file mode 100644 index 000000000..c734009c3 --- /dev/null +++ b/test/solidityJSONInterfaceTest.cpp @@ -0,0 +1,229 @@ +/* + This file is part of cpp-ethereum. + + cpp-ethereum is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + cpp-ethereum is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with cpp-ethereum. If not, see . + */ +/** + * @author Marek Kotewicz + * @date 2014 + * Unit tests for the solidity compiler JSON Interface output. + */ + +#include +#include +#include +#include + +namespace dev +{ +namespace solidity +{ +namespace test +{ + +class InterfaceChecker +{ +public: + void checkInterface(std::string const& _code, std::string const& _expectedInterfaceString) + { + try + { + m_compilerStack.parse(_code); + } + catch (const std::exception& e) + { + std::string const* extra = boost::get_error_info(e); + std::string msg = std::string("Parsing contract failed with: ") + + e.what() + std::string("\n"); + if (extra) + msg += *extra; + BOOST_FAIL(msg); + } + std::string generatedInterfaceString = m_compilerStack.getJsonDocumentation("", DocumentationType::ABI_INTERFACE); + Json::Value generatedInterface; + m_reader.parse(generatedInterfaceString, generatedInterface); + Json::Value expectedInterface; + m_reader.parse(_expectedInterfaceString, expectedInterface); + BOOST_CHECK_MESSAGE(expectedInterface == generatedInterface, + "Expected " << _expectedInterfaceString << + "\n but got:\n" << generatedInterfaceString); + } + +private: + CompilerStack m_compilerStack; + Json::Reader m_reader; +}; + +BOOST_FIXTURE_TEST_SUITE(SolidityABIJSON, InterfaceChecker) + +BOOST_AUTO_TEST_CASE(basic_test) +{ + char const* sourceCode = "contract test {\n" + " function f(uint a) returns(uint d) { return a * 7; }\n" + "}\n"; + + char const* interface = R"([ + { + "name": "f", + "inputs": [ + { + "name": "a", + "type": "uint256" + } + ], + "outputs": [ + { + "name": "d", + "type": "uint256" + } + ] + } + ])"; + + checkInterface(sourceCode, interface); +} + +BOOST_AUTO_TEST_CASE(empty_contract) +{ + char const* sourceCode = "contract test {\n" + "}\n"; + + char const* interface = "[]"; + + checkInterface(sourceCode, interface); +} + +BOOST_AUTO_TEST_CASE(multiple_methods) +{ + char const* sourceCode = "contract test {\n" + " function f(uint a) returns(uint d) { return a * 7; }\n" + " function g(uint b) returns(uint e) { return b * 8; }\n" + "}\n"; + + char const* interface = R"([ + { + "name": "f", + "inputs": [ + { + "name": "a", + "type": "uint256" + } + ], + "outputs": [ + { + "name": "d", + "type": "uint256" + } + ] + }, + { + "name": "g", + "inputs": [ + { + "name": "b", + "type": "uint256" + } + ], + "outputs": [ + { + "name": "e", + "type": "uint256" + } + ] + } + ])"; + + checkInterface(sourceCode, interface); +} + +BOOST_AUTO_TEST_CASE(multiple_params) +{ + char const* sourceCode = "contract test {\n" + " function f(uint a, uint b) returns(uint d) { return a + b; }\n" + "}\n"; + + char const* interface = R"([ + { + "name": "f", + "inputs": [ + { + "name": "a", + "type": "uint256" + }, + { + "name": "b", + "type": "uint256" + } + ], + "outputs": [ + { + "name": "d", + "type": "uint256" + } + ] + } + ])"; + + checkInterface(sourceCode, interface); +} + +BOOST_AUTO_TEST_CASE(multiple_methods_order) +{ + // methods are expected to be in alpabetical order + char const* sourceCode = "contract test {\n" + " function f(uint a) returns(uint d) { return a * 7; }\n" + " function c(uint b) returns(uint e) { return b * 8; }\n" + "}\n"; + + char const* interface = R"([ + { + "name": "c", + "inputs": [ + { + "name": "b", + "type": "uint256" + } + ], + "outputs": [ + { + "name": "e", + "type": "uint256" + } + ] + }, + { + "name": "f", + "inputs": [ + { + "name": "a", + "type": "uint256" + } + ], + "outputs": [ + { + "name": "d", + "type": "uint256" + } + ] + } + ])"; + + checkInterface(sourceCode, interface); +} + +BOOST_AUTO_TEST_SUITE_END() + +} +} +} diff --git a/test/solidityNameAndTypeResolution.cpp b/test/solidityNameAndTypeResolution.cpp index f46ad6733..03eaebb3a 100644 --- a/test/solidityNameAndTypeResolution.cpp +++ b/test/solidityNameAndTypeResolution.cpp @@ -41,10 +41,12 @@ namespace void parseTextAndResolveNames(std::string const& _source) { Parser parser; - ASTPointer contract = parser.parse( - std::make_shared(CharStream(_source))); - NameAndTypeResolver resolver; - resolver.resolveNamesAndTypes(*contract); + ASTPointer sourceUnit = parser.parse(std::make_shared(CharStream(_source))); + NameAndTypeResolver resolver({}); + resolver.registerDeclarations(*sourceUnit); + for (ASTPointer const& node: sourceUnit->getNodes()) + if (ContractDefinition* contract = dynamic_cast(node.get())) + resolver.resolveNamesAndTypes(*contract); } } @@ -121,6 +123,44 @@ BOOST_AUTO_TEST_CASE(reference_to_later_declaration) BOOST_CHECK_NO_THROW(parseTextAndResolveNames(text)); } +BOOST_AUTO_TEST_CASE(struct_definition_directly_recursive) +{ + char const* text = "contract test {\n" + " struct MyStructName {\n" + " address addr;\n" + " MyStructName x;\n" + " }\n" + "}\n"; + BOOST_CHECK_THROW(parseTextAndResolveNames(text), ParserError); +} + +BOOST_AUTO_TEST_CASE(struct_definition_indirectly_recursive) +{ + char const* text = "contract test {\n" + " struct MyStructName1 {\n" + " address addr;\n" + " uint256 count;\n" + " MyStructName2 x;\n" + " }\n" + " struct MyStructName2 {\n" + " MyStructName1 x;\n" + " }\n" + "}\n"; + BOOST_CHECK_THROW(parseTextAndResolveNames(text), ParserError); +} + +BOOST_AUTO_TEST_CASE(struct_definition_recursion_via_mapping) +{ + char const* text = "contract test {\n" + " struct MyStructName1 {\n" + " address addr;\n" + " uint256 count;\n" + " mapping(uint => MyStructName1) x;\n" + " }\n" + "}\n"; + BOOST_CHECK_NO_THROW(parseTextAndResolveNames(text)); +} + BOOST_AUTO_TEST_CASE(type_inference_smoke_test) { char const* text = "contract test {\n" @@ -186,6 +226,64 @@ BOOST_AUTO_TEST_CASE(type_inference_explicit_conversion) BOOST_CHECK_NO_THROW(parseTextAndResolveNames(text)); } +BOOST_AUTO_TEST_CASE(large_string_literal) +{ + char const* text = "contract test {\n" + " function f() { var x = \"123456789012345678901234567890123\"; }" + "}\n"; + BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); +} + +BOOST_AUTO_TEST_CASE(balance) +{ + char const* text = "contract test {\n" + " function fun() {\n" + " uint256 x = address(0).balance;\n" + " }\n" + "}\n"; + BOOST_CHECK_NO_THROW(parseTextAndResolveNames(text)); +} + +BOOST_AUTO_TEST_CASE(balance_invalid) +{ + char const* text = "contract test {\n" + " function fun() {\n" + " address(0).balance = 7;\n" + " }\n" + "}\n"; + BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); +} + +BOOST_AUTO_TEST_CASE(assignment_to_mapping) +{ + char const* text = "contract test {\n" + " struct str {\n" + " mapping(uint=>uint) map;\n" + " }\n" + " str data;" + " function fun() {\n" + " var a = data.map;\n" + " data.map = a;\n" + " }\n" + "}\n"; + BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); +} + +BOOST_AUTO_TEST_CASE(assignment_to_struct) +{ + char const* text = "contract test {\n" + " struct str {\n" + " mapping(uint=>uint) map;\n" + " }\n" + " str data;" + " function fun() {\n" + " var a = data;\n" + " data = a;\n" + " }\n" + "}\n"; + BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); +} + BOOST_AUTO_TEST_SUITE_END() } diff --git a/test/solidityNatspecJSON.cpp b/test/solidityNatspecJSON.cpp new file mode 100644 index 000000000..2c3ded08d --- /dev/null +++ b/test/solidityNatspecJSON.cpp @@ -0,0 +1,488 @@ +/* + This file is part of cpp-ethereum. + + cpp-ethereum is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + cpp-ethereum is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with cpp-ethereum. If not, see . + */ +/** + * @author Lefteris Karapetsas + * @date 2014 + * Unit tests for the solidity compiler JSON Interface output. + */ + +#include +#include +#include +#include +#include + +namespace dev +{ +namespace solidity +{ +namespace test +{ + +class DocumentationChecker +{ +public: + void checkNatspec(std::string const& _code, + std::string const& _expectedDocumentationString, + bool _userDocumentation) + { + std::string generatedDocumentationString; + try + { + m_compilerStack.parse(_code); + } + catch (const std::exception& e) + { + std::string const* extra = boost::get_error_info(e); + std::string msg = std::string("Parsing contract failed with: ") + + e.what() + std::string("\n"); + if (extra) + msg += *extra; + BOOST_FAIL(msg); + } + + if (_userDocumentation) + generatedDocumentationString = m_compilerStack.getJsonDocumentation("", DocumentationType::NATSPEC_USER); + else + generatedDocumentationString = m_compilerStack.getJsonDocumentation("", DocumentationType::NATSPEC_DEV); + Json::Value generatedDocumentation; + m_reader.parse(generatedDocumentationString, generatedDocumentation); + Json::Value expectedDocumentation; + m_reader.parse(_expectedDocumentationString, expectedDocumentation); + BOOST_CHECK_MESSAGE(expectedDocumentation == generatedDocumentation, + "Expected " << _expectedDocumentationString << + "\n but got:\n" << generatedDocumentationString); + } + +private: + CompilerStack m_compilerStack; + Json::Reader m_reader; +}; + +BOOST_FIXTURE_TEST_SUITE(SolidityNatspecJSON, DocumentationChecker) + +BOOST_AUTO_TEST_CASE(user_basic_test) +{ + char const* sourceCode = "contract test {\n" + " /// @notice Multiplies `a` by 7\n" + " function mul(uint a) returns(uint d) { return a * 7; }\n" + "}\n"; + + char const* natspec = "{" + "\"methods\":{" + " \"mul\":{ \"notice\": \"Multiplies `a` by 7\"}" + "}}"; + + checkNatspec(sourceCode, natspec, true); +} + +BOOST_AUTO_TEST_CASE(dev_and_user_basic_test) +{ + char const* sourceCode = "contract test {\n" + " /// @notice Multiplies `a` by 7\n" + " /// @dev Multiplies a number by 7\n" + " function mul(uint a) returns(uint d) { return a * 7; }\n" + "}\n"; + + char const* devNatspec = "{" + "\"methods\":{" + " \"mul\":{ \n" + " \"details\": \"Multiplies a number by 7\"\n" + " }\n" + " }\n" + "}}"; + + char const* userNatspec = "{" + "\"methods\":{" + " \"mul\":{ \"notice\": \"Multiplies `a` by 7\"}" + "}}"; + + checkNatspec(sourceCode, devNatspec, false); + checkNatspec(sourceCode, userNatspec, true); +} + +BOOST_AUTO_TEST_CASE(user_multiline_comment) +{ + char const* sourceCode = "contract test {\n" + " /// @notice Multiplies `a` by 7\n" + " /// and then adds `b`\n" + " function mul_and_add(uint a, uint256 b) returns(uint256 d)\n" + " {\n" + " return (a * 7) + b;\n" + " }\n" + "}\n"; + + char const* natspec = "{" + "\"methods\":{" + " \"mul_and_add\":{ \"notice\": \"Multiplies `a` by 7 and then adds `b`\"}" + "}}"; + + checkNatspec(sourceCode, natspec, true); +} + +BOOST_AUTO_TEST_CASE(user_multiple_functions) +{ + char const* sourceCode = "contract test {\n" + " /// @notice Multiplies `a` by 7 and then adds `b`\n" + " function mul_and_add(uint a, uint256 b) returns(uint256 d)\n" + " {\n" + " return (a * 7) + b;\n" + " }\n" + "\n" + " /// @notice Divides `input` by `div`\n" + " function divide(uint input, uint div) returns(uint d)\n" + " {\n" + " return input / div;\n" + " }\n" + " /// @notice Subtracts 3 from `input`\n" + " function sub(int input) returns(int d)\n" + " {\n" + " return input - 3;\n" + " }\n" + "}\n"; + + char const* natspec = "{" + "\"methods\":{" + " \"mul_and_add\":{ \"notice\": \"Multiplies `a` by 7 and then adds `b`\"}," + " \"divide\":{ \"notice\": \"Divides `input` by `div`\"}," + " \"sub\":{ \"notice\": \"Subtracts 3 from `input`\"}" + "}}"; + + checkNatspec(sourceCode, natspec, true); +} + +BOOST_AUTO_TEST_CASE(user_empty_contract) +{ + char const* sourceCode = "contract test {\n" + "}\n"; + + char const* natspec = "{\"methods\":{} }"; + + checkNatspec(sourceCode, natspec, true); +} + +BOOST_AUTO_TEST_CASE(dev_and_user_no_doc) +{ + char const* sourceCode = "contract test {\n" + " function mul(uint a) returns(uint d) { return a * 7; }\n" + " function sub(int input) returns(int d)\n" + " {\n" + " return input - 3;\n" + " }\n" + "}\n"; + + char const* devNatspec = "{\"methods\":{}}"; + + char const* userNatspec = "{\"methods\":{}}"; + + checkNatspec(sourceCode, devNatspec, false); + checkNatspec(sourceCode, userNatspec, true); +} + +BOOST_AUTO_TEST_CASE(dev_desc_after_nl) +{ + char const* sourceCode = "contract test {\n" + " /// @dev\n" + " /// Multiplies a number by 7 and adds second parameter\n" + " /// @param a Documentation for the first parameter\n" + " /// @param second Documentation for the second parameter\n" + " function mul(uint a, uint second) returns(uint d) { return a * 7 + second; }\n" + "}\n"; + + char const* natspec = "{" + "\"methods\":{" + " \"mul\":{ \n" + " \"details\": \" Multiplies a number by 7 and adds second parameter\",\n" + " \"params\": {\n" + " \"a\": \"Documentation for the first parameter\",\n" + " \"second\": \"Documentation for the second parameter\"\n" + " }\n" + " }\n" + "}}"; + + checkNatspec(sourceCode, natspec, false); +} + +BOOST_AUTO_TEST_CASE(dev_multiple_params) +{ + char const* sourceCode = "contract test {\n" + " /// @dev Multiplies a number by 7 and adds second parameter\n" + " /// @param a Documentation for the first parameter\n" + " /// @param second Documentation for the second parameter\n" + " function mul(uint a, uint second) returns(uint d) { return a * 7 + second; }\n" + "}\n"; + + char const* natspec = "{" + "\"methods\":{" + " \"mul\":{ \n" + " \"details\": \"Multiplies a number by 7 and adds second parameter\",\n" + " \"params\": {\n" + " \"a\": \"Documentation for the first parameter\",\n" + " \"second\": \"Documentation for the second parameter\"\n" + " }\n" + " }\n" + "}}"; + + checkNatspec(sourceCode, natspec, false); +} + +BOOST_AUTO_TEST_CASE(dev_mutiline_param_description) +{ + char const* sourceCode = "contract test {\n" + " /// @dev Multiplies a number by 7 and adds second parameter\n" + " /// @param a Documentation for the first parameter starts here.\n" + " /// Since it's a really complicated parameter we need 2 lines\n" + " /// @param second Documentation for the second parameter\n" + " function mul(uint a, uint second) returns(uint d) { return a * 7 + second; }\n" + "}\n"; + + char const* natspec = "{" + "\"methods\":{" + " \"mul\":{ \n" + " \"details\": \"Multiplies a number by 7 and adds second parameter\",\n" + " \"params\": {\n" + " \"a\": \"Documentation for the first parameter starts here. Since it's a really complicated parameter we need 2 lines\",\n" + " \"second\": \"Documentation for the second parameter\"\n" + " }\n" + " }\n" + "}}"; + + checkNatspec(sourceCode, natspec, false); +} + +BOOST_AUTO_TEST_CASE(dev_multiple_functions) +{ + char const* sourceCode = "contract test {\n" + " /// @dev Multiplies a number by 7 and adds second parameter\n" + " /// @param a Documentation for the first parameter\n" + " /// @param second Documentation for the second parameter\n" + " function mul(uint a, uint second) returns(uint d) { return a * 7 + second; }\n" + " \n" + " /// @dev Divides 2 numbers\n" + " /// @param input Documentation for the input parameter\n" + " /// @param div Documentation for the div parameter\n" + " function divide(uint input, uint div) returns(uint d)\n" + " {\n" + " return input / div;\n" + " }\n" + " /// @dev Subtracts 3 from `input`\n" + " /// @param input Documentation for the input parameter\n" + " function sub(int input) returns(int d)\n" + " {\n" + " return input - 3;\n" + " }\n" + "}\n"; + + char const* natspec = "{" + "\"methods\":{" + " \"mul\":{ \n" + " \"details\": \"Multiplies a number by 7 and adds second parameter\",\n" + " \"params\": {\n" + " \"a\": \"Documentation for the first parameter\",\n" + " \"second\": \"Documentation for the second parameter\"\n" + " }\n" + " },\n" + " \"divide\":{ \n" + " \"details\": \"Divides 2 numbers\",\n" + " \"params\": {\n" + " \"input\": \"Documentation for the input parameter\",\n" + " \"div\": \"Documentation for the div parameter\"\n" + " }\n" + " },\n" + " \"sub\":{ \n" + " \"details\": \"Subtracts 3 from `input`\",\n" + " \"params\": {\n" + " \"input\": \"Documentation for the input parameter\"\n" + " }\n" + " }\n" + "}}"; + + checkNatspec(sourceCode, natspec, false); +} + +BOOST_AUTO_TEST_CASE(dev_return) +{ + char const* sourceCode = "contract test {\n" + " /// @dev Multiplies a number by 7 and adds second parameter\n" + " /// @param a Documentation for the first parameter starts here.\n" + " /// Since it's a really complicated parameter we need 2 lines\n" + " /// @param second Documentation for the second parameter\n" + " /// @return The result of the multiplication\n" + " function mul(uint a, uint second) returns(uint d) { return a * 7 + second; }\n" + "}\n"; + + char const* natspec = "{" + "\"methods\":{" + " \"mul\":{ \n" + " \"details\": \"Multiplies a number by 7 and adds second parameter\",\n" + " \"params\": {\n" + " \"a\": \"Documentation for the first parameter starts here. Since it's a really complicated parameter we need 2 lines\",\n" + " \"second\": \"Documentation for the second parameter\"\n" + " },\n" + " \"return\": \"The result of the multiplication\"\n" + " }\n" + "}}"; + + checkNatspec(sourceCode, natspec, false); +} +BOOST_AUTO_TEST_CASE(dev_return_desc_after_nl) +{ + char const* sourceCode = "contract test {\n" + " /// @dev Multiplies a number by 7 and adds second parameter\n" + " /// @param a Documentation for the first parameter starts here.\n" + " /// Since it's a really complicated parameter we need 2 lines\n" + " /// @param second Documentation for the second parameter\n" + " /// @return\n" + " /// The result of the multiplication\n" + " function mul(uint a, uint second) returns(uint d) { return a * 7 + second; }\n" + "}\n"; + + char const* natspec = "{" + "\"methods\":{" + " \"mul\":{ \n" + " \"details\": \"Multiplies a number by 7 and adds second parameter\",\n" + " \"params\": {\n" + " \"a\": \"Documentation for the first parameter starts here. Since it's a really complicated parameter we need 2 lines\",\n" + " \"second\": \"Documentation for the second parameter\"\n" + " },\n" + " \"return\": \" The result of the multiplication\"\n" + " }\n" + "}}"; + + checkNatspec(sourceCode, natspec, false); +} + + +BOOST_AUTO_TEST_CASE(dev_multiline_return) +{ + char const* sourceCode = "contract test {\n" + " /// @dev Multiplies a number by 7 and adds second parameter\n" + " /// @param a Documentation for the first parameter starts here.\n" + " /// Since it's a really complicated parameter we need 2 lines\n" + " /// @param second Documentation for the second parameter\n" + " /// @return The result of the multiplication\n" + " /// and cookies with nutella\n" + " function mul(uint a, uint second) returns(uint d) { return a * 7 + second; }\n" + "}\n"; + + char const* natspec = "{" + "\"methods\":{" + " \"mul\":{ \n" + " \"details\": \"Multiplies a number by 7 and adds second parameter\",\n" + " \"params\": {\n" + " \"a\": \"Documentation for the first parameter starts here. Since it's a really complicated parameter we need 2 lines\",\n" + " \"second\": \"Documentation for the second parameter\"\n" + " },\n" + " \"return\": \"The result of the multiplication and cookies with nutella\"\n" + " }\n" + "}}"; + + checkNatspec(sourceCode, natspec, false); +} + +BOOST_AUTO_TEST_CASE(dev_contract_no_doc) +{ + char const* sourceCode = "contract test {\n" + " /// @dev Mul function\n" + " function mul(uint a, uint second) returns(uint d) { return a * 7 + second; }\n" + "}\n"; + + char const* natspec = "{" + " \"methods\":{" + " \"mul\":{ \n" + " \"details\": \"Mul function\"\n" + " }\n" + " }\n" + "}"; + + checkNatspec(sourceCode, natspec, false); +} + +BOOST_AUTO_TEST_CASE(dev_contract_doc) +{ + char const* sourceCode = " /// @author Lefteris\n" + " /// @title Just a test contract\n" + "contract test {\n" + " /// @dev Mul function\n" + " function mul(uint a, uint second) returns(uint d) { return a * 7 + second; }\n" + "}\n"; + + char const* natspec = "{" + " \"author\": \"Lefteris\"," + " \"title\": \"Just a test contract\"," + " \"methods\":{" + " \"mul\":{ \n" + " \"details\": \"Mul function\"\n" + " }\n" + " }\n" + "}"; + + checkNatspec(sourceCode, natspec, false); +} + +BOOST_AUTO_TEST_CASE(dev_author_at_function) +{ + char const* sourceCode = " /// @author Lefteris\n" + " /// @title Just a test contract\n" + "contract test {\n" + " /// @dev Mul function\n" + " /// @author John Doe\n" + " function mul(uint a, uint second) returns(uint d) { return a * 7 + second; }\n" + "}\n"; + + char const* natspec = "{" + " \"author\": \"Lefteris\"," + " \"title\": \"Just a test contract\"," + " \"methods\":{" + " \"mul\":{ \n" + " \"details\": \"Mul function\",\n" + " \"author\": \"John Doe\",\n" + " }\n" + " }\n" + "}"; + + checkNatspec(sourceCode, natspec, false); +} + +BOOST_AUTO_TEST_CASE(dev_title_at_function_error) +{ + char const* sourceCode = " /// @author Lefteris\n" + " /// @title Just a test contract\n" + "contract test {\n" + " /// @dev Mul function\n" + " /// @title I really should not be here\n" + " function mul(uint a, uint second) returns(uint d) { return a * 7 + second; }\n" + "}\n"; + + char const* natspec = "{" + " \"author\": \"Lefteris\"," + " \"title\": \"Just a test contract\"," + " \"methods\":{" + " \"mul\":{ \n" + " \"details\": \"Mul function\"\n" + " }\n" + " }\n" + "}"; + + BOOST_CHECK_THROW(checkNatspec(sourceCode, natspec, false), DocstringParsingError); +} + +BOOST_AUTO_TEST_SUITE_END() + +} +} +} diff --git a/test/solidityOptimizerTest.cpp b/test/solidityOptimizerTest.cpp new file mode 100644 index 000000000..388e0579c --- /dev/null +++ b/test/solidityOptimizerTest.cpp @@ -0,0 +1,146 @@ + +/* + This file is part of cpp-ethereum. + + cpp-ethereum is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + cpp-ethereum is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with cpp-ethereum. If not, see . +*/ +/** + * @author Christian + * @date 2014 + * Tests for the Solidity optimizer. + */ + +#include +#include +#include +#include +#include + +using namespace std; + +namespace dev +{ +namespace solidity +{ +namespace test +{ + +class OptimizerTestFramework: public ExecutionFramework +{ +public: + OptimizerTestFramework() { } + /// Compiles the source code with and without optimizing. + void compileBothVersions(unsigned _expectedSizeDecrease, std::string const& _sourceCode, u256 const& _value = 0, std::string const& _contractName = "") { + m_optimize = false; + bytes nonOptimizedBytecode = compileAndRun(_sourceCode, _value, _contractName); + m_nonOptimizedContract = m_contractAddress; + m_optimize = true; + bytes optimizedBytecode = compileAndRun(_sourceCode, _value, _contractName); + int sizeDiff = nonOptimizedBytecode.size() - optimizedBytecode.size(); + BOOST_CHECK_MESSAGE(sizeDiff == int(_expectedSizeDecrease), "Bytecode did only shrink by " + + boost::lexical_cast(sizeDiff) + " bytes, expected: " + + boost::lexical_cast(_expectedSizeDecrease)); + m_optimizedContract = m_contractAddress; + } + + template + void compareVersions(byte _index, Args const&... _arguments) + { + m_contractAddress = m_nonOptimizedContract; + bytes nonOptimizedOutput = callContractFunction(_index, _arguments...); + m_contractAddress = m_optimizedContract; + bytes optimizedOutput = callContractFunction(_index, _arguments...); + BOOST_CHECK_MESSAGE(nonOptimizedOutput == optimizedOutput, "Computed values do not match." + "\nNon-Optimized: " + toHex(nonOptimizedOutput) + + "\nOptimized: " + toHex(optimizedOutput)); + } + +protected: + Address m_optimizedContract; + Address m_nonOptimizedContract; +}; + +BOOST_FIXTURE_TEST_SUITE(SolidityOptimizerTest, OptimizerTestFramework) + +BOOST_AUTO_TEST_CASE(smoke_test) +{ + char const* sourceCode = R"( + contract test { + function f(uint a) returns (uint b) { + return a; + } + })"; + compileBothVersions(4, sourceCode); + compareVersions(0, u256(7)); +} + +BOOST_AUTO_TEST_CASE(large_integers) +{ + char const* sourceCode = R"( + contract test { + function f() returns (uint a, uint b) { + a = 0x234234872642837426347000000; + b = 0x110000000000000000000000002; + } + })"; + compileBothVersions(28, sourceCode); + compareVersions(0); +} + +BOOST_AUTO_TEST_CASE(invariants) +{ + char const* sourceCode = R"( + contract test { + function f(uint a) returns (uint b) { + return (((a + (1 - 1)) ^ 0) | 0) & (uint(0) - 1); + } + })"; + compileBothVersions(28, sourceCode); + compareVersions(0, u256(0x12334664)); +} + +BOOST_AUTO_TEST_CASE(unused_expressions) +{ + char const* sourceCode = R"( + contract test { + uint data; + function f() returns (uint a, uint b) { + 10 + 20; + data; + } + })"; + compileBothVersions(11, sourceCode); + compareVersions(0); +} + +BOOST_AUTO_TEST_CASE(constant_folding_both_sides) +{ + // if constants involving the same associative and commutative operator are applied from both + // sides, the operator should be applied only once, because the expression compiler + // (even in non-optimized mode) pushes literals as late as possible + char const* sourceCode = R"( + contract test { + function f(uint x) returns (uint y) { + return 98 ^ (7 * ((1 | (x | 1000)) * 40) ^ 102); + } + })"; + compileBothVersions(31, sourceCode); + compareVersions(0); +} + +BOOST_AUTO_TEST_SUITE_END() + +} +} +} // end namespaces diff --git a/test/solidityParser.cpp b/test/solidityParser.cpp index 9319a02c5..a9e2d531f 100644 --- a/test/solidityParser.cpp +++ b/test/solidityParser.cpp @@ -21,13 +21,15 @@ */ #include - +#include #include #include #include #include #include +using namespace std; + namespace dev { namespace solidity @@ -37,13 +39,19 @@ namespace test namespace { -ASTPointer parseText(std::string const& _source) +ASTPointer parseText(std::string const& _source) { Parser parser; - return parser.parse(std::make_shared(CharStream(_source))); + ASTPointer sourceUnit = parser.parse(std::make_shared(CharStream(_source))); + for (ASTPointer const& node: sourceUnit->getNodes()) + if (ASTPointer contract = dynamic_pointer_cast(node)) + return contract; + BOOST_FAIL("No contract found in source."); + return ASTPointer(); } } + BOOST_AUTO_TEST_SUITE(SolidityParser) BOOST_AUTO_TEST_CASE(smoke_test) @@ -91,6 +99,164 @@ BOOST_AUTO_TEST_CASE(single_function_param) BOOST_CHECK_NO_THROW(parseText(text)); } +BOOST_AUTO_TEST_CASE(function_natspec_documentation) +{ + ASTPointer contract; + ASTPointer function; + char const* text = "contract test {\n" + " uint256 stateVar;\n" + " /// This is a test function\n" + " function functionName(hash hashin) returns (hash hashout) {}\n" + "}\n"; + BOOST_REQUIRE_NO_THROW(contract = parseText(text)); + auto functions = contract->getDefinedFunctions(); + BOOST_REQUIRE_NO_THROW(function = functions.at(0)); + BOOST_CHECK_EQUAL(*function->getDocumentation(), " This is a test function"); +} + +BOOST_AUTO_TEST_CASE(function_normal_comments) +{ + ASTPointer contract; + ASTPointer function; + char const* text = "contract test {\n" + " uint256 stateVar;\n" + " // We won't see this comment\n" + " function functionName(hash hashin) returns (hash hashout) {}\n" + "}\n"; + BOOST_REQUIRE_NO_THROW(contract = parseText(text)); + auto functions = contract->getDefinedFunctions(); + BOOST_REQUIRE_NO_THROW(function = functions.at(0)); + BOOST_CHECK_MESSAGE(function->getDocumentation() == nullptr, + "Should not have gotten a Natspect comment for this function"); +} + +BOOST_AUTO_TEST_CASE(multiple_functions_natspec_documentation) +{ + ASTPointer contract; + ASTPointer function; + char const* text = "contract test {\n" + " uint256 stateVar;\n" + " /// This is test function 1\n" + " function functionName1(hash hashin) returns (hash hashout) {}\n" + " /// This is test function 2\n" + " function functionName2(hash hashin) returns (hash hashout) {}\n" + " // nothing to see here\n" + " function functionName3(hash hashin) returns (hash hashout) {}\n" + " /// This is test function 4\n" + " function functionName4(hash hashin) returns (hash hashout) {}\n" + "}\n"; + BOOST_REQUIRE_NO_THROW(contract = parseText(text)); + auto functions = contract->getDefinedFunctions(); + + BOOST_REQUIRE_NO_THROW(function = functions.at(0)); + BOOST_CHECK_EQUAL(*function->getDocumentation(), " This is test function 1"); + + BOOST_REQUIRE_NO_THROW(function = functions.at(1)); + BOOST_CHECK_EQUAL(*function->getDocumentation(), " This is test function 2"); + + BOOST_REQUIRE_NO_THROW(function = functions.at(2)); + BOOST_CHECK_MESSAGE(function->getDocumentation() == nullptr, + "Should not have gotten natspec comment for functionName3()"); + + BOOST_REQUIRE_NO_THROW(function = functions.at(3)); + BOOST_CHECK_EQUAL(*function->getDocumentation(), " This is test function 4"); +} + +BOOST_AUTO_TEST_CASE(multiline_function_documentation) +{ + ASTPointer contract; + ASTPointer function; + char const* text = "contract test {\n" + " uint256 stateVar;\n" + " /// This is a test function\n" + " /// and it has 2 lines\n" + " function functionName1(hash hashin) returns (hash hashout) {}\n" + "}\n"; + BOOST_REQUIRE_NO_THROW(contract = parseText(text)); + auto functions = contract->getDefinedFunctions(); + + BOOST_REQUIRE_NO_THROW(function = functions.at(0)); + BOOST_CHECK_EQUAL(*function->getDocumentation(), + " This is a test function\n" + " and it has 2 lines"); +} + +BOOST_AUTO_TEST_CASE(natspec_comment_in_function_body) +{ + ASTPointer contract; + ASTPointer function; + char const* text = "contract test {\n" + " /// fun1 description\n" + " function fun1(uint256 a) {\n" + " var b;\n" + " /// I should not interfere with actual natspec comments\n" + " uint256 c;\n" + " mapping(address=>hash) d;\n" + " string name = \"Solidity\";" + " }\n" + " uint256 stateVar;\n" + " /// This is a test function\n" + " /// and it has 2 lines\n" + " function fun(hash hashin) returns (hash hashout) {}\n" + "}\n"; + BOOST_REQUIRE_NO_THROW(contract = parseText(text)); + auto functions = contract->getDefinedFunctions(); + + BOOST_REQUIRE_NO_THROW(function = functions.at(0)); + BOOST_CHECK_EQUAL(*function->getDocumentation(), " fun1 description"); + + BOOST_REQUIRE_NO_THROW(function = functions.at(1)); + BOOST_CHECK_EQUAL(*function->getDocumentation(), + " This is a test function\n" + " and it has 2 lines"); +} + +BOOST_AUTO_TEST_CASE(natspec_docstring_between_keyword_and_signature) +{ + ASTPointer contract; + ASTPointer function; + char const* text = "contract test {\n" + " uint256 stateVar;\n" + " function ///I am in the wrong place \n" + " fun1(uint256 a) {\n" + " var b;\n" + " /// I should not interfere with actual natspec comments\n" + " uint256 c;\n" + " mapping(address=>hash) d;\n" + " string name = \"Solidity\";" + " }\n" + "}\n"; + BOOST_REQUIRE_NO_THROW(contract = parseText(text)); + auto functions = contract->getDefinedFunctions(); + + BOOST_REQUIRE_NO_THROW(function = functions.at(0)); + BOOST_CHECK_MESSAGE(!function->getDocumentation(), + "Shouldn't get natspec docstring for this function"); +} + +BOOST_AUTO_TEST_CASE(natspec_docstring_after_signature) +{ + ASTPointer contract; + ASTPointer function; + char const* text = "contract test {\n" + " uint256 stateVar;\n" + " function fun1(uint256 a) {\n" + " /// I should have been above the function signature\n" + " var b;\n" + " /// I should not interfere with actual natspec comments\n" + " uint256 c;\n" + " mapping(address=>hash) d;\n" + " string name = \"Solidity\";" + " }\n" + "}\n"; + BOOST_REQUIRE_NO_THROW(contract = parseText(text)); + auto functions = contract->getDefinedFunctions(); + + BOOST_REQUIRE_NO_THROW(function = functions.at(0)); + BOOST_CHECK_MESSAGE(!function->getDocumentation(), + "Shouldn't get natspec docstring for this function"); +} + BOOST_AUTO_TEST_CASE(struct_definition) { char const* text = "contract test {\n" @@ -221,6 +387,50 @@ BOOST_AUTO_TEST_CASE(statement_starting_with_type_conversion) BOOST_CHECK_NO_THROW(parseText(text)); } +BOOST_AUTO_TEST_CASE(import_directive) +{ + char const* text = "import \"abc\";\n" + "contract test {\n" + " function fun() {\n" + " uint64(2);\n" + " }\n" + "}\n"; + BOOST_CHECK_NO_THROW(parseText(text)); +} + +BOOST_AUTO_TEST_CASE(multiple_contracts) +{ + char const* text = "contract test {\n" + " function fun() {\n" + " uint64(2);\n" + " }\n" + "}\n" + "contract test2 {\n" + " function fun() {\n" + " uint64(2);\n" + " }\n" + "}\n"; + BOOST_CHECK_NO_THROW(parseText(text)); +} + +BOOST_AUTO_TEST_CASE(multiple_contracts_and_imports) +{ + char const* text = "import \"abc\";\n" + "contract test {\n" + " function fun() {\n" + " uint64(2);\n" + " }\n" + "}\n" + "import \"def\";\n" + "contract test2 {\n" + " function fun() {\n" + " uint64(2);\n" + " }\n" + "}\n" + "import \"ghi\";\n"; + BOOST_CHECK_NO_THROW(parseText(text)); +} + BOOST_AUTO_TEST_SUITE_END() } diff --git a/test/solidityScanner.cpp b/test/solidityScanner.cpp index d714699a0..573affe6d 100644 --- a/test/solidityScanner.cpp +++ b/test/solidityScanner.cpp @@ -153,6 +153,46 @@ BOOST_AUTO_TEST_CASE(ambiguities) BOOST_CHECK_EQUAL(scanner.next(), Token::SHL); } +BOOST_AUTO_TEST_CASE(documentation_comments_parsed_begin) +{ + Scanner scanner(CharStream("/// Send $(value / 1000) chocolates to the user")); + BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::EOS); + BOOST_CHECK_EQUAL(scanner.getCurrentCommentLiteral(), " Send $(value / 1000) chocolates to the user"); +} + +BOOST_AUTO_TEST_CASE(documentation_comments_parsed) +{ + Scanner scanner(CharStream("some other tokens /// Send $(value / 1000) chocolates to the user")); + BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::IDENTIFIER); + BOOST_CHECK_EQUAL(scanner.next(), Token::IDENTIFIER); + BOOST_CHECK_EQUAL(scanner.next(), Token::IDENTIFIER); + BOOST_CHECK_EQUAL(scanner.next(), Token::EOS); + BOOST_CHECK_EQUAL(scanner.getCurrentCommentLiteral(), " Send $(value / 1000) chocolates to the user"); +} + +BOOST_AUTO_TEST_CASE(comment_before_eos) +{ + Scanner scanner(CharStream("//")); + BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::EOS); + BOOST_CHECK_EQUAL(scanner.getCurrentCommentLiteral(), ""); +} + +BOOST_AUTO_TEST_CASE(documentation_comment_before_eos) +{ + Scanner scanner(CharStream("///")); + BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::EOS); + BOOST_CHECK_EQUAL(scanner.getCurrentCommentLiteral(), ""); +} + +BOOST_AUTO_TEST_CASE(comments_mixed_in_sequence) +{ + Scanner scanner(CharStream("hello_world ///documentation comment \n" + "//simple comment \n" + "<<")); + BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::IDENTIFIER); + BOOST_CHECK_EQUAL(scanner.next(), Token::SHL); + BOOST_CHECK_EQUAL(scanner.getCurrentCommentLiteral(), "documentation comment "); +} BOOST_AUTO_TEST_SUITE_END() diff --git a/test/stExampleFiller.json b/test/stExampleFiller.json new file mode 100644 index 000000000..7acf695ed --- /dev/null +++ b/test/stExampleFiller.json @@ -0,0 +1,37 @@ +{ + "add11" : { + "env" : { + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "currentDifficulty" : "256", + "currentGasLimit" : "1000000", + "currentNumber" : "0", + "currentTimestamp" : 1, + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6" + }, + "pre" : { + "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { + "balance" : "1000000000000000000", + "code" : "0x6001600101600055", + "nonce" : "0", + "storage" : { + } + }, + "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { + "balance" : "1000000000000000000", + "code" : "0x", + "nonce" : "0", + "storage" : { + } + } + }, + "transaction" : { + "data" : "", + "gasLimit" : "10000", + "gasPrice" : "1", + "nonce" : "0", + "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", + "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", + "value" : "100000" + } + } +} diff --git a/test/stLogTestsFiller.json b/test/stLogTestsFiller.json new file mode 100644 index 000000000..34758ff83 --- /dev/null +++ b/test/stLogTestsFiller.json @@ -0,0 +1,1851 @@ +{ + "log0_emptyMem": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ [[ 0 ]] (CALL 1000 0x0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6 23 0 0 0 0) }", + "storage": {} + }, + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (LOG0 0 0) }", + "storage": {} + }, + "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "", + "storage": {} + } + + }, + "transaction" : { + "nonce" : "0", + "gasPrice" : "1", + "gasLimit" : "10000", + "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", + "value" : "100000", + "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", + "data" : "" + } + }, + + "log0_nonEmptyMem": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ [[ 0 ]] (CALL 1000 0x0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6 23 0 0 0 0) }", + "storage": {} + }, + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) (LOG0 0 32) }", + "storage": {} + }, + "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "", + "storage": {} + } + + }, + "transaction" : { + "nonce" : "0", + "gasPrice" : "1", + "gasLimit" : "10000", + "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", + "value" : "100000", + "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", + "data" : "" + } + }, + + "log0_nonEmptyMem_logMemSize1": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ [[ 0 ]] (CALL 1000 0x0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6 23 0 0 0 0) }", + "storage": {} + }, + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG0 0 1) }", + "storage": {} + }, + "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "", + "storage": {} + } + + }, + "transaction" : { + "nonce" : "0", + "gasPrice" : "1", + "gasLimit" : "10000", + "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", + "value" : "100000", + "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", + "data" : "" + } + }, + + + "log0_nonEmptyMem_logMemSize1_logMemStart31": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ [[ 0 ]] (CALL 1000 0x0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6 23 0 0 0 0) }", + "storage": {} + }, + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG0 31 1) }", + "storage": {} + }, + "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "", + "storage": {} + } + + }, + "transaction" : { + "nonce" : "0", + "gasPrice" : "1", + "gasLimit" : "10000", + "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", + "value" : "100000", + "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", + "data" : "" + } + }, + + "log0_logMemStartTooHigh": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ [[ 0 ]] (CALL 1000 0x0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6 23 0 0 0 0) }", + "storage": {} + }, + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG0 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 1) }", + "storage": {} + }, + "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "", + "storage": {} + } + + }, + "transaction" : { + "nonce" : "0", + "gasPrice" : "1", + "gasLimit" : "10000", + "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", + "value" : "100000", + "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", + "data" : "" + } + }, + + "log0_logMemsizeTooHigh": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ [[ 0 ]] (CALL 1000 0x0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6 23 0 0 0 0) }", + "storage": {} + }, + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG0 1 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) }", + "storage": {} + }, + "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "", + "storage": {} + } + + }, + "transaction" : { + "nonce" : "0", + "gasPrice" : "1", + "gasLimit" : "10000", + "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", + "value" : "100000", + "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", + "data" : "" + } + }, + + "log0_logMemsizeZero": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ [[ 0 ]] (CALL 1000 0x0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6 23 0 0 0 0) }", + "storage": {} + }, + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG0 1 0) }", + "storage": {} + }, + "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "", + "storage": {} + } + + }, + "transaction" : { + "nonce" : "0", + "gasPrice" : "1", + "gasLimit" : "10000", + "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", + "value" : "100000", + "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", + "data" : "" + } + }, + + "log1_emptyMem": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ [[ 0 ]] (CALL 1000 0x0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6 23 0 0 0 0) }", + "storage": {} + }, + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (LOG1 0 0 0) }", + "storage": {} + }, + "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "", + "storage": {} + } + + }, + "transaction" : { + "nonce" : "0", + "gasPrice" : "1", + "gasLimit" : "10000", + "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", + "value" : "100000", + "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", + "data" : "" + } + }, + + "log1_nonEmptyMem": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ [[ 0 ]] (CALL 1000 0x0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6 23 0 0 0 0) }", + "storage": {} + }, + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) (LOG1 0 32 0) }", + "storage": {} + }, + "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "", + "storage": {} + } + + }, + "transaction" : { + "nonce" : "0", + "gasPrice" : "1", + "gasLimit" : "10000", + "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", + "value" : "100000", + "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", + "data" : "" + } + }, + + "log1_nonEmptyMem_logMemSize1": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ [[ 0 ]] (CALL 1000 0x0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6 23 0 0 0 0) }", + "storage": {} + }, + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG1 0 1 0) }", + "storage": {} + }, + "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "", + "storage": {} + } + + }, + "transaction" : { + "nonce" : "0", + "gasPrice" : "1", + "gasLimit" : "10000", + "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", + "value" : "100000", + "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", + "data" : "" + } + }, + + + "log1_nonEmptyMem_logMemSize1_logMemStart31": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ [[ 0 ]] (CALL 1000 0x0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6 23 0 0 0 0) }", + "storage": {} + }, + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG1 31 1 0) }", + "storage": {} + }, + "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "", + "storage": {} + } + + }, + "transaction" : { + "nonce" : "0", + "gasPrice" : "1", + "gasLimit" : "10000", + "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", + "value" : "100000", + "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", + "data" : "" + } + }, + + "log1_logMemStartTooHigh": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ [[ 0 ]] (CALL 1000 0x0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6 23 0 0 0 0) }", + "storage": {} + }, + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG1 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 1 0) }", + "storage": {} + }, + "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "", + "storage": {} + } + + }, + "transaction" : { + "nonce" : "0", + "gasPrice" : "1", + "gasLimit" : "10000", + "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", + "value" : "100000", + "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", + "data" : "" + } + }, + + "log1_logMemsizeTooHigh": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ [[ 0 ]] (CALL 1000 0x0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6 23 0 0 0 0) }", + "storage": {} + }, + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG1 1 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 0) }", + "storage": {} + }, + "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "", + "storage": {} + } + + }, + "transaction" : { + "nonce" : "0", + "gasPrice" : "1", + "gasLimit" : "10000", + "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", + "value" : "100000", + "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", + "data" : "" + } + }, + + "log1_logMemsizeZero": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ [[ 0 ]] (CALL 1000 0x0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6 23 0 0 0 0) }", + "storage": {} + }, + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG1 1 0 0) }", + "storage": {} + }, + "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "", + "storage": {} + } + + }, + "transaction" : { + "nonce" : "0", + "gasPrice" : "1", + "gasLimit" : "10000", + "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", + "value" : "100000", + "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", + "data" : "" + } + }, + + "log1_MaxTopic": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ [[ 0 ]] (CALL 1000 0x0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6 23 0 0 0 0) }", + "storage": {} + }, + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG1 0 32 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) }", + "storage": {} + }, + "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "", + "storage": {} + } + + }, + "transaction" : { + "nonce" : "0", + "gasPrice" : "1", + "gasLimit" : "10000", + "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", + "value" : "100000", + "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", + "data" : "" + } + }, + + "log1_Caller": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ [[ 0 ]] (CALL 1000 0x0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6 23 0 0 0 0) }", + "storage": {} + }, + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE8 0 0xff) (LOG1 0 32 (CALLER)) }", + "storage": {} + }, + "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "", + "storage": {} + } + + }, + "transaction" : { + "nonce" : "0", + "gasPrice" : "1", + "gasLimit" : "10000", + "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", + "value" : "100000", + "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", + "data" : "" + } + }, + + "log2_emptyMem": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ [[ 0 ]] (CALL 1000 0x0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6 23 0 0 0 0) }", + "storage": {} + }, + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (LOG2 0 0 0 0) }", + "storage": {} + }, + "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "", + "storage": {} + } + + }, + "transaction" : { + "nonce" : "0", + "gasPrice" : "1", + "gasLimit" : "10000", + "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", + "value" : "100000", + "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", + "data" : "" + } + }, + + "log2_nonEmptyMem": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ [[ 0 ]] (CALL 1000 0x0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6 23 0 0 0 0) }", + "storage": {} + }, + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) (LOG2 0 32 0 0) }", + "storage": {} + }, + "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "", + "storage": {} + } + + }, + "transaction" : { + "nonce" : "0", + "gasPrice" : "1", + "gasLimit" : "10000", + "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", + "value" : "100000", + "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", + "data" : "" + } + }, + + "log2_nonEmptyMem_logMemSize1": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ [[ 0 ]] (CALL 1000 0x0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6 23 0 0 0 0) }", + "storage": {} + }, + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG2 0 1 0 0) }", + "storage": {} + }, + "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "", + "storage": {} + } + + }, + "transaction" : { + "nonce" : "0", + "gasPrice" : "1", + "gasLimit" : "10000", + "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", + "value" : "100000", + "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", + "data" : "" + } + }, + + + "log2_nonEmptyMem_logMemSize1_logMemStart31": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ [[ 0 ]] (CALL 1000 0x0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6 23 0 0 0 0) }", + "storage": {} + }, + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG2 31 1 0 0) }", + "storage": {} + }, + "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "", + "storage": {} + } + + }, + "transaction" : { + "nonce" : "0", + "gasPrice" : "1", + "gasLimit" : "10000", + "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", + "value" : "100000", + "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", + "data" : "" + } + }, + + "log2_logMemStartTooHigh": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ [[ 0 ]] (CALL 1000 0x0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6 23 0 0 0 0) }", + "storage": {} + }, + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG2 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 1 0 0) }", + "storage": {} + }, + "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "", + "storage": {} + } + + }, + "transaction" : { + "nonce" : "0", + "gasPrice" : "1", + "gasLimit" : "10000", + "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", + "value" : "100000", + "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", + "data" : "" + } + }, + + "log2_logMemsizeTooHigh": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ [[ 0 ]] (CALL 1000 0x0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6 23 0 0 0 0) }", + "storage": {} + }, + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG2 1 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 0 0) }", + "storage": {} + }, + "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "", + "storage": {} + } + + }, + "transaction" : { + "nonce" : "0", + "gasPrice" : "1", + "gasLimit" : "10000", + "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", + "value" : "100000", + "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", + "data" : "" + } + }, + + "log2_logMemsizeZero": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ [[ 0 ]] (CALL 1000 0x0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6 23 0 0 0 0) }", + "storage": {} + }, + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG2 1 0 0 0) }", + "storage": {} + }, + "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "", + "storage": {} + } + + }, + "transaction" : { + "nonce" : "0", + "gasPrice" : "1", + "gasLimit" : "10000", + "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", + "value" : "100000", + "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", + "data" : "" + } + }, + + "log2_MaxTopic": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ [[ 0 ]] (CALL 1000 0x0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6 23 0 0 0 0) }", + "storage": {} + }, + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG2 0 32 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) }", + "storage": {} + }, + "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "", + "storage": {} + } + + }, + "transaction" : { + "nonce" : "0", + "gasPrice" : "1", + "gasLimit" : "10000", + "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", + "value" : "100000", + "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", + "data" : "" + } + }, + + "log2_Caller": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ [[ 0 ]] (CALL 1000 0x0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6 23 0 0 0 0) }", + "storage": {} + }, + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE8 0 0xff) (LOG2 0 32 0 (CALLER) ) }", + "storage": {} + }, + "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "", + "storage": {} + } + + }, + "transaction" : { + "nonce" : "0", + "gasPrice" : "1", + "gasLimit" : "10000", + "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", + "value" : "100000", + "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", + "data" : "" + } + }, + + "log3_emptyMem": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ [[ 0 ]] (CALL 1000 0x0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6 23 0 0 0 0) }", + "storage": {} + }, + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (LOG3 0 0 0 0 0) }", + "storage": {} + }, + "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "", + "storage": {} + } + + }, + "transaction" : { + "nonce" : "0", + "gasPrice" : "1", + "gasLimit" : "10000", + "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", + "value" : "100000", + "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", + "data" : "" + } + }, + + "log3_nonEmptyMem": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ [[ 0 ]] (CALL 1000 0x0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6 23 0 0 0 0) }", + "storage": {} + }, + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) (LOG3 0 32 0 0 0) }", + "storage": {} + }, + "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "", + "storage": {} + } + + }, + "transaction" : { + "nonce" : "0", + "gasPrice" : "1", + "gasLimit" : "10000", + "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", + "value" : "100000", + "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", + "data" : "" + } + }, + + "log3_nonEmptyMem_logMemSize1": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ [[ 0 ]] (CALL 1000 0x0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6 23 0 0 0 0) }", + "storage": {} + }, + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG3 0 1 0 0 0) }", + "storage": {} + }, + "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "", + "storage": {} + } + + }, + "transaction" : { + "nonce" : "0", + "gasPrice" : "1", + "gasLimit" : "10000", + "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", + "value" : "100000", + "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", + "data" : "" + } + }, + + + "log3_nonEmptyMem_logMemSize1_logMemStart31": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ [[ 0 ]] (CALL 1000 0x0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6 23 0 0 0 0) }", + "storage": {} + }, + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG3 31 1 0 0 0) }", + "storage": {} + }, + "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "", + "storage": {} + } + + }, + "transaction" : { + "nonce" : "0", + "gasPrice" : "1", + "gasLimit" : "10000", + "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", + "value" : "100000", + "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", + "data" : "" + } + }, + + "log3_logMemStartTooHigh": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ [[ 0 ]] (CALL 1000 0x0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6 23 0 0 0 0) }", + "storage": {} + }, + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG3 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 1 0 0 0) }", + "storage": {} + }, + "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "", + "storage": {} + } + + }, + "transaction" : { + "nonce" : "0", + "gasPrice" : "1", + "gasLimit" : "10000", + "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", + "value" : "100000", + "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", + "data" : "" + } + }, + + "log3_logMemsizeTooHigh": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ [[ 0 ]] (CALL 1000 0x0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6 23 0 0 0 0) }", + "storage": {} + }, + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG3 1 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 0 0 0) }", + "storage": {} + }, + "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "", + "storage": {} + } + + }, + "transaction" : { + "nonce" : "0", + "gasPrice" : "1", + "gasLimit" : "10000", + "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", + "value" : "100000", + "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", + "data" : "" + } + }, + + "log3_logMemsizeZero": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ [[ 0 ]] (CALL 1000 0x0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6 23 0 0 0 0) }", + "storage": {} + }, + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG3 1 0 0 0 0) }", + "storage": {} + }, + "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "", + "storage": {} + } + + }, + "transaction" : { + "nonce" : "0", + "gasPrice" : "1", + "gasLimit" : "10000", + "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", + "value" : "100000", + "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", + "data" : "" + } + }, + + "log3_MaxTopic": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ [[ 0 ]] (CALL 1000 0x0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6 23 0 0 0 0) }", + "storage": {} + }, + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG3 0 32 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) }", + "storage": {} + }, + "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "", + "storage": {} + } + + }, + "transaction" : { + "nonce" : "0", + "gasPrice" : "1", + "gasLimit" : "10000", + "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", + "value" : "100000", + "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", + "data" : "" + } + }, + + "log3_Caller": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ [[ 0 ]] (CALL 1000 0x0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6 23 0 0 0 0) }", + "storage": {} + }, + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE8 0 0xff) (LOG3 0 32 0 0 (CALLER) ) }", + "storage": {} + }, + "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "", + "storage": {} + } + + }, + "transaction" : { + "nonce" : "0", + "gasPrice" : "1", + "gasLimit" : "10000", + "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", + "value" : "100000", + "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", + "data" : "" + } + }, + + "log3_PC": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ [[ 0 ]] (CALL 1000 0x0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6 23 0 0 0 0) }", + "storage": {} + }, + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE8 0 0xff) (LOG3 0 32 (PC) (PC) (PC) ) }", + "storage": {} + }, + "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "", + "storage": {} + } + + }, + "transaction" : { + "nonce" : "0", + "gasPrice" : "1", + "gasLimit" : "10000", + "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", + "value" : "100000", + "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", + "data" : "" + } + }, + + "log4_emptyMem": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ [[ 0 ]] (CALL 1000 0x0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6 23 0 0 0 0) }", + "storage": {} + }, + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (LOG4 0 0 0 0 0 0) }", + "storage": {} + }, + "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "", + "storage": {} + } + + }, + "transaction" : { + "nonce" : "0", + "gasPrice" : "1", + "gasLimit" : "10000", + "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", + "value" : "100000", + "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", + "data" : "" + } + }, + + "log4_nonEmptyMem": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ [[ 0 ]] (CALL 1000 0x0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6 23 0 0 0 0) }", + "storage": {} + }, + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) (LOG4 0 32 0 0 0 0) }", + "storage": {} + }, + "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "", + "storage": {} + } + + }, + "transaction" : { + "nonce" : "0", + "gasPrice" : "1", + "gasLimit" : "10000", + "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", + "value" : "100000", + "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", + "data" : "" + } + }, + + "log4_nonEmptyMem_logMemSize1": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ [[ 0 ]] (CALL 1000 0x0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6 23 0 0 0 0) }", + "storage": {} + }, + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG4 0 1 0 0 0 0) }", + "storage": {} + }, + "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "", + "storage": {} + } + + }, + "transaction" : { + "nonce" : "0", + "gasPrice" : "1", + "gasLimit" : "10000", + "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", + "value" : "100000", + "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", + "data" : "" + } + }, + + + "log4_nonEmptyMem_logMemSize1_logMemStart31": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ [[ 0 ]] (CALL 1000 0x0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6 23 0 0 0 0) }", + "storage": {} + }, + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG4 31 1 0 0 0 0) }", + "storage": {} + }, + "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "", + "storage": {} + } + + }, + "transaction" : { + "nonce" : "0", + "gasPrice" : "1", + "gasLimit" : "10000", + "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", + "value" : "100000", + "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", + "data" : "" + } + }, + + "log4_logMemStartTooHigh": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ [[ 0 ]] (CALL 1000 0x0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6 23 0 0 0 0) }", + "storage": {} + }, + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG4 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 1 0 0 0 0) }", + "storage": {} + }, + "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "", + "storage": {} + } + + }, + "transaction" : { + "nonce" : "0", + "gasPrice" : "1", + "gasLimit" : "10000", + "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", + "value" : "100000", + "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", + "data" : "" + } + }, + + "log4_logMemsizeTooHigh": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ [[ 0 ]] (CALL 1000 0x0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6 23 0 0 0 0) }", + "storage": {} + }, + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG4 1 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 0 0 0 0) }", + "storage": {} + }, + "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "", + "storage": {} + } + + }, + "transaction" : { + "nonce" : "0", + "gasPrice" : "1", + "gasLimit" : "10000", + "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", + "value" : "100000", + "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", + "data" : "" + } + }, + + "log4_logMemsizeZero": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ [[ 0 ]] (CALL 1000 0x0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6 23 0 0 0 0) }", + "storage": {} + }, + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG4 1 0 0 0 0 0) }", + "storage": {} + }, + "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "", + "storage": {} + } + + }, + "transaction" : { + "nonce" : "0", + "gasPrice" : "1", + "gasLimit" : "10000", + "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", + "value" : "100000", + "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", + "data" : "" + } + }, + + "log4_MaxTopic": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ [[ 0 ]] (CALL 1000 0x0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6 23 0 0 0 0) }", + "storage": {} + }, + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG4 0 32 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) }", + "storage": {} + }, + "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "", + "storage": {} + } + + }, + "transaction" : { + "nonce" : "0", + "gasPrice" : "1", + "gasLimit" : "10000", + "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", + "value" : "100000", + "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", + "data" : "" + } + }, + + "log4_Caller": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ [[ 0 ]] (CALL 1000 0x0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6 23 0 0 0 0) }", + "storage": {} + }, + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE8 0 0xff) (LOG3 0 32 0 0 0 (CALLER) ) }", + "storage": {} + }, + "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "", + "storage": {} + } + + }, + "transaction" : { + "nonce" : "0", + "gasPrice" : "1", + "gasLimit" : "10000", + "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", + "value" : "100000", + "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", + "data" : "" + } + }, + + "log4_PC": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ [[ 0 ]] (CALL 1000 0x0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6 23 0 0 0 0) }", + "storage": {} + }, + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE8 0 0xff) (LOG3 0 32 (PC) (PC) (PC) (PC) ) }", + "storage": {} + }, + "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "", + "storage": {} + } + + }, + "transaction" : { + "nonce" : "0", + "gasPrice" : "1", + "gasLimit" : "10000", + "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", + "value" : "100000", + "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", + "data" : "" + } + } +} diff --git a/test/stPreCompiledContractsFiller.json b/test/stPreCompiledContractsFiller.json index bb2b35756..62a3a1623 100644 --- a/test/stPreCompiledContractsFiller.json +++ b/test/stPreCompiledContractsFiller.json @@ -33,6 +33,75 @@ } }, + "CallEcrecover0_overlappingInputOutput": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "10000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { + "balance" : "20000000", + "nonce" : 0, + "code": "{ (MSTORE 0 0x18c547e4f7b0f325ad1e56f57e26c745b09a3e503d86e00e5255ff7f715d3d1c) (MSTORE 32 28) (MSTORE 64 0x73b1693892219d736caba55bdb67216e485557ea6b6af75f37096c9aa6a5a75f) (MSTORE 96 0xeeb940b1d03b21e36b0e47e79769f095fe2ab855bd91e3a38756b7d75a9c4549) [[ 2 ]] (CALL 1000 1 0 0 128 64 32) [[ 0 ]] (MOD (MLOAD 64) (EXP 2 160)) [[ 1 ]] (EQ (ORIGIN) (SLOAD 0)) }", + "storage": {} + }, + "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "", + "storage": {} + } + }, + "transaction" : { + "nonce" : "0", + "gasPrice" : "1", + "gasLimit" : "365224", + "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", + "value" : "100000", + "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", + "data" : "" + } + }, + + + "CallEcrecover0_completeReturnValue": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "10000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { + "balance" : "20000000", + "nonce" : 0, + "code": "{ (MSTORE 0 0x18c547e4f7b0f325ad1e56f57e26c745b09a3e503d86e00e5255ff7f715d3d1c) (MSTORE 32 28) (MSTORE 64 0x73b1693892219d736caba55bdb67216e485557ea6b6af75f37096c9aa6a5a75f) (MSTORE 96 0xeeb940b1d03b21e36b0e47e79769f095fe2ab855bd91e3a38756b7d75a9c4549) [[ 2 ]] (CALL 1000 1 0 0 128 128 32) [[ 0 ]] (MLOAD 128) }", + "storage": {} + }, + "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "", + "storage": {} + } + }, + "transaction" : { + "nonce" : "0", + "gasPrice" : "1", + "gasLimit" : "365224", + "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", + "value" : "100000", + "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", + "data" : "" + } + }, + "CallEcrecover0_gas500": { "env" : { "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", @@ -305,6 +374,40 @@ } }, + "CallSha256_1_nonzeroValue": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "10000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { + "balance" : "20000000", + "nonce" : 0, + "code" : "{ [[ 2 ]] (CALL 500 2 0x13 0 0 0 32) [[ 0 ]] (MLOAD 0)}", + "storage": {} + }, + "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "", + "storage": {} + } + }, + "transaction" : { + "nonce" : "0", + "gasPrice" : "1", + "gasLimit" : "365224", + "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", + "value" : "100000", + "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", + "data" : "" + } + }, + "CallSha256_2": { "env" : { "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", diff --git a/test/stRecursiveCreateFiller.json b/test/stRecursiveCreateFiller.json new file mode 100644 index 000000000..0d18fb7a5 --- /dev/null +++ b/test/stRecursiveCreateFiller.json @@ -0,0 +1,35 @@ +{ + "recursiveCreate": { + "env": { + "previousHash": "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber": "0", + "currentGasLimit": "10000000", + "currentDifficulty": "256", + "currentTimestamp": 1, + "currentCoinbase": "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre": { + "095e7baea6a6c7c4c2dfeb977efac326af552d87": { + "balance": "20000000", + "nonce": 0, + "code": "{(CODECOPY 0 0 32)(CREATE 0 0 32)}", + "storage": {} + }, + "a94f5374fce5edbc8e2a8697c15331677e6ebf0b": { + "balance": "1000000000000000000", + "nonce": 0, + "code": "", + "storage": {} + } + }, + "transaction": { + "nonce": "0", + "gasPrice": "1", + "gasLimit": "465224", + "to": "095e7baea6a6c7c4c2dfeb977efac326af552d87", + "value": "100000", + "secretKey": "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", + "data": "" + } + } +} diff --git a/test/stSpecialTestFiller.json b/test/stSpecialTestFiller.json new file mode 100644 index 000000000..fcb1d74a6 --- /dev/null +++ b/test/stSpecialTestFiller.json @@ -0,0 +1,41 @@ +{ + "makeMoney" : { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0x601080600c6000396000f20060003554156009570060203560003555) (CALL 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec 0xaaaaaaaaace5edbc8e2a8697c15331677e6ebf0b 23 0 0 0 0) }", + "storage": {} + }, + "aaaaaaaaace5edbc8e2a8697c15331677e6ebf0b" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "0x600160015532600255", + "storage": {} + }, + "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { + "balance" : "1000", + "nonce" : 0, + "code" : "", + "storage": {} + } + }, + "transaction" : { + "nonce" : "0", + "gasPrice" : "1", + "gasLimit" : "850", + "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", + "value" : "10", + "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", + "data" : "" + } + } +} diff --git a/test/stSystemOperationsTestFiller.json b/test/stSystemOperationsTestFiller.json index e62753089..9fc8db773 100644 --- a/test/stSystemOperationsTestFiller.json +++ b/test/stSystemOperationsTestFiller.json @@ -12,7 +12,7 @@ "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { "balance" : "1000000000000000000", "nonce" : 0, - "code" : "{ (MSTORE 0 0x601080600c6000396000f20060003554156009570060203560003555) [[ 0 ]] (CREATE 23 4 28) }", + "code" : "{ (MSTORE 0 0x601080600c6000396000f30060003554156009570060203560003555) [[ 0 ]] (CREATE 23 4 28) }", "storage": {} }, "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { @@ -46,7 +46,7 @@ "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { "balance" : "1000000000000000000", "nonce" : 0, - "code" : "{ (MSTORE 0 0x601080600c6000396000f20060003554156009570060203560003555) [[ 0 ]] (CREATE 1000 4 28) }", + "code" : "{ (MSTORE 0 0x601080600c6000396000f30060003554156009570060203560003555) [[ 0 ]] (CREATE 1000 4 28) }", "storage": {} }, "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { @@ -80,7 +80,7 @@ "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { "balance" : "1000000000000000000", "nonce" : 0, - "code" : "{ (MSTORE 0 0x601080600c6000396000f20060003554156009570060203560003555) [[ 0 ]] (CREATE 23 0xfffffffffff 28) }", + "code" : "{ (MSTORE 0 0x601080600c6000396000f30060003554156009570060203560003555) [[ 0 ]] (CREATE 23 0xfffffffffff 28) }", "storage": {} }, "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { @@ -114,7 +114,7 @@ "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { "balance" : "1000000000000000000", "nonce" : 0, - "code" : "{ (MSTORE 0 0x601080600c6000396000f20060003554156009570060203560003555) [[ 0 ]] (CREATE 23 4 0xfffffffffff) }", + "code" : "{ (MSTORE 0 0x601080600c6000396000f30060003554156009570060203560003555) [[ 0 ]] (CREATE 23 4 0xfffffffffff) }", "storage": {} }, "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { @@ -195,7 +195,7 @@ }, "945304eb96065b2a98b57a48a06ae28d285a71b5" : { "balance" : "23", - "code" : "0x6001600155603760005360026000f2", + "code" : "0x6001600155603760005360026000f3", "nonce" : "0", "storage" : { } @@ -321,7 +321,7 @@ }, "945304eb96065b2a98b57a48a06ae28d285a71b5" : { "balance" : "23", - "code" : "0x6001600155603760005360026000f2", + "code" : "0x6001600155603760005360026000f3", "nonce" : "0", "storage" : { } @@ -634,6 +634,86 @@ } }, + "CallRecursiveBombLog": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "10000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { + "balance" : "20000000", + "nonce" : 0, + "code" : "{ (CALL 100000 0x945304eb96065b2a98b57a48a06ae28d285a71b5 23 0 0 0 0) }", + "storage": {} + }, + "945304eb96065b2a98b57a48a06ae28d285a71b5" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) (LOG0 0 32) [[ 0 ]] (+ (SLOAD 0) 1) [[ 1 ]] (CALL (- (GAS) 224) (ADDRESS) 0 0 0 0 0) } ", + "storage": {} + }, + "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "", + "storage": {} + } + }, + "transaction" : { + "nonce" : "0", + "gasPrice" : "1", + "gasLimit" : "1000000", + "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", + "value" : "100000", + "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", + "data" : "" + } + }, + + "CallRecursiveBombLog2": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "10000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { + "balance" : "20000000", + "nonce" : 0, + "code" : "{ (CALL 100000 0x945304eb96065b2a98b57a48a06ae28d285a71b5 23 0 0 0 0) }", + "storage": {} + }, + "945304eb96065b2a98b57a48a06ae28d285a71b5" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 (GAS)) (LOG0 0 32) [[ 0 ]] (+ (SLOAD 0) 1) [[ 1 ]] (CALL (- (GAS) 224) (ADDRESS) 0 0 0 0 0) } ", + "storage": {} + }, + "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "", + "storage": {} + } + }, + "transaction" : { + "nonce" : "0", + "gasPrice" : "1", + "gasLimit" : "1000000", + "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", + "value" : "100000", + "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", + "data" : "" + } + }, + "CallRecursiveBomb1": { "env" : { "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", diff --git a/test/trie.cpp b/test/trie.cpp index 67f706917..0cf87c212 100644 --- a/test/trie.cpp +++ b/test/trie.cpp @@ -54,13 +54,12 @@ BOOST_AUTO_TEST_CASE(trie_tests) { string testPath = test::getTestPath(); - testPath += "/TrieTests"; cnote << "Testing Trie..."; js::mValue v; - string s = asString(contents(testPath + "/trietest.json")); - BOOST_REQUIRE_MESSAGE(s.length() > 0, "Contents of 'trietest.json' is empty. Have you cloned the 'tests' repo branch develop?"); + string s = asString(contents(testPath + "/trieanyorder.json")); + BOOST_REQUIRE_MESSAGE(s.length() > 0, "Contents of 'trieanyorder.json' is empty. Have you cloned the 'tests' repo branch develop?"); js::read_string(s, v); for (auto& i: v.get_obj()) { @@ -88,12 +87,11 @@ BOOST_AUTO_TEST_CASE(trie_tests) BOOST_REQUIRE(t.check(true)); } BOOST_REQUIRE(!o["root"].is_null()); - BOOST_CHECK_EQUAL(o["root"].get_str(), toHex(t.root().asArray())); + BOOST_CHECK_EQUAL(o["root"].get_str(), "0x" + toHex(t.root().asArray())); } } } - inline h256 stringMapHash256(StringMap const& _s) { return hash256(_s); @@ -246,6 +244,7 @@ BOOST_AUTO_TEST_CASE(moreTrieTests) BOOST_AUTO_TEST_CASE(trieLowerBound) { cnote << "Stress-testing Trie.lower_bound..."; + if (0) { MemoryDB dm; EnforceRefs e(dm, true); @@ -291,6 +290,7 @@ BOOST_AUTO_TEST_CASE(trieLowerBound) BOOST_AUTO_TEST_CASE(trieStess) { cnote << "Stress-testing Trie..."; + if (0) { MemoryDB m; MemoryDB dm; diff --git a/test/vm.cpp b/test/vm.cpp index cacbf94cc..49d6ed104 100644 --- a/test/vm.cpp +++ b/test/vm.cpp @@ -21,6 +21,8 @@ */ #include +#include +#include #include "vm.h" using namespace std; @@ -32,18 +34,18 @@ using namespace dev::test; FakeExtVM::FakeExtVM(eth::BlockInfo const& _previousBlock, eth::BlockInfo const& _currentBlock, unsigned _depth): /// TODO: XXX: remove the default argument & fix. ExtVMFace(Address(), Address(), Address(), 0, 1, bytesConstRef(), bytes(), _previousBlock, _currentBlock, _depth) {} -h160 FakeExtVM::create(u256 _endowment, u256* _gas, bytesConstRef _init, OnOpFunc const&) +h160 FakeExtVM::create(u256 _endowment, u256& io_gas, bytesConstRef _init, OnOpFunc const&) { Address na = right160(sha3(rlpList(myAddress, get<1>(addresses[myAddress])))); - Transaction t(_endowment, gasPrice, *_gas, _init.toBytes()); + Transaction t(_endowment, gasPrice, io_gas, _init.toBytes()); callcreates.push_back(t); return na; } -bool FakeExtVM::call(Address _receiveAddress, u256 _value, bytesConstRef _data, u256* _gas, bytesRef _out, OnOpFunc const&, Address _myAddressOverride, Address _codeAddressOverride) +bool FakeExtVM::call(Address _receiveAddress, u256 _value, bytesConstRef _data, u256& io_gas, bytesRef _out, OnOpFunc const&, Address _myAddressOverride, Address _codeAddressOverride) { - Transaction t(_value, gasPrice, *_gas, _receiveAddress, _data.toVector()); + Transaction t(_value, gasPrice, io_gas, _receiveAddress, _data.toVector()); callcreates.push_back(t); (void)_out; (void)_myAddressOverride; @@ -241,10 +243,11 @@ void FakeExtVM::importCallCreates(mArray& _callcreates) eth::OnOpFunc FakeExtVM::simpleTrace() { - return [](uint64_t steps, eth::Instruction inst, bigint newMemSize, bigint gasCost, void* voidVM, void const* voidExt) + + return [](uint64_t steps, eth::Instruction inst, bigint newMemSize, bigint gasCost, dev::eth::VM* voidVM, dev::eth::ExtVMFace const* voidExt) { - FakeExtVM const& ext = *(FakeExtVM const*)voidExt; - eth::VM& vm = *(eth::VM*)voidVM; + FakeExtVM const& ext = *static_cast(voidExt); + eth::VM& vm = *voidVM; std::ostringstream o; o << std::endl << " STACK" << std::endl; @@ -297,18 +300,19 @@ void doVMTests(json_spirit::mValue& v, bool _fillin) } bytes output; - VM vm(fev.gas); + auto vm = eth::VMFactory::create(fev.gas); u256 gas; + bool vmExceptionOccured = false; try { - output = vm.go(fev, fev.simpleTrace()).toVector(); - gas = vm.gas(); + output = vm->go(fev, fev.simpleTrace()).toBytes(); + gas = vm->gas(); } catch (VMException const& _e) { - cnote << "VM did throw an exception: " << diagnostic_information(_e); - gas = 0; + cnote << "Safe VM Exception"; + vmExceptionOccured = true; } catch (Exception const& _e) { @@ -342,48 +346,63 @@ void doVMTests(json_spirit::mValue& v, bool _fillin) { o["env"] = mValue(fev.exportEnv()); o["exec"] = mValue(fev.exportExec()); - o["post"] = mValue(fev.exportState()); - o["callcreates"] = fev.exportCallCreates(); - o["out"] = "0x" + toHex(output); - fev.push(o, "gas", gas); + if (!vmExceptionOccured) + { + o["post"] = mValue(fev.exportState()); + o["callcreates"] = fev.exportCallCreates(); + o["out"] = "0x" + toHex(output); + fev.push(o, "gas", gas); + o["logs"] = exportLog(fev.sub.logs); + } } else { - BOOST_REQUIRE(o.count("post") > 0); - BOOST_REQUIRE(o.count("callcreates") > 0); - BOOST_REQUIRE(o.count("out") > 0); - BOOST_REQUIRE(o.count("gas") > 0); + if (o.count("post") > 0) // No exceptions expected + { + BOOST_CHECK(!vmExceptionOccured); - dev::test::FakeExtVM test; - test.importState(o["post"].get_obj()); - test.importCallCreates(o["callcreates"].get_array()); + BOOST_REQUIRE(o.count("post") > 0); + BOOST_REQUIRE(o.count("callcreates") > 0); + BOOST_REQUIRE(o.count("out") > 0); + BOOST_REQUIRE(o.count("gas") > 0); + BOOST_REQUIRE(o.count("logs") > 0); - checkOutput(output, o); + dev::test::FakeExtVM test; + test.importState(o["post"].get_obj()); + test.importCallCreates(o["callcreates"].get_array()); + test.sub.logs = importLog(o["logs"].get_array()); - BOOST_CHECK_EQUAL(toInt(o["gas"]), gas); + checkOutput(output, o); - auto& expectedAddrs = test.addresses; - auto& resultAddrs = fev.addresses; - for (auto&& expectedPair : expectedAddrs) - { - auto& expectedAddr = expectedPair.first; - auto resultAddrIt = resultAddrs.find(expectedAddr); - if (resultAddrIt == resultAddrs.end()) - BOOST_ERROR("Missing expected address " << expectedAddr); - else - { - auto& expectedState = expectedPair.second; - auto& resultState = resultAddrIt->second; - BOOST_CHECK_MESSAGE(std::get<0>(expectedState) == std::get<0>(resultState), expectedAddr << ": incorrect balance " << std::get<0>(resultState) << ", expected " << std::get<0>(expectedState)); - BOOST_CHECK_MESSAGE(std::get<1>(expectedState) == std::get<1>(resultState), expectedAddr << ": incorrect txCount " << std::get<1>(resultState) << ", expected " << std::get<1>(expectedState)); - BOOST_CHECK_MESSAGE(std::get<3>(expectedState) == std::get<3>(resultState), expectedAddr << ": incorrect code"); + BOOST_CHECK_EQUAL(toInt(o["gas"]), gas); - checkStorage(std::get<2>(expectedState), std::get<2>(resultState), expectedAddr); + auto& expectedAddrs = test.addresses; + auto& resultAddrs = fev.addresses; + for (auto&& expectedPair : expectedAddrs) + { + auto& expectedAddr = expectedPair.first; + auto resultAddrIt = resultAddrs.find(expectedAddr); + if (resultAddrIt == resultAddrs.end()) + BOOST_ERROR("Missing expected address " << expectedAddr); + else + { + auto& expectedState = expectedPair.second; + auto& resultState = resultAddrIt->second; + BOOST_CHECK_MESSAGE(std::get<0>(expectedState) == std::get<0>(resultState), expectedAddr << ": incorrect balance " << std::get<0>(resultState) << ", expected " << std::get<0>(expectedState)); + BOOST_CHECK_MESSAGE(std::get<1>(expectedState) == std::get<1>(resultState), expectedAddr << ": incorrect txCount " << std::get<1>(resultState) << ", expected " << std::get<1>(expectedState)); + BOOST_CHECK_MESSAGE(std::get<3>(expectedState) == std::get<3>(resultState), expectedAddr << ": incorrect code"); + + checkStorage(std::get<2>(expectedState), std::get<2>(resultState), expectedAddr); + } } - } - checkAddresses, bytes> > >(test.addresses, fev.addresses); - BOOST_CHECK(test.callcreates == fev.callcreates); + checkAddresses, bytes> > >(test.addresses, fev.addresses); + BOOST_CHECK(test.callcreates == fev.callcreates); + + checkLog(fev.sub.logs, test.sub.logs); + } + else // Exception expected + BOOST_CHECK(vmExceptionOccured); } } } @@ -432,6 +451,31 @@ BOOST_AUTO_TEST_CASE(vmPushDupSwapTest) dev::test::executeTests("vmPushDupSwapTest", "/VMTests", dev::test::doVMTests); } +BOOST_AUTO_TEST_CASE(vmLogTest) +{ + dev::test::executeTests("vmLogTest", "/VMTests", dev::test::doVMTests); +} + +BOOST_AUTO_TEST_CASE(vmPerformanceTest) +{ + for (int i = 1; i < boost::unit_test::framework::master_test_suite().argc; ++i) + { + string arg = boost::unit_test::framework::master_test_suite().argv[i]; + if (arg == "--performance") + dev::test::executeTests("vmPerformanceTest", "/VMTests", dev::test::doVMTests); + } +} + +BOOST_AUTO_TEST_CASE(vmArithPerformanceTest) +{ + for (int i = 1; i < boost::unit_test::framework::master_test_suite().argc; ++i) + { + string arg = boost::unit_test::framework::master_test_suite().argv[i]; + if (arg == "--performance") + dev::test::executeTests("vmArithPerformanceTest", "/VMTests", dev::test::doVMTests); + } +} + BOOST_AUTO_TEST_CASE(vmRandom) { string testPath = getTestPath(); diff --git a/test/vm.h b/test/vm.h index a52a02e31..ff948cbf8 100644 --- a/test/vm.h +++ b/test/vm.h @@ -55,8 +55,8 @@ public: virtual u256 txCount(Address _a) override { return std::get<1>(addresses[_a]); } virtual void suicide(Address _a) override { std::get<0>(addresses[_a]) += std::get<0>(addresses[myAddress]); addresses.erase(myAddress); } virtual bytes const& codeAt(Address _a) override { return std::get<3>(addresses[_a]); } - virtual h160 create(u256 _endowment, u256* _gas, bytesConstRef _init, eth::OnOpFunc const&) override; - virtual bool call(Address _receiveAddress, u256 _value, bytesConstRef _data, u256* _gas, bytesRef _out, eth::OnOpFunc const&, Address, Address) override; + virtual h160 create(u256 _endowment, u256& io_gas, bytesConstRef _init, eth::OnOpFunc const&) override; + virtual bool call(Address _receiveAddress, u256 _value, bytesConstRef _data, u256& io_gas, bytesRef _out, eth::OnOpFunc const&, Address, Address) override; void setTransaction(Address _caller, u256 _value, u256 _gasPrice, bytes const& _data); void setContract(Address _myAddress, u256 _myBalance, u256 _myNonce, std::map const& _storage, bytes const& _code); void set(Address _a, u256 _myBalance, u256 _myNonce, std::map const& _storage, bytes const& _code); @@ -80,9 +80,6 @@ public: bytes thisTxData; bytes thisTxCode; u256 gas; - -private: - eth::Manifest m_ms; }; diff --git a/test/vmEnvironmentalInfoTestFiller.json b/test/vmEnvironmentalInfoTestFiller.json index 95e7936aa..abeed9945 100644 --- a/test/vmEnvironmentalInfoTestFiller.json +++ b/test/vmEnvironmentalInfoTestFiller.json @@ -338,6 +338,33 @@ } }, + "calldataloadSizeTooHigh": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ [[ 0 ]] (CALLDATALOAD 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa)}", + "storage": {} + } + }, + "exec" : { + "address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", + "origin" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "caller" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "value" : "1000000000000000000", + "data" : "0x123456789abcdef0000000000000000000000000000000000000000000000000024", + "gasPrice" : "1000000000", + "gas" : "100000000000" + } + }, "calldatasize0": { "env" : { @@ -451,6 +478,62 @@ } }, + "calldatacopy_DataIndexTooHigh": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (CALLDATACOPY 0 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa 0xff ) [[ 0 ]] @0}", + "storage": {} + } + }, + "exec" : { + "address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", + "origin" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "caller" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "value" : "1000000000000000000", + "data" : "0x1234567890abcdef01234567890abcdef", + "gasPrice" : "1000000000", + "gas" : "100000000000" + } + }, + + "calldatacopy_DataIndexTooHigh2": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (CALLDATACOPY 0 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa 9 ) [[ 0 ]] @0}", + "storage": {} + } + }, + "exec" : { + "address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", + "origin" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "caller" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "value" : "1000000000000000000", + "data" : "0x1234567890abcdef01234567890abcdef", + "gasPrice" : "1000000000", + "gas" : "100000000000" + } + }, + "calldatacopy1": { "env" : { "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", @@ -535,6 +618,34 @@ } }, + "codecopy_DataIndexTooHigh": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (CODECOPY 0 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa 8 ) [[ 0 ]] @0}", + "storage": {} + } + }, + "exec" : { + "address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", + "origin" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "caller" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "value" : "1000000000000000000", + "data" : "0x1234567890abcdef01234567890abcdef", + "gasPrice" : "1000000000", + "gas" : "100000000000" + } + }, + "codecopy0": { "env" : { "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", @@ -686,6 +797,35 @@ } }, + "extcodecopy_DataIndexTooHigh": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (EXTCODECOPY (ADDRESS) 0 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa 8 ) [[ 0 ]] @0}", + "storage": {} + } + }, + "exec" : { + "address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", + "origin" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "caller" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "value" : "1000000000000000000", + "data" : "0x1234567890abcdef01234567890abcdef", + "gasPrice" : "1000000000", + "gas" : "100000000000" + } + }, + + "extcodecopy0": { "env" : { "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", diff --git a/test/vmIOandFlowOperationsTestFiller.json b/test/vmIOandFlowOperationsTestFiller.json index e2ec1def1..dce594e1e 100644 --- a/test/vmIOandFlowOperationsTestFiller.json +++ b/test/vmIOandFlowOperationsTestFiller.json @@ -55,7 +55,7 @@ } }, - "dupAt51doesNotExistAnymore": { + "dupAt51becameMload": { "env" : { "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", "currentNumber" : "0", @@ -83,7 +83,7 @@ } }, - "swapAt52doesNotExistAnymore": { + "swapAt52becameMstore": { "env" : { "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", "currentNumber" : "0", diff --git a/test/vmLogTestFiller.json b/test/vmLogTestFiller.json new file mode 100644 index 000000000..4f3d26f52 --- /dev/null +++ b/test/vmLogTestFiller.json @@ -0,0 +1,1294 @@ +{ + "log0_emptyMem": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (LOG0 0 0) }", + "storage": {} + } + }, + "exec" : { + "address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", + "origin" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "caller" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "value" : "1000000000000000000", + "data" : "", + "gasPrice" : "100000000000000", + "gas" : "10000" + } + }, + + "log0_nonEmptyMem": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) (LOG0 0 32) }", + "storage": {} + } + }, + "exec" : { + "address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", + "origin" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "caller" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "value" : "1000000000000000000", + "data" : "", + "gasPrice" : "100000000000000", + "gas" : "10000" + } + }, + + "log_2logs": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) (LOG0 0 32) (LOG0 2 16) }", + "storage": {} + } + }, + "exec" : { + "address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", + "origin" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "caller" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "value" : "1000000000000000000", + "data" : "", + "gasPrice" : "100000000000000", + "gas" : "10000" + } + }, + + "log0_nonEmptyMem_logMemSize1": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG0 0 1) }", + "storage": {} + } + }, + "exec" : { + "address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", + "origin" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "caller" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "value" : "1000000000000000000", + "data" : "", + "gasPrice" : "100000000000000", + "gas" : "10000" + } + }, + + + "log0_nonEmptyMem_logMemSize1_logMemStart31": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG0 31 1) }", + "storage": {} + } + }, + "exec" : { + "address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", + "origin" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "caller" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "value" : "1000000000000000000", + "data" : "", + "gasPrice" : "100000000000000", + "gas" : "10000" + } + }, + + "log0_logMemStartTooHigh": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG0 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 1) }", + "storage": {} + } + }, + "exec" : { + "address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", + "origin" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "caller" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "value" : "1000000000000000000", + "data" : "", + "gasPrice" : "100000000000000", + "gas" : "10000" + } + }, + + "log0_logMemsizeTooHigh": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG0 1 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) }", + "storage": {} + } + }, + "exec" : { + "address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", + "origin" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "caller" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "value" : "1000000000000000000", + "data" : "", + "gasPrice" : "100000000000000", + "gas" : "10000" + } + }, + + "log0_logMemsizeZero": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG0 1 0) }", + "storage": {} + } + }, + "exec" : { + "address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", + "origin" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "caller" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "value" : "1000000000000000000", + "data" : "", + "gasPrice" : "100000000000000", + "gas" : "10000" + } + }, + + "log1_emptyMem": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (LOG1 0 0 0) }", + "storage": {} + } + }, + "exec" : { + "address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", + "origin" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "caller" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "value" : "1000000000000000000", + "data" : "", + "gasPrice" : "100000000000000", + "gas" : "10000" + } + }, + + "log1_nonEmptyMem": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) (LOG1 0 32 0) }", + "storage": {} + } + }, + "exec" : { + "address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", + "origin" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "caller" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "value" : "1000000000000000000", + "data" : "", + "gasPrice" : "100000000000000", + "gas" : "10000" + } + }, + + "log1_nonEmptyMem_logMemSize1": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG1 0 1 0) }", + "storage": {} + } + }, + "exec" : { + "address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", + "origin" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "caller" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "value" : "1000000000000000000", + "data" : "", + "gasPrice" : "100000000000000", + "gas" : "10000" + } + }, + + + "log1_nonEmptyMem_logMemSize1_logMemStart31": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG1 31 1 0) }", + "storage": {} + } + }, + "exec" : { + "address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", + "origin" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "caller" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "value" : "1000000000000000000", + "data" : "", + "gasPrice" : "100000000000000", + "gas" : "10000" + } + }, + + "log1_logMemStartTooHigh": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG1 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 1 0) }", + "storage": {} + } + }, + "exec" : { + "address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", + "origin" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "caller" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "value" : "1000000000000000000", + "data" : "", + "gasPrice" : "100000000000000", + "gas" : "10000" + } + }, + + "log1_logMemsizeTooHigh": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG1 1 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 0) }", + "storage": {} + } + }, + "exec" : { + "address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", + "origin" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "caller" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "value" : "1000000000000000000", + "data" : "", + "gasPrice" : "100000000000000", + "gas" : "10000" + } + }, + + "log1_logMemsizeZero": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG1 1 0 0) }", + "storage": {} + } + }, + "exec" : { + "address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", + "origin" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "caller" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "value" : "1000000000000000000", + "data" : "", + "gasPrice" : "100000000000000", + "gas" : "10000" + } + }, + + "log1_MaxTopic": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG1 0 32 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) }", + "storage": {} + } + }, + "exec" : { + "address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", + "origin" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "caller" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "value" : "1000000000000000000", + "data" : "", + "gasPrice" : "100000000000000", + "gas" : "10000" + } + }, + + "log1_Caller": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE8 0 0xff) (LOG1 0 32 (CALLER)) }", + "storage": {} + } + }, + "exec" : { + "address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", + "origin" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "caller" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "value" : "1000000000000000000", + "data" : "", + "gasPrice" : "100000000000000", + "gas" : "10000" + } + }, + + "log2_emptyMem": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (LOG2 0 0 0 0) }", + "storage": {} + } + }, + "exec" : { + "address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", + "origin" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "caller" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "value" : "1000000000000000000", + "data" : "", + "gasPrice" : "100000000000000", + "gas" : "10000" + } + }, + + "log2_nonEmptyMem": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) (LOG2 0 32 0 0) }", + "storage": {} + } + }, + "exec" : { + "address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", + "origin" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "caller" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "value" : "1000000000000000000", + "data" : "", + "gasPrice" : "100000000000000", + "gas" : "10000" + } + }, + + "log2_nonEmptyMem_logMemSize1": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG2 0 1 0 0) }", + "storage": {} + } + }, + "exec" : { + "address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", + "origin" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "caller" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "value" : "1000000000000000000", + "data" : "", + "gasPrice" : "100000000000000", + "gas" : "10000" + } + }, + + + "log2_nonEmptyMem_logMemSize1_logMemStart31": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG2 31 1 0 0) }", + "storage": {} + } + }, + "exec" : { + "address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", + "origin" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "caller" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "value" : "1000000000000000000", + "data" : "", + "gasPrice" : "100000000000000", + "gas" : "10000" + } + }, + + "log2_logMemStartTooHigh": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG2 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 1 0 0) }", + "storage": {} + } + }, + "exec" : { + "address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", + "origin" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "caller" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "value" : "1000000000000000000", + "data" : "", + "gasPrice" : "100000000000000", + "gas" : "10000" + } + }, + + "log2_logMemsizeTooHigh": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG2 1 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 0 0) }", + "storage": {} + } + }, + "exec" : { + "address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", + "origin" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "caller" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "value" : "1000000000000000000", + "data" : "", + "gasPrice" : "100000000000000", + "gas" : "10000" + } + }, + + "log2_logMemsizeZero": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG2 1 0 0 0) }", + "storage": {} + } + }, + "exec" : { + "address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", + "origin" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "caller" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "value" : "1000000000000000000", + "data" : "", + "gasPrice" : "100000000000000", + "gas" : "10000" + } + }, + + "log2_MaxTopic": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG2 0 32 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) }", + "storage": {} + } + }, + "exec" : { + "address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", + "origin" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "caller" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "value" : "1000000000000000000", + "data" : "", + "gasPrice" : "100000000000000", + "gas" : "10000" + } + }, + + "log2_Caller": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE8 0 0xff) (LOG2 0 32 0 (CALLER) ) }", + "storage": {} + } + }, + "exec" : { + "address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", + "origin" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "caller" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "value" : "1000000000000000000", + "data" : "", + "gasPrice" : "100000000000000", + "gas" : "10000" + } + }, + + "log3_emptyMem": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (LOG3 0 0 0 0 0) }", + "storage": {} + } + }, + "exec" : { + "address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", + "origin" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "caller" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "value" : "1000000000000000000", + "data" : "", + "gasPrice" : "100000000000000", + "gas" : "10000" + } + }, + + "log3_nonEmptyMem": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) (LOG3 0 32 0 0 0) }", + "storage": {} + } + }, + "exec" : { + "address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", + "origin" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "caller" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "value" : "1000000000000000000", + "data" : "", + "gasPrice" : "100000000000000", + "gas" : "10000" + } + }, + + "log3_nonEmptyMem_logMemSize1": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG3 0 1 0 0 0) }", + "storage": {} + } + }, + "exec" : { + "address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", + "origin" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "caller" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "value" : "1000000000000000000", + "data" : "", + "gasPrice" : "100000000000000", + "gas" : "10000" + } + }, + + + "log3_nonEmptyMem_logMemSize1_logMemStart31": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG3 31 1 0 0 0) }", + "storage": {} + } + }, + "exec" : { + "address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", + "origin" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "caller" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "value" : "1000000000000000000", + "data" : "", + "gasPrice" : "100000000000000", + "gas" : "10000" + } + }, + + "log3_logMemStartTooHigh": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG3 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 1 0 0 0) }", + "storage": {} + } + }, + "exec" : { + "address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", + "origin" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "caller" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "value" : "1000000000000000000", + "data" : "", + "gasPrice" : "100000000000000", + "gas" : "10000" + } + }, + + "log3_logMemsizeTooHigh": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG3 1 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 0 0 0) }", + "storage": {} + } + }, + "exec" : { + "address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", + "origin" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "caller" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "value" : "1000000000000000000", + "data" : "", + "gasPrice" : "100000000000000", + "gas" : "10000" + } + }, + + "log3_logMemsizeZero": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG3 1 0 0 0 0) }", + "storage": {} + } + }, + "exec" : { + "address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", + "origin" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "caller" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "value" : "1000000000000000000", + "data" : "", + "gasPrice" : "100000000000000", + "gas" : "10000" + } + }, + + "log3_MaxTopic": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG3 0 32 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) }", + "storage": {} + } + }, + "exec" : { + "address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", + "origin" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "caller" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "value" : "1000000000000000000", + "data" : "", + "gasPrice" : "100000000000000", + "gas" : "10000" + } + }, + + "log3_Caller": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE8 0 0xff) (LOG3 0 32 0 0 (CALLER) ) }", + "storage": {} + } + }, + "exec" : { + "address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", + "origin" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "caller" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "value" : "1000000000000000000", + "data" : "", + "gasPrice" : "100000000000000", + "gas" : "10000" + } + }, + + "log3_PC": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE8 0 0xff) (LOG3 0 32 (PC) (PC) (PC) ) }", + "storage": {} + } + }, + "exec" : { + "address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", + "origin" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "caller" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "value" : "1000000000000000000", + "data" : "", + "gasPrice" : "100000000000000", + "gas" : "10000" + } + }, + + "log4_emptyMem": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (LOG4 0 0 0 0 0 0) }", + "storage": {} + } + }, + "exec" : { + "address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", + "origin" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "caller" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "value" : "1000000000000000000", + "data" : "", + "gasPrice" : "100000000000000", + "gas" : "10000" + } + }, + + "log4_nonEmptyMem": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) (LOG4 0 32 0 0 0 0) }", + "storage": {} + } + }, + "exec" : { + "address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", + "origin" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "caller" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "value" : "1000000000000000000", + "data" : "", + "gasPrice" : "100000000000000", + "gas" : "10000" + } + }, + + "log4_nonEmptyMem_logMemSize1": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG4 0 1 0 0 0 0) }", + "storage": {} + } + }, + "exec" : { + "address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", + "origin" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "caller" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "value" : "1000000000000000000", + "data" : "", + "gasPrice" : "100000000000000", + "gas" : "10000" + } + }, + + + "log4_nonEmptyMem_logMemSize1_logMemStart31": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG4 31 1 0 0 0 0) }", + "storage": {} + } + }, + "exec" : { + "address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", + "origin" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "caller" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "value" : "1000000000000000000", + "data" : "", + "gasPrice" : "100000000000000", + "gas" : "10000" + } + }, + + "log4_logMemStartTooHigh": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG4 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 1 0 0 0 0) }", + "storage": {} + } + }, + "exec" : { + "address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", + "origin" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "caller" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "value" : "1000000000000000000", + "data" : "", + "gasPrice" : "100000000000000", + "gas" : "10000" + } + }, + + "log4_logMemsizeTooHigh": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG4 1 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 0 0 0 0) }", + "storage": {} + } + }, + "exec" : { + "address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", + "origin" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "caller" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "value" : "1000000000000000000", + "data" : "", + "gasPrice" : "100000000000000", + "gas" : "10000" + } + }, + + "log4_logMemsizeZero": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG4 1 0 0 0 0 0) }", + "storage": {} + } + }, + "exec" : { + "address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", + "origin" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "caller" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "value" : "1000000000000000000", + "data" : "", + "gasPrice" : "100000000000000", + "gas" : "10000" + } + }, + + "log4_MaxTopic": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE 0 0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd) (LOG4 0 32 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) }", + "storage": {} + } + }, + "exec" : { + "address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", + "origin" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "caller" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "value" : "1000000000000000000", + "data" : "", + "gasPrice" : "100000000000000", + "gas" : "10000" + } + }, + + "log4_Caller": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE8 0 0xff) (LOG3 0 32 0 0 0 (CALLER) ) }", + "storage": {} + } + }, + "exec" : { + "address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", + "origin" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "caller" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "value" : "1000000000000000000", + "data" : "", + "gasPrice" : "100000000000000", + "gas" : "10000" + } + }, + + "log4_PC": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "{ (MSTORE8 0 0xff) (LOG3 0 32 (PC) (PC) (PC) (PC) ) }", + "storage": {} + } + }, + "exec" : { + "address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", + "origin" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "caller" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "value" : "1000000000000000000", + "data" : "", + "gasPrice" : "100000000000000", + "gas" : "10000" + } + } +} diff --git a/test/vmPushDupSwapTestFiller.json b/test/vmPushDupSwapTestFiller.json index 3fc7e4a79..69d0254b7 100644 --- a/test/vmPushDupSwapTestFiller.json +++ b/test/vmPushDupSwapTestFiller.json @@ -924,7 +924,7 @@ } }, - "push32error": { + "push32AndSuicide": { "env" : { "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", "currentNumber" : "0", @@ -952,6 +952,35 @@ } }, + + "push32FillUpInputWithZerosAtTheEnd": { + "env" : { + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", + "currentNumber" : "0", + "currentGasLimit" : "1000000", + "currentDifficulty" : "256", + "currentTimestamp" : 1, + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" + }, + "pre" : { + "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { + "balance" : "1000000000000000000", + "nonce" : 0, + "code" : "0x7fff10112233445566778899aabbccddeeff00112233445566778899aabbccdd", + "storage": {} + } + }, + "exec" : { + "address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", + "origin" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "caller" : "cd1722f3947def4cf144679da39c4c32bdc35681", + "value" : "1000000000000000000", + "data" : "", + "gasPrice" : "100000000000000", + "gas" : "10000" + } + }, + "dup1": { "env" : { "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6", diff --git a/test/webthreestubclient.h b/test/webthreestubclient.h index 179c620a7..9b36c3644 100644 --- a/test/webthreestubclient.h +++ b/test/webthreestubclient.h @@ -1,588 +1,500 @@ /** - * THIS FILE IS GENERATED BY jsonrpcstub, DO NOT CHANGE IT!!!!! + * This file is generated by jsonrpcstub, DO NOT CHANGE IT MANUALLY! */ -#ifndef _WEBTHREESTUBCLIENT_H_ -#define _WEBTHREESTUBCLIENT_H_ +#ifndef JSONRPC_CPP_STUB_WEBTHREESTUBCLIENT_H_ +#define JSONRPC_CPP_STUB_WEBTHREESTUBCLIENT_H_ -#include +#include -class WebThreeStubClient +class WebThreeStubClient : public jsonrpc::Client { public: - WebThreeStubClient(jsonrpc::AbstractClientConnector* conn) + WebThreeStubClient(jsonrpc::IClientConnector &conn) : jsonrpc::Client(conn) {} + + std::string eth_coinbase() throw (jsonrpc::JsonRpcException) { - this->client = new jsonrpc::Client(conn); + Json::Value p; + p = Json::nullValue; + Json::Value result = this->CallMethod("eth_coinbase",p); + if (result.isString()) + return result.asString(); + else + throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); } - ~WebThreeStubClient() + bool eth_setCoinbase(const std::string& param1) throw (jsonrpc::JsonRpcException) { - delete this->client; + Json::Value p; + p.append(param1); + Json::Value result = this->CallMethod("eth_setCoinbase",p); + if (result.isBool()) + return result.asBool(); + else + throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); } - - std::string db_get(const std::string& param1, const std::string& param2) throw (jsonrpc::JsonRpcException) + bool eth_listening() throw (jsonrpc::JsonRpcException) { Json::Value p; - p.append(param1); -p.append(param2); - - Json::Value result = this->client->CallMethod("db_get",p); - if (result.isString()) - return result.asString(); - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - + p = Json::nullValue; + Json::Value result = this->CallMethod("eth_listening",p); + if (result.isBool()) + return result.asBool(); + else + throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); } - - std::string db_getString(const std::string& param1, const std::string& param2) throw (jsonrpc::JsonRpcException) + bool eth_setListening(const bool& param1) throw (jsonrpc::JsonRpcException) { Json::Value p; p.append(param1); -p.append(param2); - - Json::Value result = this->client->CallMethod("db_getString",p); - if (result.isString()) - return result.asString(); - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - + Json::Value result = this->CallMethod("eth_setListening",p); + if (result.isBool()) + return result.asBool(); + else + throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); } - - bool db_put(const std::string& param1, const std::string& param2, const std::string& param3) throw (jsonrpc::JsonRpcException) + bool eth_mining() throw (jsonrpc::JsonRpcException) { Json::Value p; - p.append(param1); -p.append(param2); -p.append(param3); - - Json::Value result = this->client->CallMethod("db_put",p); - if (result.isBool()) - return result.asBool(); - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - + p = Json::nullValue; + Json::Value result = this->CallMethod("eth_mining",p); + if (result.isBool()) + return result.asBool(); + else + throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); } - - bool db_putString(const std::string& param1, const std::string& param2, const std::string& param3) throw (jsonrpc::JsonRpcException) + bool eth_setMining(const bool& param1) throw (jsonrpc::JsonRpcException) { Json::Value p; p.append(param1); -p.append(param2); -p.append(param3); - - Json::Value result = this->client->CallMethod("db_putString",p); - if (result.isBool()) - return result.asBool(); - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - + Json::Value result = this->CallMethod("eth_setMining",p); + if (result.isBool()) + return result.asBool(); + else + throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); } - - Json::Value eth_accounts() throw (jsonrpc::JsonRpcException) + std::string eth_gasPrice() throw (jsonrpc::JsonRpcException) { Json::Value p; p = Json::nullValue; - Json::Value result = this->client->CallMethod("eth_accounts",p); - if (result.isArray()) - return result; - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - + Json::Value result = this->CallMethod("eth_gasPrice",p); + if (result.isString()) + return result.asString(); + else + throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); } - - std::string eth_balanceAt(const std::string& param1) throw (jsonrpc::JsonRpcException) + Json::Value eth_accounts() throw (jsonrpc::JsonRpcException) { Json::Value p; - p.append(param1); - - Json::Value result = this->client->CallMethod("eth_balanceAt",p); - if (result.isString()) - return result.asString(); - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - + p = Json::nullValue; + Json::Value result = this->CallMethod("eth_accounts",p); + if (result.isArray()) + return result; + else + throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); } - - Json::Value eth_blockByHash(const std::string& param1) throw (jsonrpc::JsonRpcException) + int eth_peerCount() throw (jsonrpc::JsonRpcException) { Json::Value p; - p.append(param1); - - Json::Value result = this->client->CallMethod("eth_blockByHash",p); - if (result.isObject()) - return result; - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - + p = Json::nullValue; + Json::Value result = this->CallMethod("eth_peerCount",p); + if (result.isInt()) + return result.asInt(); + else + throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); } - - Json::Value eth_blockByNumber(const int& param1) throw (jsonrpc::JsonRpcException) + int eth_defaultBlock() throw (jsonrpc::JsonRpcException) { Json::Value p; - p.append(param1); - - Json::Value result = this->client->CallMethod("eth_blockByNumber",p); - if (result.isObject()) - return result; - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - + p = Json::nullValue; + Json::Value result = this->CallMethod("eth_defaultBlock",p); + if (result.isInt()) + return result.asInt(); + else + throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); } - - std::string eth_call(const Json::Value& param1) throw (jsonrpc::JsonRpcException) + bool eth_setDefaultBlock(const int& param1) throw (jsonrpc::JsonRpcException) { Json::Value p; p.append(param1); - - Json::Value result = this->client->CallMethod("eth_call",p); - if (result.isString()) - return result.asString(); - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - + Json::Value result = this->CallMethod("eth_setDefaultBlock",p); + if (result.isBool()) + return result.asBool(); + else + throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); } - - bool eth_changed(const int& param1) throw (jsonrpc::JsonRpcException) + int eth_number() throw (jsonrpc::JsonRpcException) { Json::Value p; - p.append(param1); - - Json::Value result = this->client->CallMethod("eth_changed",p); - if (result.isBool()) - return result.asBool(); - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - + p = Json::nullValue; + Json::Value result = this->CallMethod("eth_number",p); + if (result.isInt()) + return result.asInt(); + else + throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); } - - std::string eth_codeAt(const std::string& param1) throw (jsonrpc::JsonRpcException) + std::string eth_balanceAt(const std::string& param1) throw (jsonrpc::JsonRpcException) { Json::Value p; p.append(param1); - - Json::Value result = this->client->CallMethod("eth_codeAt",p); - if (result.isString()) - return result.asString(); - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - + Json::Value result = this->CallMethod("eth_balanceAt",p); + if (result.isString()) + return result.asString(); + else + throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); } - - std::string eth_coinbase() throw (jsonrpc::JsonRpcException) + std::string eth_stateAt(const std::string& param1, const std::string& param2) throw (jsonrpc::JsonRpcException) { Json::Value p; - p = Json::nullValue; - Json::Value result = this->client->CallMethod("eth_coinbase",p); - if (result.isString()) - return result.asString(); - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - + p.append(param1); + p.append(param2); + Json::Value result = this->CallMethod("eth_stateAt",p); + if (result.isString()) + return result.asString(); + else + throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); } - - std::string eth_compile(const std::string& param1) throw (jsonrpc::JsonRpcException) + Json::Value eth_storageAt(const std::string& param1) throw (jsonrpc::JsonRpcException) { Json::Value p; p.append(param1); - - Json::Value result = this->client->CallMethod("eth_compile",p); - if (result.isString()) - return result.asString(); - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - + Json::Value result = this->CallMethod("eth_storageAt",p); + if (result.isObject()) + return result; + else + throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); } - double eth_countAt(const std::string& param1) throw (jsonrpc::JsonRpcException) { Json::Value p; p.append(param1); - - Json::Value result = this->client->CallMethod("eth_countAt",p); - if (result.isDouble()) - return result.asDouble(); - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - + Json::Value result = this->CallMethod("eth_countAt",p); + if (result.isDouble()) + return result.asDouble(); + else + throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); } - - int eth_defaultBlock() throw (jsonrpc::JsonRpcException) + std::string eth_codeAt(const std::string& param1) throw (jsonrpc::JsonRpcException) { Json::Value p; - p = Json::nullValue; - Json::Value result = this->client->CallMethod("eth_defaultBlock",p); - if (result.isInt()) - return result.asInt(); - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - + p.append(param1); + Json::Value result = this->CallMethod("eth_codeAt",p); + if (result.isString()) + return result.asString(); + else + throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); } - - std::string eth_gasPrice() throw (jsonrpc::JsonRpcException) + std::string eth_transact(const Json::Value& param1) throw (jsonrpc::JsonRpcException) { Json::Value p; - p = Json::nullValue; - Json::Value result = this->client->CallMethod("eth_gasPrice",p); - if (result.isString()) - return result.asString(); - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - + p.append(param1); + Json::Value result = this->CallMethod("eth_transact",p); + if (result.isString()) + return result.asString(); + else + throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); } - - Json::Value eth_getMessages(const int& param1) throw (jsonrpc::JsonRpcException) + std::string eth_call(const Json::Value& param1) throw (jsonrpc::JsonRpcException) { Json::Value p; p.append(param1); - - Json::Value result = this->client->CallMethod("eth_getMessages",p); - if (result.isArray()) - return result; - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - + Json::Value result = this->CallMethod("eth_call",p); + if (result.isString()) + return result.asString(); + else + throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); } - - bool eth_listening() throw (jsonrpc::JsonRpcException) + Json::Value eth_blockByHash(const std::string& param1) throw (jsonrpc::JsonRpcException) { Json::Value p; - p = Json::nullValue; - Json::Value result = this->client->CallMethod("eth_listening",p); - if (result.isBool()) - return result.asBool(); - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - + p.append(param1); + Json::Value result = this->CallMethod("eth_blockByHash",p); + if (result.isObject()) + return result; + else + throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); } - - std::string eth_lll(const std::string& param1) throw (jsonrpc::JsonRpcException) + Json::Value eth_blockByNumber(const int& param1) throw (jsonrpc::JsonRpcException) { Json::Value p; p.append(param1); - - Json::Value result = this->client->CallMethod("eth_lll",p); - if (result.isString()) - return result.asString(); - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - + Json::Value result = this->CallMethod("eth_blockByNumber",p); + if (result.isObject()) + return result; + else + throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); } - - bool eth_mining() throw (jsonrpc::JsonRpcException) + Json::Value eth_transactionByHash(const std::string& param1, const int& param2) throw (jsonrpc::JsonRpcException) { Json::Value p; - p = Json::nullValue; - Json::Value result = this->client->CallMethod("eth_mining",p); - if (result.isBool()) - return result.asBool(); - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - + p.append(param1); + p.append(param2); + Json::Value result = this->CallMethod("eth_transactionByHash",p); + if (result.isObject()) + return result; + else + throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); } - - int eth_newFilter(const Json::Value& param1) throw (jsonrpc::JsonRpcException) + Json::Value eth_transactionByNumber(const int& param1, const int& param2) throw (jsonrpc::JsonRpcException) { Json::Value p; p.append(param1); - - Json::Value result = this->client->CallMethod("eth_newFilter",p); - if (result.isInt()) - return result.asInt(); - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - + p.append(param2); + Json::Value result = this->CallMethod("eth_transactionByNumber",p); + if (result.isObject()) + return result; + else + throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); } - - int eth_newFilterString(const std::string& param1) throw (jsonrpc::JsonRpcException) + Json::Value eth_uncleByHash(const std::string& param1, const int& param2) throw (jsonrpc::JsonRpcException) { Json::Value p; p.append(param1); - - Json::Value result = this->client->CallMethod("eth_newFilterString",p); - if (result.isInt()) - return result.asInt(); - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - + p.append(param2); + Json::Value result = this->CallMethod("eth_uncleByHash",p); + if (result.isObject()) + return result; + else + throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); } - - int eth_number() throw (jsonrpc::JsonRpcException) + Json::Value eth_uncleByNumber(const int& param1, const int& param2) throw (jsonrpc::JsonRpcException) { Json::Value p; - p = Json::nullValue; - Json::Value result = this->client->CallMethod("eth_number",p); - if (result.isInt()) - return result.asInt(); - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - + p.append(param1); + p.append(param2); + Json::Value result = this->CallMethod("eth_uncleByNumber",p); + if (result.isObject()) + return result; + else + throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); } - - int eth_peerCount() throw (jsonrpc::JsonRpcException) + Json::Value eth_compilers() throw (jsonrpc::JsonRpcException) { Json::Value p; p = Json::nullValue; - Json::Value result = this->client->CallMethod("eth_peerCount",p); - if (result.isInt()) - return result.asInt(); - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - + Json::Value result = this->CallMethod("eth_compilers",p); + if (result.isArray()) + return result; + else + throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); } - - bool eth_setCoinbase(const std::string& param1) throw (jsonrpc::JsonRpcException) + std::string eth_lll(const std::string& param1) throw (jsonrpc::JsonRpcException) { Json::Value p; p.append(param1); - - Json::Value result = this->client->CallMethod("eth_setCoinbase",p); - if (result.isBool()) - return result.asBool(); - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - + Json::Value result = this->CallMethod("eth_lll",p); + if (result.isString()) + return result.asString(); + else + throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); } - - bool eth_setDefaultBlock(const int& param1) throw (jsonrpc::JsonRpcException) + std::string eth_solidity(const std::string& param1) throw (jsonrpc::JsonRpcException) { Json::Value p; p.append(param1); - - Json::Value result = this->client->CallMethod("eth_setDefaultBlock",p); - if (result.isBool()) - return result.asBool(); - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - + Json::Value result = this->CallMethod("eth_solidity",p); + if (result.isString()) + return result.asString(); + else + throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); } - - bool eth_setListening(const bool& param1) throw (jsonrpc::JsonRpcException) + std::string eth_serpent(const std::string& param1) throw (jsonrpc::JsonRpcException) { Json::Value p; p.append(param1); - - Json::Value result = this->client->CallMethod("eth_setListening",p); - if (result.isBool()) - return result.asBool(); - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - + Json::Value result = this->CallMethod("eth_serpent",p); + if (result.isString()) + return result.asString(); + else + throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); } - - bool eth_setMining(const bool& param1) throw (jsonrpc::JsonRpcException) + int eth_newFilter(const Json::Value& param1) throw (jsonrpc::JsonRpcException) { Json::Value p; p.append(param1); - - Json::Value result = this->client->CallMethod("eth_setMining",p); - if (result.isBool()) - return result.asBool(); - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - + Json::Value result = this->CallMethod("eth_newFilter",p); + if (result.isInt()) + return result.asInt(); + else + throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); } - - std::string eth_stateAt(const std::string& param1, const std::string& param2) throw (jsonrpc::JsonRpcException) + int eth_newFilterString(const std::string& param1) throw (jsonrpc::JsonRpcException) { Json::Value p; p.append(param1); -p.append(param2); - - Json::Value result = this->client->CallMethod("eth_stateAt",p); - if (result.isString()) - return result.asString(); - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - + Json::Value result = this->CallMethod("eth_newFilterString",p); + if (result.isInt()) + return result.asInt(); + else + throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); } - - std::string eth_transact(const Json::Value& param1) throw (jsonrpc::JsonRpcException) + bool eth_uninstallFilter(const int& param1) throw (jsonrpc::JsonRpcException) { Json::Value p; p.append(param1); - - Json::Value result = this->client->CallMethod("eth_transact",p); - if (result.isString()) - return result.asString(); - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - + Json::Value result = this->CallMethod("eth_uninstallFilter",p); + if (result.isBool()) + return result.asBool(); + else + throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); } - - Json::Value eth_transactionByHash(const std::string& param1, const int& param2) throw (jsonrpc::JsonRpcException) + bool eth_changed(const int& param1) throw (jsonrpc::JsonRpcException) { Json::Value p; p.append(param1); -p.append(param2); - - Json::Value result = this->client->CallMethod("eth_transactionByHash",p); - if (result.isObject()) - return result; - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - + Json::Value result = this->CallMethod("eth_changed",p); + if (result.isBool()) + return result.asBool(); + else + throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); } - - Json::Value eth_transactionByNumber(const int& param1, const int& param2) throw (jsonrpc::JsonRpcException) + Json::Value eth_filterLogs(const int& param1) throw (jsonrpc::JsonRpcException) { Json::Value p; p.append(param1); -p.append(param2); - - Json::Value result = this->client->CallMethod("eth_transactionByNumber",p); - if (result.isObject()) - return result; - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - + Json::Value result = this->CallMethod("eth_filterLogs",p); + if (result.isArray()) + return result; + else + throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); } - - Json::Value eth_uncleByHash(const std::string& param1, const int& param2) throw (jsonrpc::JsonRpcException) + Json::Value eth_logs(const Json::Value& param1) throw (jsonrpc::JsonRpcException) { Json::Value p; p.append(param1); -p.append(param2); - - Json::Value result = this->client->CallMethod("eth_uncleByHash",p); - if (result.isObject()) - return result; - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - + Json::Value result = this->CallMethod("eth_logs",p); + if (result.isArray()) + return result; + else + throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); } - - Json::Value eth_uncleByNumber(const int& param1, const int& param2) throw (jsonrpc::JsonRpcException) + bool db_put(const std::string& param1, const std::string& param2, const std::string& param3) throw (jsonrpc::JsonRpcException) { Json::Value p; p.append(param1); -p.append(param2); - - Json::Value result = this->client->CallMethod("eth_uncleByNumber",p); - if (result.isObject()) - return result; - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - + p.append(param2); + p.append(param3); + Json::Value result = this->CallMethod("db_put",p); + if (result.isBool()) + return result.asBool(); + else + throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); } - - bool eth_uninstallFilter(const int& param1) throw (jsonrpc::JsonRpcException) + std::string db_get(const std::string& param1, const std::string& param2) throw (jsonrpc::JsonRpcException) { Json::Value p; p.append(param1); - - Json::Value result = this->client->CallMethod("eth_uninstallFilter",p); - if (result.isBool()) - return result.asBool(); - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - + p.append(param2); + Json::Value result = this->CallMethod("db_get",p); + if (result.isString()) + return result.asString(); + else + throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); } - - std::string shh_addToGroup(const std::string& param1, const std::string& param2) throw (jsonrpc::JsonRpcException) + bool db_putString(const std::string& param1, const std::string& param2, const std::string& param3) throw (jsonrpc::JsonRpcException) { Json::Value p; p.append(param1); -p.append(param2); - - Json::Value result = this->client->CallMethod("shh_addToGroup",p); - if (result.isString()) - return result.asString(); - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - + p.append(param2); + p.append(param3); + Json::Value result = this->CallMethod("db_putString",p); + if (result.isBool()) + return result.asBool(); + else + throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); } - - Json::Value shh_changed(const int& param1) throw (jsonrpc::JsonRpcException) + std::string db_getString(const std::string& param1, const std::string& param2) throw (jsonrpc::JsonRpcException) { Json::Value p; p.append(param1); - - Json::Value result = this->client->CallMethod("shh_changed",p); - if (result.isArray()) - return result; - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - + p.append(param2); + Json::Value result = this->CallMethod("db_getString",p); + if (result.isString()) + return result.asString(); + else + throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); } - - bool shh_haveIdentity(const std::string& param1) throw (jsonrpc::JsonRpcException) + bool shh_post(const Json::Value& param1) throw (jsonrpc::JsonRpcException) { Json::Value p; p.append(param1); - - Json::Value result = this->client->CallMethod("shh_haveIdentity",p); - if (result.isBool()) - return result.asBool(); - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - + Json::Value result = this->CallMethod("shh_post",p); + if (result.isBool()) + return result.asBool(); + else + throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); } - - int shh_newFilter(const Json::Value& param1) throw (jsonrpc::JsonRpcException) + std::string shh_newIdentity() throw (jsonrpc::JsonRpcException) + { + Json::Value p; + p = Json::nullValue; + Json::Value result = this->CallMethod("shh_newIdentity",p); + if (result.isString()) + return result.asString(); + else + throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); + } + bool shh_haveIdentity(const std::string& param1) throw (jsonrpc::JsonRpcException) { Json::Value p; p.append(param1); - - Json::Value result = this->client->CallMethod("shh_newFilter",p); - if (result.isInt()) - return result.asInt(); - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - + Json::Value result = this->CallMethod("shh_haveIdentity",p); + if (result.isBool()) + return result.asBool(); + else + throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); } - std::string shh_newGroup(const std::string& param1, const std::string& param2) throw (jsonrpc::JsonRpcException) { Json::Value p; p.append(param1); -p.append(param2); - - Json::Value result = this->client->CallMethod("shh_newGroup",p); - if (result.isString()) - return result.asString(); - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - + p.append(param2); + Json::Value result = this->CallMethod("shh_newGroup",p); + if (result.isString()) + return result.asString(); + else + throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); } - - std::string shh_newIdentity() throw (jsonrpc::JsonRpcException) + std::string shh_addToGroup(const std::string& param1, const std::string& param2) throw (jsonrpc::JsonRpcException) { Json::Value p; - p = Json::nullValue; - Json::Value result = this->client->CallMethod("shh_newIdentity",p); - if (result.isString()) - return result.asString(); - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - + p.append(param1); + p.append(param2); + Json::Value result = this->CallMethod("shh_addToGroup",p); + if (result.isString()) + return result.asString(); + else + throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); } - - bool shh_post(const Json::Value& param1) throw (jsonrpc::JsonRpcException) + int shh_newFilter(const Json::Value& param1) throw (jsonrpc::JsonRpcException) { Json::Value p; p.append(param1); - - Json::Value result = this->client->CallMethod("shh_post",p); - if (result.isBool()) - return result.asBool(); - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - + Json::Value result = this->CallMethod("shh_newFilter",p); + if (result.isInt()) + return result.asInt(); + else + throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); } - bool shh_uninstallFilter(const int& param1) throw (jsonrpc::JsonRpcException) { Json::Value p; p.append(param1); - - Json::Value result = this->client->CallMethod("shh_uninstallFilter",p); - if (result.isBool()) - return result.asBool(); - else - throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); - + Json::Value result = this->CallMethod("shh_uninstallFilter",p); + if (result.isBool()) + return result.asBool(); + else + throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); + } + Json::Value shh_changed(const int& param1) throw (jsonrpc::JsonRpcException) + { + Json::Value p; + p.append(param1); + Json::Value result = this->CallMethod("shh_changed",p); + if (result.isArray()) + return result; + else + throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); } - - private: - jsonrpc::Client* client; }; -#endif //_WEBTHREESTUBCLIENT_H_ + +#endif //JSONRPC_CPP_WEBTHREESTUBCLIENT_H_ diff --git a/test/whisperTopic.cpp b/test/whisperTopic.cpp index 493b37bc2..79adf3d6a 100644 --- a/test/whisperTopic.cpp +++ b/test/whisperTopic.cpp @@ -32,6 +32,8 @@ BOOST_AUTO_TEST_SUITE(whisper) BOOST_AUTO_TEST_CASE(topic) { + cnote << "Testing Whisper..."; + auto oldLogVerbosity = g_logVerbosity; g_logVerbosity = 0; bool started = false; @@ -40,16 +42,16 @@ BOOST_AUTO_TEST_CASE(topic) { setThreadName("other"); - Host ph("Test", NetworkPreferences(30303, "", false, true)); + Host ph("Test", NetworkPreferences(50303, "", false, true)); auto wh = ph.registerCapability(new WhisperHost()); ph.start(); started = true; /// Only interested in odd packets - auto w = wh->installWatch(BuildTopicMask()("odd")); + auto w = wh->installWatch(BuildTopicMask("odd")); - for (int i = 0, last = 0; i < 100 && last < 81; ++i) + for (int i = 0, last = 0; i < 200 && last < 81; ++i) { for (auto i: wh->checkWatch(w)) { @@ -65,10 +67,12 @@ BOOST_AUTO_TEST_CASE(topic) while (!started) this_thread::sleep_for(chrono::milliseconds(50)); - Host ph("Test", NetworkPreferences(30300, "", false, true)); + Host ph("Test", NetworkPreferences(50300, "", false, true)); auto wh = ph.registerCapability(new WhisperHost()); + this_thread::sleep_for(chrono::milliseconds(500)); ph.start(); - ph.connect("127.0.0.1", 30303); + this_thread::sleep_for(chrono::milliseconds(500)); + ph.connect("127.0.0.1", 50303); KeyPair us = KeyPair::create(); for (int i = 0; i < 10; ++i) @@ -78,6 +82,8 @@ BOOST_AUTO_TEST_CASE(topic) } listener.join(); + g_logVerbosity = oldLogVerbosity; + BOOST_REQUIRE_EQUAL(result, 1 + 9 + 25 + 49 + 81); } diff --git a/third/CMakeLists.txt b/third/CMakeLists.txt index d5371b666..c9c95cf33 100644 --- a/third/CMakeLists.txt +++ b/third/CMakeLists.txt @@ -1,101 +1,50 @@ +cmake_policy(SET CMP0015 NEW) +# let cmake autolink dependencies on windows +cmake_policy(SET CMP0020 NEW) +# this policy was introduced in cmake 3.0 +# remove if, once 3.0 will be used on unix +if (${CMAKE_MAJOR_VERSION} GREATER 2) + cmake_policy(SET CMP0043 OLD) +endif() + set(CMAKE_INCLUDE_CURRENT_DIR ON) aux_source_directory(. SRC_LIST) -include_directories(..) -if (APPLE) - # Add homebrew path for qt5 - set(CMAKE_PREFIX_PATH /usr/local/opt/qt5) - include_directories(/usr/local/opt/qt5/include /usr/local/include) -elseif ("${TARGET_PLATFORM}" STREQUAL "w64") - set(SRC_LIST ${SRC_LIST} ../windows/qt_plugin_import.cpp) - include_directories(/usr/x86_64-w64-mingw32/include /usr/x86_64-w64-mingw32/include/QtCore /usr/x86_64-w64-mingw32/include/QtGui /usr/x86_64-w64-mingw32/include/QtQuick /usr/x86_64-w64-mingw32/include/QtQml /usr/x86_64-w64-mingw32/include/QtNetwork /usr/x86_64-w64-mingw32/include/QtWidgets /usr/x86_64-w64-mingw32/include/QtWebKit /usr/x86_64-w64-mingw32/include/QtWebKitWidgets) -elseif (UNIX) - set(CMAKE_PREFIX_PATH ${CMAKE_PREFIX_PATH} ";$ENV{QTDIR}/lib/cmake") -endif () - -find_package(Qt5Core REQUIRED) -find_package(Qt5Gui REQUIRED) -find_package(Qt5Quick REQUIRED) -find_package(Qt5Qml REQUIRED) -find_package(Qt5Network REQUIRED) -find_package(Qt5Widgets REQUIRED) -find_package(Qt5WebKit REQUIRED) -find_package(Qt5WebKitWidgets REQUIRED) +include_directories(${JSON_RPC_CPP_INCLUDE_DIRS}) +include_directories(..) qt5_wrap_ui(ui_Main.h Main.ui) -# Set name of binary and add_executable() file(GLOB HEADERS "*.h") -if (APPLE) - set(EXECUTEABLE Third) - set(BIN_INSTALL_DIR ".") - set(DOC_INSTALL_DIR ".") - - set(PROJECT_VERSION "${ETH_VERSION}") - set(MACOSX_BUNDLE_INFO_STRING "${PROJECT_NAME} ${PROJECT_VERSION}") - set(MACOSX_BUNDLE_BUNDLE_VERSION "${PROJECT_NAME} ${PROJECT_VERSION}") - set(MACOSX_BUNDLE_LONG_VERSION_STRING "${PROJECT_NAME} ${PROJECT_VERSION}") - set(MACOSX_BUNDLE_SHORT_VERSION_STRING "${PROJECT_VERSION}") - set(MACOSX_BUNDLE_COPYRIGHT "${PROJECT_COPYRIGHT_YEAR} ${PROJECT_VENDOR}") - set(MACOSX_BUNDLE_GUI_IDENTIFIER "${PROJECT_DOMAIN_SECOND}.${PROJECT_DOMAIN_FIRST}") - set(MACOSX_BUNDLE_BUNDLE_NAME ${EXECUTEABLE}) - set(MACOSX_BUNDLE_ICON_FILE third) - include(BundleUtilities) - - add_executable(${EXECUTEABLE} MACOSX_BUNDLE third.icns Main.ui ${SRC_LIST} ${HEADERS}) - set_target_properties(${EXECUTEABLE} PROPERTIES MACOSX_BUNDLE_INFO_PLIST "${CMAKE_CURRENT_SOURCE_DIR}/EthereumMacOSXBundleInfo.plist.in") - SET_SOURCE_FILES_PROPERTIES(${EXECUTEABLE} PROPERTIES MACOSX_PACKAGE_LOCATION MacOS) - SET_SOURCE_FILES_PROPERTIES(${MACOSX_BUNDLE_ICON_FILE}.icns PROPERTIES MACOSX_PACKAGE_LOCATION "Resources") - -else () - set(EXECUTEABLE third) - add_executable(${EXECUTEABLE} Main.ui ${SRC_LIST} ${HEADERS}) -endif () - -qt5_use_modules(${EXECUTEABLE} Core)# Gui Widgets Network WebKit WebKitWidgets) -target_link_libraries(${EXECUTEABLE} webthree qethereum ethereum evm ethcore secp256k1 gmp ${CRYPTOPP_LS} serpent lll evmcore devcore web3jsonrpc jsqrc) if (APPLE) - # First have qt5 install plugins and frameworks - add_custom_command(TARGET ${EXECUTEABLE} POST_BUILD - COMMAND /usr/local/opt/qt5/bin/macdeployqt ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_CFG_INTDIR}/${EXECUTEABLE}.app - WORKING_DIRECTORY ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}) - - # This tool and next will inspect linked libraries in order to determine which dependencies are required - if (${CMAKE_CFG_INTDIR} STREQUAL ".") - set(APP_BUNDLE_PATH "${CMAKE_CURRENT_BINARY_DIR}/${EXECUTEABLE}.app") - else () - set(APP_BUNDLE_PATH "${CMAKE_CURRENT_BINARY_DIR}/\$ENV{CONFIGURATION}/${EXECUTEABLE}.app") - endif () - install(CODE " - include(BundleUtilities) - set(BU_CHMOD_BUNDLE_ITEMS 1) - fixup_bundle(\"${APP_BUNDLE_PATH}\" \"${BUNDLELIBS}\" \"../libqethereum ../libethereum ../secp256k1\") - " COMPONENT RUNTIME ) - # Cleanup duplicate libs from macdeployqt - install(CODE " - file(GLOB LINGER_RM \"${APP_BUNDLE_PATH}/Contents/Frameworks/*.dylib\") - if (LINGER_RM) - file(REMOVE \${LINGER_RM}) - endif () - ") -elseif ("${TARGET_PLATFORM}" STREQUAL "w64") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fno-keep-inline-dllexport -static-libgcc -static-libstdc++ -static") - set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,-s -Wl,-subsystem,windows -mthreads -L/usr/x86_64-w64-mingw32/plugins/platforms") - target_link_libraries(${EXECUTEABLE} gcc) - target_link_libraries(${EXECUTEABLE} mingw32 qtmain mswsock iphlpapi qwindows shlwapi Qt5PlatformSupport opengl32 gdi32 comdlg32 oleaut32 imm32 winmm ole32 uuid ws2_32) - target_link_libraries(${EXECUTEABLE} boost_system-mt-s) - target_link_libraries(${EXECUTEABLE} boost_filesystem-mt-s) - target_link_libraries(${EXECUTEABLE} boost_thread_win32-mt-s) - target_link_libraries(${EXECUTEABLE} crypt32) - target_link_libraries(${EXECUTEABLE} Qt5PlatformSupport) - set(CMAKE_SHARED_LIBRARY_LINK_CXX_FLAGS) -elseif (UNIX) + set(EXECUTABLE Third) else () - target_link_libraries(${EXECUTEABLE} boost_system) - target_link_libraries(${EXECUTEABLE} boost_filesystem) - find_package(Threads REQUIRED) - target_link_libraries(${EXECUTEABLE} ${CMAKE_THREAD_LIBS_INIT}) - install( TARGETS ${EXECUTEABLE} RUNTIME DESTINATION bin ) + set(EXECUTABLE third) endif () +# eth_add_executable is defined in cmake/EthExecutableHelper.cmake +eth_add_executable(${EXECUTABLE} + ICON third + UI_RESOURCES third.icns Main.ui +) + +add_dependencies(${EXECUTABLE} BuildInfo.h) + +target_link_libraries(${EXECUTABLE} Qt5::Core) +target_link_libraries(${EXECUTABLE} webthree) +target_link_libraries(${EXECUTABLE} qethereum) +target_link_libraries(${EXECUTABLE} ethereum) +target_link_libraries(${EXECUTABLE} evm) +target_link_libraries(${EXECUTABLE} ethcore) +target_link_libraries(${EXECUTABLE} secp256k1) +target_link_libraries(${EXECUTABLE} serpent) +target_link_libraries(${EXECUTABLE} lll) +target_link_libraries(${EXECUTABLE} evmcore) +target_link_libraries(${EXECUTABLE} devcore) +target_link_libraries(${EXECUTABLE} web3jsonrpc) +target_link_libraries(${EXECUTABLE} jsqrc) + +# eth_install_executable is defined in cmake/EthExecutableHelper.cmake +eth_install_executable(${EXECUTABLE}) + diff --git a/third/EthereumMacOSXBundleInfo.plist.in b/third/EthereumMacOSXBundleInfo.plist.in deleted file mode 100644 index 684ad7908..000000000 --- a/third/EthereumMacOSXBundleInfo.plist.in +++ /dev/null @@ -1,38 +0,0 @@ - - - - - CFBundleDevelopmentRegion - English - CFBundleExecutable - ${MACOSX_BUNDLE_EXECUTABLE_NAME} - CFBundleGetInfoString - ${MACOSX_BUNDLE_INFO_STRING} - CFBundleIconFile - ${MACOSX_BUNDLE_ICON_FILE} - CFBundleIdentifier - ${MACOSX_BUNDLE_GUI_IDENTIFIER} - CFBundleInfoDictionaryVersion - 6.0 - CFBundleLongVersionString - ${MACOSX_BUNDLE_LONG_VERSION_STRING} - CFBundleName - ${MACOSX_BUNDLE_BUNDLE_NAME} - CFBundlePackageType - APPL - CFBundleShortVersionString - ${MACOSX_BUNDLE_SHORT_VERSION_STRING} - CFBundleSignature - ???? - CFBundleVersion - ${MACOSX_BUNDLE_BUNDLE_VERSION} - CSResourcesFileMapped - - LSRequiresCarbon - - NSHumanReadableCopyright - ${MACOSX_BUNDLE_COPYRIGHT} - NSHighResolutionCapable - - - diff --git a/third/MainWin.cpp b/third/MainWin.cpp index c2dcb7ce2..894f1af0f 100644 --- a/third/MainWin.cpp +++ b/third/MainWin.cpp @@ -117,7 +117,7 @@ Main::Main(QWidget *parent) : m_web3.reset(new WebThreeDirect("Third", getDataDir() + "/Third", false, {"eth", "shh"})); m_web3->connect(Host::pocHost()); - m_server = unique_ptr(new WebThreeStubServer(&m_qwebConnector, *web3(), keysAsVector(m_myKeys))); + m_server = unique_ptr(new WebThreeStubServer(m_qwebConnector, *web3(), keysAsVector(m_myKeys))); m_server->setIdentities(keysAsVector(owned())); m_server->StartListening(); @@ -182,7 +182,7 @@ void Main::onKeysChanged() installBalancesWatch(); } -unsigned Main::installWatch(dev::eth::MessageFilter const& _tf, std::function const& _f) +unsigned Main::installWatch(dev::eth::LogFilter const& _tf, std::function const& _f) { auto ret = ethereum()->installWatch(_tf); m_handlers[ret] = _f; @@ -198,37 +198,34 @@ unsigned Main::installWatch(dev::h256 _tf, std::function const& _f) void Main::installWatches() { - installWatch(dev::eth::MessageFilter().altered(c_config, 0), [=](){ installNameRegWatch(); }); - installWatch(dev::eth::MessageFilter().altered(c_config, 1), [=](){ installCurrenciesWatch(); }); + installWatch(dev::eth::LogFilter().topic((u256)(u160)c_config).topic((u256)0), [=](){ installNameRegWatch(); }); + installWatch(dev::eth::LogFilter().topic((u256)(u160)c_config).topic((u256)1), [=](){ installCurrenciesWatch(); }); installWatch(dev::eth::ChainChangedFilter, [=](){ onNewBlock(); }); } void Main::installNameRegWatch() { ethereum()->uninstallWatch(m_nameRegFilter); - m_nameRegFilter = installWatch(dev::eth::MessageFilter().altered((u160)ethereum()->stateAt(c_config, 0)), [=](){ onNameRegChange(); }); + m_nameRegFilter = installWatch(dev::eth::LogFilter().topic(ethereum()->stateAt(c_config, 0)), [=](){ onNameRegChange(); }); } void Main::installCurrenciesWatch() { ethereum()->uninstallWatch(m_currenciesFilter); - m_currenciesFilter = installWatch(dev::eth::MessageFilter().altered((u160)ethereum()->stateAt(c_config, 1)), [=](){ onCurrenciesChange(); }); + m_currenciesFilter = installWatch(dev::eth::LogFilter().topic(ethereum()->stateAt(c_config, 1)), [=](){ onCurrenciesChange(); }); } void Main::installBalancesWatch() { - dev::eth::MessageFilter tf; + dev::eth::LogFilter tf; vector
altCoins; Address coinsAddr = right160(ethereum()->stateAt(c_config, 1)); for (unsigned i = 0; i < ethereum()->stateAt(coinsAddr, 0); ++i) altCoins.push_back(right160(ethereum()->stateAt(coinsAddr, i + 1))); for (auto i: m_myKeys) - { - tf.altered(i.address()); for (auto c: altCoins) - tf.altered(c, (u160)i.address()); - } + tf.address(c).topic((u256)(u160)i.address()); ethereum()->uninstallWatch(m_balancesFilter); m_balancesFilter = installWatch(tf, [=](){ onBalancesChange(); }); @@ -614,15 +611,3 @@ void Main::on_mine_triggered() else ethereum()->stopMining(); } - -// extra bits needed to link on VS -#ifdef _MSC_VER - -// include moc file, ofuscated to hide from automoc -#include\ -"moc_MainWin.cpp" - -#include\ -"moc_MiningView.cpp" - -#endif diff --git a/third/MainWin.h b/third/MainWin.h index 607d65fee..478fb6fb6 100644 --- a/third/MainWin.h +++ b/third/MainWin.h @@ -40,7 +40,7 @@ namespace dev { class WebThreeDirect; namespace eth { class Client; class State; -class MessageFilter; +class LogFilter; } namespace shh { class WhisperHost; @@ -95,7 +95,7 @@ private: void readSettings(bool _skipGeometry = false); void writeSettings(); - unsigned installWatch(dev::eth::MessageFilter const& _tf, std::function const& _f); + unsigned installWatch(dev::eth::LogFilter const& _tf, std::function const& _f); unsigned installWatch(dev::h256 _tf, std::function const& _f); void onNewBlock(); diff --git a/walleth/CMakeLists.txt b/walleth/CMakeLists.txt deleted file mode 100644 index cac73a726..000000000 --- a/walleth/CMakeLists.txt +++ /dev/null @@ -1,117 +0,0 @@ -cmake_policy(SET CMP0015 NEW) - -if ("${TARGET_PLATFORM}" STREQUAL "w64") - cmake_policy(SET CMP0020 NEW) -endif () - - -set(CMAKE_INCLUDE_CURRENT_DIR ON) -aux_source_directory(. SRC_LIST) - -include_directories(..) -link_directories(../libethcore) -link_directories(../libethereum) -link_directories(../libqethereum) - -# Find Qt5 for Apple and update src_list for windows -if (APPLE) - # homebrew defaults to qt4 and installs qt5 as 'keg-only' - # which places it into /usr/local/opt insteadof /usr/local. - - set(CMAKE_PREFIX_PATH /usr/local/opt/qt5) - include_directories(/usr/local/opt/qt5/include /usr/local/include) -elseif ("${TARGET_PLATFORM}" STREQUAL "w64") - set(SRC_LIST ${SRC_LIST} ../windows/qt_plugin_import.cpp) -elseif (UNIX) - set(CMAKE_PREFIX_PATH ${CMAKE_PREFIX_PATH} ";$ENV{QTDIR}/lib/cmake") -endif () - - -find_package(Qt5Widgets REQUIRED) -find_package(Qt5Gui REQUIRED) -find_package(Qt5Quick REQUIRED) -find_package(Qt5Qml REQUIRED) -find_package(Qt5Network REQUIRED) -qt5_wrap_ui(ui_Main.h Main.ui) -qt5_add_resources(RESOURCE_ADDED Resources.qrc) - -# Set name of binary and add_executable() -if (APPLE) - set(EXECUTEABLE Walleth) - set(CMAKE_INSTALL_PREFIX ./) - set(BIN_INSTALL_DIR ".") - set(DOC_INSTALL_DIR ".") - - set(PROJECT_VERSION "${ETH_VERSION}") - set(MACOSX_BUNDLE_INFO_STRING "${PROJECT_NAME} ${PROJECT_VERSION}") - set(MACOSX_BUNDLE_BUNDLE_VERSION "${PROJECT_NAME} ${PROJECT_VERSION}") - set(MACOSX_BUNDLE_LONG_VERSION_STRING "${PROJECT_NAME} ${PROJECT_VERSION}") - set(MACOSX_BUNDLE_SHORT_VERSION_STRING "${PROJECT_VERSION}") - set(MACOSX_BUNDLE_COPYRIGHT "${PROJECT_COPYRIGHT_YEAR} ${PROJECT_VENDOR}") - set(MACOSX_BUNDLE_GUI_IDENTIFIER "${PROJECT_DOMAIN_SECOND}.${PROJECT_DOMAIN_FIRST}") - set(MACOSX_BUNDLE_BUNDLE_NAME ${EXECUTEABLE}) - include(BundleUtilities) - - add_executable(${EXECUTEABLE} MACOSX_BUNDLE Main.ui ${RESOURCE_ADDED} ${SRC_LIST}) -else () - set(EXECUTEABLE walleth) - add_executable(${EXECUTEABLE} Main.ui ${RESOURCE_ADDED} ${SRC_LIST}) -endif () - -qt5_use_modules(${EXECUTEABLE} Core Gui Widgets Network Quick Qml) -target_link_libraries(${EXECUTEABLE} qethereum ethereum secp256k1 ${CRYPTOPP_LS}) - -if (APPLE) - if (${ADDFRAMEWORKS}) - set_target_properties(${EXECUTEABLE} PROPERTIES MACOSX_BUNDLE_INFO_PLIST "${CMAKE_CURRENT_SOURCE_DIR}/EthereumMacOSXBundleInfo.plist.in") - endif () - - SET_SOURCE_FILES_PROPERTIES(${EXECUTEABLE} PROPERTIES MACOSX_PACKAGE_LOCATION MacOS) - - # This is a workaround for when the build-type defaults to Debug, and when a multi-config generator like xcode is used, where the type - # will not be set but defaults to release. - set(generator_lowercase "${CMAKE_GENERATOR}") - string(TOLOWER "${CMAKE_GENERATOR}" generator_lowercase) - if ("${generator_lowercase}" STREQUAL "xcode") - # TODO: Not sure how to resolve this. Possibly \${TARGET_BUILD_DIR} - set(binary_build_dir "${CMAKE_CURRENT_BINARY_DIR}/Debug") - else () - set(binary_build_dir "${CMAKE_CURRENT_BINARY_DIR}") - endif () - - set(APPS ${binary_build_dir}/${EXECUTEABLE}.app) - - # This tool and the next will automatically looked at the linked libraries in order to determine what dependencies are required. Thus, target_link_libaries only needs to add ethereum and secp256k1 (above) - install(CODE " - include(BundleUtilities) - set(BU_CHMOD_BUNDLE_ITEMS 1) - fixup_bundle(\"${APPS}\" \"${BUNDLELIBS}\" \"../libqethereum ../libethereum ../secp256k1\") - " COMPONENT RUNTIME ) - - if (${ADDFRAMEWORKS}) - add_custom_target(addframeworks ALL - COMMAND /usr/local/opt/qt5/bin/macdeployqt ${binary_build_dir}/${EXECUTEABLE}.app - WORKING_DIRECTORY ${CMAKE_RUNTIME_OUTPUT_DIRECTORY} - DEPENDS ${PROJECT_NAME} - ) - endif () - -elseif ("${TARGET_PLATFORM}" STREQUAL "w64") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fno-keep-inline-dllexport -static-libgcc -static-libstdc++ -static") - set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,-s -Wl,-subsystem,windows -mthreads -L/usr/x86_64-w64-mingw32/plugins/platforms") - target_link_libraries(${EXECUTEABLE} gcc) - target_link_libraries(${EXECUTEABLE} mingw32 qtmain mswsock iphlpapi qwindows shlwapi Qt5PlatformSupport gdi32 comdlg32 oleaut32 imm32 winmm ole32 uuid ws2_32) - target_link_libraries(${EXECUTEABLE} boost_system-mt-s) - target_link_libraries(${EXECUTEABLE} boost_filesystem-mt-s) - target_link_libraries(${EXECUTEABLE} boost_thread_win32-mt-s) - target_link_libraries(${EXECUTEABLE} Qt5PlatformSupport) - set(CMAKE_SHARED_LIBRARY_LINK_CXX_FLAGS) -elseif (UNIX) -else () - target_link_libraries(${EXECUTEABLE} boost_system) - target_link_libraries(${EXECUTEABLE} boost_filesystem) - find_package(Threads REQUIRED) - target_link_libraries(${EXECUTEABLE} ${CMAKE_THREAD_LIBS_INIT}) - install( TARGETS ${EXECUTEABLE} RUNTIME DESTINATION bin ) -endif () - diff --git a/walleth/EthereumMacOSXBundleInfo.plist.in b/walleth/EthereumMacOSXBundleInfo.plist.in deleted file mode 100644 index 684ad7908..000000000 --- a/walleth/EthereumMacOSXBundleInfo.plist.in +++ /dev/null @@ -1,38 +0,0 @@ - - - - - CFBundleDevelopmentRegion - English - CFBundleExecutable - ${MACOSX_BUNDLE_EXECUTABLE_NAME} - CFBundleGetInfoString - ${MACOSX_BUNDLE_INFO_STRING} - CFBundleIconFile - ${MACOSX_BUNDLE_ICON_FILE} - CFBundleIdentifier - ${MACOSX_BUNDLE_GUI_IDENTIFIER} - CFBundleInfoDictionaryVersion - 6.0 - CFBundleLongVersionString - ${MACOSX_BUNDLE_LONG_VERSION_STRING} - CFBundleName - ${MACOSX_BUNDLE_BUNDLE_NAME} - CFBundlePackageType - APPL - CFBundleShortVersionString - ${MACOSX_BUNDLE_SHORT_VERSION_STRING} - CFBundleSignature - ???? - CFBundleVersion - ${MACOSX_BUNDLE_BUNDLE_VERSION} - CSResourcesFileMapped - - LSRequiresCarbon - - NSHumanReadableCopyright - ${MACOSX_BUNDLE_COPYRIGHT} - NSHighResolutionCapable - - - diff --git a/walleth/Main.ui b/walleth/Main.ui deleted file mode 100644 index 6904590a8..000000000 --- a/walleth/Main.ui +++ /dev/null @@ -1,168 +0,0 @@ - - - Main - - - - 0 - 0 - 562 - 488 - - - - Walleth - - - true - - - QMainWindow::AllowNestedDocks|QMainWindow::AllowTabbedDocks|QMainWindow::VerticalTabs - - - true - - - - - 0 - - - 0 - - - 0 - - - 0 - - - - - - - 0 wei - - - - - - - 0 peers - - - - - - - 1 block - - - - - - - - - - - 0 - 0 - 562 - 20 - - - - - &File - - - - - - &Network - - - - - - - - T&ools - - - - - - - - &Help - - - - - - - - - - - - &Quit - - - - - true - - - true - - - Use &UPnP - - - - - &Connect to Peer... - - - - - true - - - Enable &Network - - - - - true - - - &Mine - - - - - &New Address - - - - - &About... - - - - - true - - - &Preview - - - - - - - diff --git a/walleth/MainWin.cpp b/walleth/MainWin.cpp deleted file mode 100644 index f56cad65d..000000000 --- a/walleth/MainWin.cpp +++ /dev/null @@ -1,286 +0,0 @@ -#include -#include -//#include -//#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "BuildInfo.h" -#include "MainWin.h" -#include "ui_Main.h" -using namespace std; - -// types -using dev::bytes; -using dev::bytesConstRef; -using dev::h160; -using dev::h256; -using dev::u160; -using dev::u256; -using dev::u256s; -using dev::Address; -using dev::eth::BlockInfo; -using dev::eth::Client; -using dev::eth::Instruction; -using dev::KeyPair; -using dev::eth::NodeMode; -using dev::p2p::PeerInfo; -using dev::RLP; -using dev::Secret; -using dev::eth::Transaction; - -// functions -using dev::toHex; -using dev::fromHex; -using dev::right160; -using dev::simpleDebugOut; -using dev::toLog2; -using dev::toString; -using dev::eth::units; -using dev::eth::disassemble; -using dev::eth::formatBalance; - -// vars -using dev::g_logPost; -using dev::g_logVerbosity; - -Main::Main(QWidget *parent) : - QMainWindow(parent), - ui(new Ui::Main) -{ - setWindowFlags(Qt::Window); - ui->setupUi(this); - setWindowIcon(QIcon(":/Ethereum.png")); - - g_qmlMain = this; - - m_client.reset(new Client("Walleth", Address(), dev::getDataDir() + "/Walleth")); - - g_qmlClient = m_client.get(); - - qRegisterMetaType("dev::u256"); - qRegisterMetaType("dev::KeyPair"); - qRegisterMetaType("dev::Secret"); - qRegisterMetaType("dev::Address"); - qRegisterMetaType("QmlAccount*"); - qRegisterMetaType("QmlEthereum*"); - - qmlRegisterType("org.ethereum", 1, 0, "Ethereum"); - qmlRegisterType("org.ethereum", 1, 0, "Account"); - qmlRegisterSingletonType("org.ethereum", 1, 0, "Balance", QmlEthereum::constructU256Helper); - qmlRegisterSingletonType("org.ethereum", 1, 0, "Key", QmlEthereum::constructKeyHelper); - - /* - ui->librariesView->setModel(m_libraryMan); - ui->graphsView->setModel(m_graphMan); - */ - - m_view = new QQuickView(); - -// QQmlContext* context = m_view->rootContext(); -// context->setContextProperty("u256", new U256Helper(this)); - - m_view->setSource(QUrl("qrc:/Simple.qml")); - - QWidget* w = QWidget::createWindowContainer(m_view); - m_view->setResizeMode(QQuickView::SizeRootObjectToView); - ui->fullDisplay->insertWidget(0, w); - m_view->create(); - -// m_timelinesItem = m_view->rootObject()->findChild("timelines"); - - readSettings(); - refresh(); - - m_refreshNetwork = new QTimer(this); - connect(m_refreshNetwork, SIGNAL(timeout()), SLOT(refreshNetwork())); - m_refreshNetwork->start(1000); - - connect(&m_webCtrl, &QNetworkAccessManager::finished, [&](QNetworkReply* _r) - { - m_servers = QString::fromUtf8(_r->readAll()).split("\n", QString::SkipEmptyParts); - if (m_servers.size()) - { - ui->net->setChecked(true); - on_net_triggered(true); - } - }); - QNetworkRequest r(QUrl("http://www.ethereum.org/servers.poc" + QString(dev::Version).section('.', 1, 1) + ".txt")); - r.setHeader(QNetworkRequest::UserAgentHeader, "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1712.0 Safari/537.36"); - m_webCtrl.get(r); - srand(time(0)); - - startTimer(200); - - statusBar()->addPermanentWidget(ui->balance); - statusBar()->addPermanentWidget(ui->peerCount); - statusBar()->addPermanentWidget(ui->blockCount); -} - -Main::~Main() -{ - writeSettings(); -} - -void Main::timerEvent(QTimerEvent *) -{ - -} - -void Main::on_about_triggered() -{ - QMessageBox::about(this, "About Walleth PoC-" + QString(dev::Version).section('.', 1, 1), QString("Walleth/v") + dev::Version + "/" DEV_QUOTED(ETH_BUILD_TYPE) "/" DEV_QUOTED(ETH_BUILD_PLATFORM) "\n" DEV_QUOTED(ETH_COMMIT_HASH) + (ETH_CLEAN_REPO ? "\nCLEAN" : "\n+ LOCAL CHANGES") + "\n\nBy Gav Wood, 2014.\nBased on a design by Vitalik Buterin.\n\nThanks to the various contributors including: Alex Leverington, Tim Hughes, caktux, Eric Lombrozo, Marko Simovic."); -} - -void Main::writeSettings() -{ - QSettings s("ethereum", "walleth"); - QByteArray b; - b.resize(sizeof(Secret) * m_myKeys.size()); - auto p = b.data(); - for (auto i: m_myKeys) - { - memcpy(p, &(i.secret()), sizeof(Secret)); - p += sizeof(Secret); - } - s.setValue("address", b); - - s.setValue("upnp", ui->upnp->isChecked()); - s.setValue("clientName", m_clientName); - s.setValue("idealPeers", m_idealPeers); - s.setValue("port", m_port); - - bytes d = client()->savePeers(); - if (d.size()) - m_peers = QByteArray((char*)d.data(), (int)d.size()); - s.setValue("peers", m_peers); - - s.setValue("geometry", saveGeometry()); - s.setValue("windowState", saveState()); -} - -void Main::readSettings() -{ - QSettings s("ethereum", "walleth"); - - restoreGeometry(s.value("geometry").toByteArray()); - restoreState(s.value("windowState").toByteArray()); - - QByteArray b = s.value("address").toByteArray(); - if (b.isEmpty()) - m_myKeys.append(KeyPair::create()); - else - { - h256 k; - for (unsigned i = 0; i < b.size() / sizeof(Secret); ++i) - { - memcpy(&k, b.data() + i * sizeof(Secret), sizeof(Secret)); - m_myKeys.append(KeyPair(k)); - } - } - //m_eth->setAddress(m_myKeys.last().address()); - m_peers = s.value("peers").toByteArray(); - ui->upnp->setChecked(s.value("upnp", true).toBool()); - m_clientName = s.value("clientName", "").toString(); - m_idealPeers = s.value("idealPeers", 5).toInt(); - m_port = s.value("port", 30303).toInt(); -} - -void Main::refreshNetwork() -{ - auto ps = client()->peers(); - ui->peerCount->setText(QString::fromStdString(toString(ps.size())) + " peer(s)"); -} - -void Main::refresh() -{ - auto d = client()->blockChain().details(); - auto diff = BlockInfo(client()->blockChain().block()).difficulty; - ui->blockCount->setText(QString("#%1 @%3 T%2").arg(d.number).arg(toLog2(d.totalDifficulty)).arg(toLog2(diff))); - - m_keysChanged = false; - u256 totalBalance = 0; - for (auto i: m_myKeys) - { - u256 b = m_client->balanceAt(i.address()); - totalBalance += b; - } - ui->balance->setText(QString::fromStdString(formatBalance(totalBalance))); -} - -void Main::on_net_triggered(bool _auto) -{ - string n = string("Walleth/v") + dev::Version; - if (m_clientName.size()) - n += "/" + m_clientName.toStdString(); - n += "/" DEV_QUOTED(ETH_BUILD_TYPE) "/" DEV_QUOTED(ETH_BUILD_PLATFORM); - client()->setClientVersion(n); - if (ui->net->isChecked()) - { - if (_auto) - { - QString s = m_servers[rand() % m_servers.size()]; - client()->startNetwork(m_port, s.section(':', 0, 0).toStdString(), s.section(':', 1).toInt(), NodeMode::Full, m_idealPeers, "", ui->upnp->isChecked()); - } - else - client()->startNetwork(m_port, string(), 0, NodeMode::Full, m_idealPeers, "", ui->upnp->isChecked()); - if (m_peers.size()) - client()->restorePeers(bytesConstRef((byte*)m_peers.data(), m_peers.size())); - } - else - client()->stopNetwork(); -} - -void Main::on_connect_triggered() -{ - if (!ui->net->isChecked()) - { - ui->net->setChecked(true); - on_net_triggered(); - } - bool ok = false; - QString s = QInputDialog::getItem(this, "Connect to a Network Peer", "Enter a peer to which a connection may be made:", m_servers, m_servers.count() ? rand() % m_servers.count() : 0, true, &ok); - if (ok && s.contains(":")) - { - string host = s.section(":", 0, 0).toStdString(); - unsigned short port = s.section(":", 1).toInt(); - client()->connect(host, port); - } -} - -void Main::on_mine_triggered() -{ - if (ui->mine->isChecked()) - { - client()->setAddress(m_myKeys.last().address()); - client()->startMining(); - } - else - client()->stopMining(); -} - -void Main::on_create_triggered() -{ - m_myKeys.append(KeyPair::create()); - m_keysChanged = true; -} - -// extra bits needed to link on VS -#ifdef _MSC_VER - -// include moc file, ofuscated to hide from automoc -#include\ -"moc_MainWin.cpp" - -// include qrc content -#include\ -"qrc_Resources.cpp" - -#endif diff --git a/walleth/MainWin.h b/walleth/MainWin.h deleted file mode 100644 index 860db8bc9..000000000 --- a/walleth/MainWin.h +++ /dev/null @@ -1,84 +0,0 @@ -#ifndef MAIN_H -#define MAIN_H - -#include -#include -#include -#include -#include -#include - -namespace Ui { -class Main; -} - -namespace dev { namespace eth { -class Client; -class State; -}} - -class QQuickView; -class QQmlEngine; -class QJSEngine; - -class Main : public QMainWindow -{ - Q_OBJECT - -public: - explicit Main(QWidget *parent = 0); - ~Main(); - - dev::eth::Client* client() const { return m_client.get(); } - -private slots: - void on_connect_triggered(); - void on_mine_triggered(); - void on_create_triggered(); - void on_net_triggered(bool _auto = false); - void on_about_triggered(); - void on_preview_triggered() { refresh(); } - void on_quit_triggered() { close(); } - - void refresh(); - void refreshNetwork(); - -protected: - virtual void timerEvent(QTimerEvent *); - -private: -/* QString pretty(dev::Address _a) const; - QString render(dev::Address _a) const; - dev::Address fromString(QString const& _a) const; -*/ - dev::eth::State const& state() const; - - void updateFee(); - void readSettings(); - void writeSettings(); - - dev::u256 fee() const; - dev::u256 total() const; - dev::u256 value() const; - - std::unique_ptr ui; - - QByteArray m_peers; - QMutex m_guiLock; - QTimer* m_refresh; - QTimer* m_refreshNetwork; - QVector m_myKeys; - bool m_keysChanged = false; - int m_port; - int m_idealPeers; - QString m_clientName; - QStringList m_servers; - - QQuickView* m_view; - - QNetworkAccessManager m_webCtrl; - - std::unique_ptr m_client; -}; - -#endif // MAIN_H diff --git a/walleth/Resources.qrc b/walleth/Resources.qrc deleted file mode 100644 index 1789216ed..000000000 --- a/walleth/Resources.qrc +++ /dev/null @@ -1,5 +0,0 @@ - - - Simple.qml - - diff --git a/walleth/Simple.qml b/walleth/Simple.qml deleted file mode 100644 index 53cb7def4..000000000 --- a/walleth/Simple.qml +++ /dev/null @@ -1,38 +0,0 @@ -import QtQml 2.2 -import QtQuick 2.1 -import QtQuick.Controls 1.0 -import QtQuick.Layouts 1.0 -import Qt.labs.settings 1.0 -import org.ethereum 1.0 - -Item { - id: main - anchors.fill: parent - anchors.margins: 9 - -// Qt.application.name: "Walleth" -// Qt.application.organization: "Ethereum" -// Qt.application.domain: "org.ethereum" - - Ethereum { - id: eth - } - - Account { - id: myAccount - address: Key.addressOf("84fc4ba9373c30bfe32d8c5a502854e7f1175878") - ethereum: eth - // TODO: state: eth.latest // could be eth.pending - // will provide balance, txCount, isContract, incomingTransactions (list model), outgoingTransactions (list model). - // transaction lists' items will provide value, from, to, final balance. - } - - // KeyPair provides makeTransaction(recvAddress, value, data (array)) - - Text { - text: "Balance: " + Balance.stringOf(myAccount.balance) + " [" + myAccount.txCount + "]" + "\nAccount: " + Key.stringOf(myAccount.address) - Layout.minimumHeight: 30 - Layout.fillHeight: true - Layout.fillWidth: true - } -} diff --git a/walleth/main.cpp b/walleth/main.cpp deleted file mode 100644 index 42afd5e66..000000000 --- a/walleth/main.cpp +++ /dev/null @@ -1,11 +0,0 @@ -#include "MainWin.h" -#include - -int main(int argc, char *argv[]) -{ - QApplication a(argc, argv); - Main w; - w.show(); - - return a.exec(); -} diff --git a/windows/.gitattributes b/windows/.gitattributes deleted file mode 100644 index 48910107d..000000000 --- a/windows/.gitattributes +++ /dev/null @@ -1,2 +0,0 @@ -*.vcxproj eol=crlf -*.props eol=crlf diff --git a/windows/Alethzero.vcxproj b/windows/Alethzero.vcxproj deleted file mode 100644 index 38dbd6265..000000000 --- a/windows/Alethzero.vcxproj +++ /dev/null @@ -1,311 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - - Win32Proj - AlethZero - AlethZero - {BFCFFC46-78A3-4350-9938-0EA3A2B1CCCD} - - - - Application - true - v120 - - - Application - true - v120 - - - Application - false - v120 - - - Application - false - v120 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - true - - - - false - - - false - - - - Use - Disabled - WIN32;_WINSOCK_DEPRECATED_NO_WARNINGS;_DEBUG;%(PreprocessorDefinitions) - MultiThreadedDebugDLL - true - stdafx.h - - - Windows - true - true - - - - - - - - - Use - Disabled - WIN32;_DEBUG;%(PreprocessorDefinitions) - MultiThreadedDebugDLL - true - stdafx.h - - - Windows - true - - - - - - - - - Use - MaxSpeed - true - true - WIN32;_WINSOCK_DEPRECATED_NO_WARNINGS;NDEBUG;%(PreprocessorDefinitions) - MultiThreadedDLL - true - AnySuitable - stdafx.h - - - Windows - true - true - true - true - - - - - - - - - Use - MaxSpeed - true - true - WIN32;NDEBUG;%(PreprocessorDefinitions) - MultiThreadedDLL - true - AnySuitable - stdafx.h - - - Windows - true - true - true - - - - - - - - - {df3c5b07-a1a2-4f16-b37f-a27333622cdd} - - - {f174e81a-2a66-4693-b917-11bb42d3658c} - - - - - - - - - - Create - Create - Create - Create - - - - - - $(Lua) moc.lua "$(QtBin)/moc" "$(IntDir)moc_%(FileName).cpp" "@(ClCompile->'%(AdditionalIncludeDirectories)');$(IncludePath)" "@(ClCompile->'%(PreprocessorDefinitions)');_MSC_VER=1800" "%(FullPath)" - $(IntDir)moc_%(FileName).cpp - - - $(Lua) moc.lua "$(QtBin)/moc" "$(IntDir)moc_%(FileName).cpp" "@(ClCompile->'%(AdditionalIncludeDirectories)');$(IncludePath)" "@(ClCompile->'%(PreprocessorDefinitions)');_MSC_VER=1800" "%(FullPath)" - - - $(Lua) moc.lua "$(QtBin)/moc" "$(IntDir)moc_%(FileName).cpp" "@(ClCompile->'%(AdditionalIncludeDirectories)');$(IncludePath)" "@(ClCompile->'%(PreprocessorDefinitions)');_MSC_VER=1800" "%(FullPath)" - - - $(Lua) moc.lua "$(QtBin)/moc" "$(IntDir)moc_%(FileName).cpp" "@(ClCompile->'%(AdditionalIncludeDirectories)');$(IncludePath)" "@(ClCompile->'%(PreprocessorDefinitions)');_MSC_VER=1800" "%(FullPath)" - - - $(IntDir)moc_%(FileName).cpp - $(IntDir)moc_%(FileName).cpp - $(IntDir)moc_%(FileName).cpp - - - - - $(Lua) moc.lua "$(QtBin)/moc" "$(IntDir)moc_%(FileName).cpp" "@(ClCompile->'%(AdditionalIncludeDirectories)');$(IncludePath)" "@(ClCompile->'%(PreprocessorDefinitions)');_MSC_VER=1800" "%(FullPath)" - - - $(Lua) moc.lua "$(QtBin)/moc" "$(IntDir)moc_%(FileName).cpp" "@(ClCompile->'%(AdditionalIncludeDirectories)');$(IncludePath)" "@(ClCompile->'%(PreprocessorDefinitions)');_MSC_VER=1800" "%(FullPath)" - - - $(Lua) moc.lua "$(QtBin)/moc" "$(IntDir)moc_%(FileName).cpp" "@(ClCompile->'%(AdditionalIncludeDirectories)');$(IncludePath)" "@(ClCompile->'%(PreprocessorDefinitions)');_MSC_VER=1800" "%(FullPath)" - - - $(Lua) moc.lua "$(QtBin)/moc" "$(IntDir)moc_%(FileName).cpp" "@(ClCompile->'%(AdditionalIncludeDirectories)');$(IncludePath)" "@(ClCompile->'%(PreprocessorDefinitions)');_MSC_VER=1800" "%(FullPath)" - - - $(IntDir)moc_%(FileName).cpp - $(IntDir)moc_%(FileName).cpp - $(IntDir)moc_%(FileName).cpp - $(IntDir)moc_%(FileName).cpp - - - $(Lua) moc.lua "$(QtBin)/moc" "$(IntDir)moc_%(FileName).cpp" "@(ClCompile->'%(AdditionalIncludeDirectories)');$(IncludePath)" "@(ClCompile->'%(PreprocessorDefinitions)');_MSC_VER=1800" "%(FullPath)" - - - $(Lua) moc.lua "$(QtBin)/moc" "$(IntDir)moc_%(FileName).cpp" "@(ClCompile->'%(AdditionalIncludeDirectories)');$(IncludePath)" "@(ClCompile->'%(PreprocessorDefinitions)');_MSC_VER=1800" "%(FullPath)" - - - $(Lua) moc.lua "$(QtBin)/moc" "$(IntDir)moc_%(FileName).cpp" "@(ClCompile->'%(AdditionalIncludeDirectories)');$(IncludePath)" "@(ClCompile->'%(PreprocessorDefinitions)');_MSC_VER=1800" "%(FullPath)" - - - $(Lua) moc.lua "$(QtBin)/moc" "$(IntDir)moc_%(FileName).cpp" "@(ClCompile->'%(AdditionalIncludeDirectories)');$(IncludePath)" "@(ClCompile->'%(PreprocessorDefinitions)');_MSC_VER=1800" "%(FullPath)" - - - $(IntDir)moc_%(FileName).cpp - $(IntDir)moc_%(FileName).cpp - $(IntDir)moc_%(FileName).cpp - $(IntDir)moc_%(FileName).cpp - - - - - - Document - "$(QtBin)/uic" -o "$(IntDir)ui_%(FileName).h" "%(FullPath)" - "$(QtBin)/uic" -o "$(IntDir)ui_%(FileName).h" "%(FullPath)" - $(IntDir)ui_%(FileName).h - "$(QtBin)/uic" -o "$(IntDir)ui_%(FileName).h" "%(FullPath)" - "$(QtBin)/uic" -o "$(IntDir)ui_%(FileName).h" "%(FullPath)" - $(IntDir)ui_%(FileName).h - "$(QtBin)/uic" -o "$(IntDir)ui_%(FileName).h" "%(FullPath)" - "$(QtBin)/uic" -o "$(IntDir)ui_%(FileName).h" "%(FullPath)" - $(IntDir)ui_%(FileName).h - "$(QtBin)/uic" -o "$(IntDir)ui_%(FileName).h" "%(FullPath)" - "$(QtBin)/uic" -o "$(IntDir)ui_%(FileName).h" "%(FullPath)" - $(IntDir)ui_%(FileName).h - - - - - Document - $(Lua) "%(FullPath)" "$(IntDir)%(FileName).h" - - - $(Lua) "%(FullPath)" "$(IntDir)%(FileName).h" - - - $(Lua) "%(FullPath)" "$(IntDir)%(FileName).h" - - - $(Lua) "%(FullPath)" "$(IntDir)%(FileName).h" - - - $(IntDir)%(FileName).h - $(IntDir)%(FileName).h - $(IntDir)%(FileName).h - $(IntDir)%(FileName).h - ../.git/index - ../.git/index - ../.git/index - ../.git/index - - - - - - - - - - - - - $(BuildDependsOn);FinalCopy - - - - - - - - \ No newline at end of file diff --git a/windows/Alethzero.vcxproj.filters b/windows/Alethzero.vcxproj.filters deleted file mode 100644 index ef47bdba0..000000000 --- a/windows/Alethzero.vcxproj.filters +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - - Windows - - - Windows - - - - - - - - Windows - - - - - - - {049fb46c-1677-45cb-95ae-3a2d9e3090be} - - - - - - - Windows - - - - - \ No newline at end of file diff --git a/windows/BuildInfo.lua b/windows/BuildInfo.lua deleted file mode 100644 index 47b23a795..000000000 --- a/windows/BuildInfo.lua +++ /dev/null @@ -1,25 +0,0 @@ - -function os.capture(cmd) - local f = io.popen(cmd, 'r') - if (f) then - local s = f:read('*a') - if (f:close()) then - return s - end - end - return nil -end - -hash = (os.capture("git rev-parse HEAD") or "UnknownRevision"):gsub("\n$", "") -clean = ((os.capture("git diff --name-only") or "0"):gsub("\n$", "") == "") and "1" or "0" - -local output = io.open(arg[1], "w") -if (output) then - output:write("// This file was automatically generated by buildinfo.lua\n#pragma once\n\n") - output:write("#define ETH_COMMIT_HASH "..hash.."\n") - output:write("#define ETH_CLEAN_REPO "..clean.."\n") - output:close() -end - - - diff --git a/windows/Eth.vcxproj b/windows/Eth.vcxproj deleted file mode 100644 index 9b2d47727..000000000 --- a/windows/Eth.vcxproj +++ /dev/null @@ -1,195 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - - Win32Proj - Ethereum - eth - {C60C065C-2135-4B2B-AFD4-35FD7AC56B40} - - - - Application - true - v120 - - - Application - true - v120 - - - Application - false - v120 - - - Application - false - v120 - - - - - - - - - - - - - - - - - - - - - - - - - - - true - - - - false - - - false - - - - - - Disabled - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - MultiThreadedDebugDLL - true - - - Console - true - true - - - - - - - Disabled - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - MultiThreadedDebugDLL - true - - - Console - true - - - - - - - MaxSpeed - true - true - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - MultiThreadedDLL - true - AnySuitable - - - Console - true - true - true - true - - - - - - - MaxSpeed - true - true - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - MultiThreadedDLL - true - AnySuitable - - - Console - true - true - true - - - - - {826e68cb-d3ee-4a8a-b540-59a8c3f38d4f} - - - - - - - - Document - $(Lua) "%(FullPath)" "$(IntDir)%(FileName).h" - - - $(IntDir)%(FileName).h - $(Lua) "%(FullPath)" "$(IntDir)%(FileName).h" - - - $(IntDir)%(FileName).h - $(Lua) "%(FullPath)" "$(IntDir)%(FileName).h" - - - $(IntDir)%(FileName).h - $(Lua) "%(FullPath)" "$(IntDir)%(FileName).h" - - - $(IntDir)%(FileName).h - ../.git/index - ../.git/index - ../.git/index - ../.git/index - - - - - - - $(BuildDependsOn);FinalCopy - - - - - - - - \ No newline at end of file diff --git a/windows/Ethereum.sln b/windows/Ethereum.sln deleted file mode 100644 index 26fe794c2..000000000 --- a/windows/Ethereum.sln +++ /dev/null @@ -1,191 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Express 2013 for Windows Desktop -VisualStudioVersion = 12.0.21005.1 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Libs", "Libs", "{988F2383-FA1D-408B-BCF6-C0EE7AB0A560}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{6838FA95-01BF-4FF7-914C-FC209B81406E}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LibEthereum", "LibEthereum.vcxproj", "{826E68CB-D3EE-4A8A-B540-59A8C3F38D4F}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LibLevelDB", "LibLevelDB.vcxproj", "{27014763-955D-486B-9BA7-69872192E6F4}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LibSecp256k1", "LibSecp256k1.vcxproj", "{1E1175BB-C4A9-41D8-B2D1-9022F71D3CEA}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestSecp256k1", "TestSecp256k1.vcxproj", "{3BF049F8-AF7E-4E1C-9627-3E94C887AF24}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestEthereum", "TestEthereum.vcxproj", "{3F3E389B-88DE-41D5-A73B-4F6036E18B36}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LibCryptoPP", "LibCryptoPP.vcxproj", "{1CC213A4-3482-4211-B47B-172E90DAC7DE}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LibMiniUPnPc", "LibMiniUPnPc.vcxproj", "{1B1CA20E-39C3-4D9B-AC37-3783048E6672}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "AlethZero", "Alethzero.vcxproj", "{BFCFFC46-78A3-4350-9938-0EA3A2B1CCCD}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LibQEthereum", "LibQEthereum.vcxproj", "{DF3C5B07-A1A2-4F16-B37F-A27333622CDD}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "eth", "Eth.vcxproj", "{C60C065C-2135-4B2B-AFD4-35FD7AC56B40}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "neth", "Neth.vcxproj", "{90C70663-7181-4E99-9079-54188CEB8954}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LibSerpent", "LibSerpent.vcxproj", "{F174E81A-2A66-4693-B917-11BB42D3658C}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "exp", "Exp.vcxproj", "{9AA5CF66-1150-4A02-B40E-3B89740DADB8}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "sc", "Sc.vcxproj", "{90068D1B-070E-4C41-88B0-1E243E1E5BFF}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "lllc", "Lllc.vcxproj", "{255BDC68-B8DB-465F-8220-981E77684189}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Win32 = Debug|Win32 - Debug|x64 = Debug|x64 - Release|Win32 = Release|Win32 - Release|x64 = Release|x64 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {826E68CB-D3EE-4A8A-B540-59A8C3F38D4F}.Debug|Win32.ActiveCfg = Debug|Win32 - {826E68CB-D3EE-4A8A-B540-59A8C3F38D4F}.Debug|Win32.Build.0 = Debug|Win32 - {826E68CB-D3EE-4A8A-B540-59A8C3F38D4F}.Debug|x64.ActiveCfg = Debug|x64 - {826E68CB-D3EE-4A8A-B540-59A8C3F38D4F}.Debug|x64.Build.0 = Debug|x64 - {826E68CB-D3EE-4A8A-B540-59A8C3F38D4F}.Release|Win32.ActiveCfg = Release|Win32 - {826E68CB-D3EE-4A8A-B540-59A8C3F38D4F}.Release|Win32.Build.0 = Release|Win32 - {826E68CB-D3EE-4A8A-B540-59A8C3F38D4F}.Release|x64.ActiveCfg = Release|x64 - {826E68CB-D3EE-4A8A-B540-59A8C3F38D4F}.Release|x64.Build.0 = Release|x64 - {27014763-955D-486B-9BA7-69872192E6F4}.Debug|Win32.ActiveCfg = Debug|Win32 - {27014763-955D-486B-9BA7-69872192E6F4}.Debug|Win32.Build.0 = Debug|Win32 - {27014763-955D-486B-9BA7-69872192E6F4}.Debug|x64.ActiveCfg = Debug|x64 - {27014763-955D-486B-9BA7-69872192E6F4}.Debug|x64.Build.0 = Debug|x64 - {27014763-955D-486B-9BA7-69872192E6F4}.Release|Win32.ActiveCfg = Release|Win32 - {27014763-955D-486B-9BA7-69872192E6F4}.Release|Win32.Build.0 = Release|Win32 - {27014763-955D-486B-9BA7-69872192E6F4}.Release|x64.ActiveCfg = Release|x64 - {27014763-955D-486B-9BA7-69872192E6F4}.Release|x64.Build.0 = Release|x64 - {1E1175BB-C4A9-41D8-B2D1-9022F71D3CEA}.Debug|Win32.ActiveCfg = Debug|Win32 - {1E1175BB-C4A9-41D8-B2D1-9022F71D3CEA}.Debug|Win32.Build.0 = Debug|Win32 - {1E1175BB-C4A9-41D8-B2D1-9022F71D3CEA}.Debug|x64.ActiveCfg = Debug|x64 - {1E1175BB-C4A9-41D8-B2D1-9022F71D3CEA}.Debug|x64.Build.0 = Debug|x64 - {1E1175BB-C4A9-41D8-B2D1-9022F71D3CEA}.Release|Win32.ActiveCfg = Release|Win32 - {1E1175BB-C4A9-41D8-B2D1-9022F71D3CEA}.Release|Win32.Build.0 = Release|Win32 - {1E1175BB-C4A9-41D8-B2D1-9022F71D3CEA}.Release|x64.ActiveCfg = Release|x64 - {1E1175BB-C4A9-41D8-B2D1-9022F71D3CEA}.Release|x64.Build.0 = Release|x64 - {3BF049F8-AF7E-4E1C-9627-3E94C887AF24}.Debug|Win32.ActiveCfg = Debug|Win32 - {3BF049F8-AF7E-4E1C-9627-3E94C887AF24}.Debug|Win32.Build.0 = Debug|Win32 - {3BF049F8-AF7E-4E1C-9627-3E94C887AF24}.Debug|x64.ActiveCfg = Debug|x64 - {3BF049F8-AF7E-4E1C-9627-3E94C887AF24}.Debug|x64.Build.0 = Debug|x64 - {3BF049F8-AF7E-4E1C-9627-3E94C887AF24}.Release|Win32.ActiveCfg = Release|Win32 - {3BF049F8-AF7E-4E1C-9627-3E94C887AF24}.Release|Win32.Build.0 = Release|Win32 - {3BF049F8-AF7E-4E1C-9627-3E94C887AF24}.Release|x64.ActiveCfg = Release|x64 - {3BF049F8-AF7E-4E1C-9627-3E94C887AF24}.Release|x64.Build.0 = Release|x64 - {3F3E389B-88DE-41D5-A73B-4F6036E18B36}.Debug|Win32.ActiveCfg = Debug|Win32 - {3F3E389B-88DE-41D5-A73B-4F6036E18B36}.Debug|Win32.Build.0 = Debug|Win32 - {3F3E389B-88DE-41D5-A73B-4F6036E18B36}.Debug|x64.ActiveCfg = Debug|x64 - {3F3E389B-88DE-41D5-A73B-4F6036E18B36}.Debug|x64.Build.0 = Debug|x64 - {3F3E389B-88DE-41D5-A73B-4F6036E18B36}.Release|Win32.ActiveCfg = Release|Win32 - {3F3E389B-88DE-41D5-A73B-4F6036E18B36}.Release|Win32.Build.0 = Release|Win32 - {3F3E389B-88DE-41D5-A73B-4F6036E18B36}.Release|x64.ActiveCfg = Release|x64 - {3F3E389B-88DE-41D5-A73B-4F6036E18B36}.Release|x64.Build.0 = Release|x64 - {1CC213A4-3482-4211-B47B-172E90DAC7DE}.Debug|Win32.ActiveCfg = Debug|Win32 - {1CC213A4-3482-4211-B47B-172E90DAC7DE}.Debug|Win32.Build.0 = Debug|Win32 - {1CC213A4-3482-4211-B47B-172E90DAC7DE}.Debug|x64.ActiveCfg = Debug|x64 - {1CC213A4-3482-4211-B47B-172E90DAC7DE}.Debug|x64.Build.0 = Debug|x64 - {1CC213A4-3482-4211-B47B-172E90DAC7DE}.Release|Win32.ActiveCfg = Release|Win32 - {1CC213A4-3482-4211-B47B-172E90DAC7DE}.Release|Win32.Build.0 = Release|Win32 - {1CC213A4-3482-4211-B47B-172E90DAC7DE}.Release|x64.ActiveCfg = Release|x64 - {1CC213A4-3482-4211-B47B-172E90DAC7DE}.Release|x64.Build.0 = Release|x64 - {1B1CA20E-39C3-4D9B-AC37-3783048E6672}.Debug|Win32.ActiveCfg = Debug|Win32 - {1B1CA20E-39C3-4D9B-AC37-3783048E6672}.Debug|Win32.Build.0 = Debug|Win32 - {1B1CA20E-39C3-4D9B-AC37-3783048E6672}.Debug|x64.ActiveCfg = Debug|x64 - {1B1CA20E-39C3-4D9B-AC37-3783048E6672}.Debug|x64.Build.0 = Debug|x64 - {1B1CA20E-39C3-4D9B-AC37-3783048E6672}.Release|Win32.ActiveCfg = Release|Win32 - {1B1CA20E-39C3-4D9B-AC37-3783048E6672}.Release|Win32.Build.0 = Release|Win32 - {1B1CA20E-39C3-4D9B-AC37-3783048E6672}.Release|x64.ActiveCfg = Release|x64 - {1B1CA20E-39C3-4D9B-AC37-3783048E6672}.Release|x64.Build.0 = Release|x64 - {BFCFFC46-78A3-4350-9938-0EA3A2B1CCCD}.Debug|Win32.ActiveCfg = Debug|Win32 - {BFCFFC46-78A3-4350-9938-0EA3A2B1CCCD}.Debug|Win32.Build.0 = Debug|Win32 - {BFCFFC46-78A3-4350-9938-0EA3A2B1CCCD}.Debug|x64.ActiveCfg = Debug|x64 - {BFCFFC46-78A3-4350-9938-0EA3A2B1CCCD}.Debug|x64.Build.0 = Debug|x64 - {BFCFFC46-78A3-4350-9938-0EA3A2B1CCCD}.Release|Win32.ActiveCfg = Release|Win32 - {BFCFFC46-78A3-4350-9938-0EA3A2B1CCCD}.Release|Win32.Build.0 = Release|Win32 - {BFCFFC46-78A3-4350-9938-0EA3A2B1CCCD}.Release|x64.ActiveCfg = Release|x64 - {BFCFFC46-78A3-4350-9938-0EA3A2B1CCCD}.Release|x64.Build.0 = Release|x64 - {326EF470-463F-4751-A22A-48BBAAD8B143}.Debug|Win32.ActiveCfg = Debug|Win32 - {326EF470-463F-4751-A22A-48BBAAD8B143}.Debug|Win32.Build.0 = Debug|Win32 - {326EF470-463F-4751-A22A-48BBAAD8B143}.Debug|x64.ActiveCfg = Debug|x64 - {326EF470-463F-4751-A22A-48BBAAD8B143}.Debug|x64.Build.0 = Debug|x64 - {326EF470-463F-4751-A22A-48BBAAD8B143}.Release|Win32.ActiveCfg = Release|Win32 - {326EF470-463F-4751-A22A-48BBAAD8B143}.Release|Win32.Build.0 = Release|Win32 - {326EF470-463F-4751-A22A-48BBAAD8B143}.Release|x64.ActiveCfg = Release|x64 - {326EF470-463F-4751-A22A-48BBAAD8B143}.Release|x64.Build.0 = Release|x64 - {DF3C5B07-A1A2-4F16-B37F-A27333622CDD}.Debug|Win32.ActiveCfg = Debug|Win32 - {DF3C5B07-A1A2-4F16-B37F-A27333622CDD}.Debug|Win32.Build.0 = Debug|Win32 - {DF3C5B07-A1A2-4F16-B37F-A27333622CDD}.Debug|x64.ActiveCfg = Debug|x64 - {DF3C5B07-A1A2-4F16-B37F-A27333622CDD}.Debug|x64.Build.0 = Debug|x64 - {DF3C5B07-A1A2-4F16-B37F-A27333622CDD}.Release|Win32.ActiveCfg = Release|Win32 - {DF3C5B07-A1A2-4F16-B37F-A27333622CDD}.Release|Win32.Build.0 = Release|Win32 - {DF3C5B07-A1A2-4F16-B37F-A27333622CDD}.Release|x64.ActiveCfg = Release|x64 - {DF3C5B07-A1A2-4F16-B37F-A27333622CDD}.Release|x64.Build.0 = Release|x64 - {C60C065C-2135-4B2B-AFD4-35FD7AC56B40}.Debug|Win32.ActiveCfg = Debug|Win32 - {C60C065C-2135-4B2B-AFD4-35FD7AC56B40}.Debug|Win32.Build.0 = Debug|Win32 - {C60C065C-2135-4B2B-AFD4-35FD7AC56B40}.Debug|x64.ActiveCfg = Debug|x64 - {C60C065C-2135-4B2B-AFD4-35FD7AC56B40}.Debug|x64.Build.0 = Debug|x64 - {C60C065C-2135-4B2B-AFD4-35FD7AC56B40}.Release|Win32.ActiveCfg = Release|Win32 - {C60C065C-2135-4B2B-AFD4-35FD7AC56B40}.Release|Win32.Build.0 = Release|Win32 - {C60C065C-2135-4B2B-AFD4-35FD7AC56B40}.Release|x64.ActiveCfg = Release|x64 - {C60C065C-2135-4B2B-AFD4-35FD7AC56B40}.Release|x64.Build.0 = Release|x64 - {90C70663-7181-4E99-9079-54188CEB8954}.Debug|Win32.ActiveCfg = Debug|Win32 - {90C70663-7181-4E99-9079-54188CEB8954}.Debug|Win32.Build.0 = Debug|Win32 - {90C70663-7181-4E99-9079-54188CEB8954}.Debug|x64.ActiveCfg = Debug|x64 - {90C70663-7181-4E99-9079-54188CEB8954}.Debug|x64.Build.0 = Debug|x64 - {90C70663-7181-4E99-9079-54188CEB8954}.Release|Win32.ActiveCfg = Release|Win32 - {90C70663-7181-4E99-9079-54188CEB8954}.Release|Win32.Build.0 = Release|Win32 - {90C70663-7181-4E99-9079-54188CEB8954}.Release|x64.ActiveCfg = Release|x64 - {90C70663-7181-4E99-9079-54188CEB8954}.Release|x64.Build.0 = Release|x64 - {F174E81A-2A66-4693-B917-11BB42D3658C}.Debug|Win32.ActiveCfg = Debug|Win32 - {F174E81A-2A66-4693-B917-11BB42D3658C}.Debug|Win32.Build.0 = Debug|Win32 - {F174E81A-2A66-4693-B917-11BB42D3658C}.Debug|x64.ActiveCfg = Debug|x64 - {F174E81A-2A66-4693-B917-11BB42D3658C}.Debug|x64.Build.0 = Debug|x64 - {F174E81A-2A66-4693-B917-11BB42D3658C}.Release|Win32.ActiveCfg = Release|Win32 - {F174E81A-2A66-4693-B917-11BB42D3658C}.Release|Win32.Build.0 = Release|Win32 - {F174E81A-2A66-4693-B917-11BB42D3658C}.Release|x64.ActiveCfg = Release|x64 - {F174E81A-2A66-4693-B917-11BB42D3658C}.Release|x64.Build.0 = Release|x64 - {9AA5CF66-1150-4A02-B40E-3B89740DADB8}.Debug|Win32.ActiveCfg = Debug|Win32 - {9AA5CF66-1150-4A02-B40E-3B89740DADB8}.Debug|Win32.Build.0 = Debug|Win32 - {9AA5CF66-1150-4A02-B40E-3B89740DADB8}.Debug|x64.ActiveCfg = Debug|x64 - {9AA5CF66-1150-4A02-B40E-3B89740DADB8}.Debug|x64.Build.0 = Debug|x64 - {9AA5CF66-1150-4A02-B40E-3B89740DADB8}.Release|Win32.ActiveCfg = Release|Win32 - {9AA5CF66-1150-4A02-B40E-3B89740DADB8}.Release|Win32.Build.0 = Release|Win32 - {9AA5CF66-1150-4A02-B40E-3B89740DADB8}.Release|x64.ActiveCfg = Release|x64 - {9AA5CF66-1150-4A02-B40E-3B89740DADB8}.Release|x64.Build.0 = Release|x64 - {90068D1B-070E-4C41-88B0-1E243E1E5BFF}.Debug|Win32.ActiveCfg = Debug|Win32 - {90068D1B-070E-4C41-88B0-1E243E1E5BFF}.Debug|Win32.Build.0 = Debug|Win32 - {90068D1B-070E-4C41-88B0-1E243E1E5BFF}.Debug|x64.ActiveCfg = Debug|x64 - {90068D1B-070E-4C41-88B0-1E243E1E5BFF}.Debug|x64.Build.0 = Debug|x64 - {90068D1B-070E-4C41-88B0-1E243E1E5BFF}.Release|Win32.ActiveCfg = Release|Win32 - {90068D1B-070E-4C41-88B0-1E243E1E5BFF}.Release|Win32.Build.0 = Release|Win32 - {90068D1B-070E-4C41-88B0-1E243E1E5BFF}.Release|x64.ActiveCfg = Release|x64 - {90068D1B-070E-4C41-88B0-1E243E1E5BFF}.Release|x64.Build.0 = Release|x64 - {255BDC68-B8DB-465F-8220-981E77684189}.Debug|Win32.ActiveCfg = Debug|Win32 - {255BDC68-B8DB-465F-8220-981E77684189}.Debug|Win32.Build.0 = Debug|Win32 - {255BDC68-B8DB-465F-8220-981E77684189}.Debug|x64.ActiveCfg = Debug|x64 - {255BDC68-B8DB-465F-8220-981E77684189}.Debug|x64.Build.0 = Debug|x64 - {255BDC68-B8DB-465F-8220-981E77684189}.Release|Win32.ActiveCfg = Release|Win32 - {255BDC68-B8DB-465F-8220-981E77684189}.Release|Win32.Build.0 = Release|Win32 - {255BDC68-B8DB-465F-8220-981E77684189}.Release|x64.ActiveCfg = Release|x64 - {255BDC68-B8DB-465F-8220-981E77684189}.Release|x64.Build.0 = Release|x64 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(NestedProjects) = preSolution - {826E68CB-D3EE-4A8A-B540-59A8C3F38D4F} = {988F2383-FA1D-408B-BCF6-C0EE7AB0A560} - {27014763-955D-486B-9BA7-69872192E6F4} = {988F2383-FA1D-408B-BCF6-C0EE7AB0A560} - {1E1175BB-C4A9-41D8-B2D1-9022F71D3CEA} = {988F2383-FA1D-408B-BCF6-C0EE7AB0A560} - {1CC213A4-3482-4211-B47B-172E90DAC7DE} = {988F2383-FA1D-408B-BCF6-C0EE7AB0A560} - {1B1CA20E-39C3-4D9B-AC37-3783048E6672} = {988F2383-FA1D-408B-BCF6-C0EE7AB0A560} - {DF3C5B07-A1A2-4F16-B37F-A27333622CDD} = {988F2383-FA1D-408B-BCF6-C0EE7AB0A560} - {F174E81A-2A66-4693-B917-11BB42D3658C} = {988F2383-FA1D-408B-BCF6-C0EE7AB0A560} - {3BF049F8-AF7E-4E1C-9627-3E94C887AF24} = {6838FA95-01BF-4FF7-914C-FC209B81406E} - {3F3E389B-88DE-41D5-A73B-4F6036E18B36} = {6838FA95-01BF-4FF7-914C-FC209B81406E} - EndGlobalSection -EndGlobal diff --git a/windows/Ethereum.vcxproj.filters b/windows/Ethereum.vcxproj.filters deleted file mode 100644 index 0bee64924..000000000 --- a/windows/Ethereum.vcxproj.filters +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - {ed0eafbf-bbfb-4700-b7c0-9b58049cc681} - - - - - Windows - - - \ No newline at end of file diff --git a/windows/Exp.vcxproj b/windows/Exp.vcxproj deleted file mode 100644 index cf4eb5d2e..000000000 --- a/windows/Exp.vcxproj +++ /dev/null @@ -1,195 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - - Win32Proj - Ethereum - exp - {9AA5CF66-1150-4A02-B40E-3B89740DADB8} - - - - Application - true - v120 - - - Application - true - v120 - - - Application - false - v120 - - - Application - false - v120 - - - - - - - - - - - - - - - - - - - - - - - - - - - true - - - - false - - - false - - - - - - Disabled - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - MultiThreadedDebugDLL - true - - - Console - true - true - - - - - - - Disabled - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - MultiThreadedDebugDLL - true - - - Console - true - - - - - - - MaxSpeed - true - true - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - MultiThreadedDLL - true - AnySuitable - - - Console - true - true - true - true - - - - - - - MaxSpeed - true - true - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - MultiThreadedDLL - true - AnySuitable - - - Console - true - true - true - - - - - {826e68cb-d3ee-4a8a-b540-59a8c3f38d4f} - - - - - Document - $(Lua) "%(FullPath)" "$(IntDir)%(FileName).h" - - - $(IntDir)%(FileName).h - $(Lua) "%(FullPath)" "$(IntDir)%(FileName).h" - - - $(IntDir)%(FileName).h - $(Lua) "%(FullPath)" "$(IntDir)%(FileName).h" - - - $(IntDir)%(FileName).h - $(Lua) "%(FullPath)" "$(IntDir)%(FileName).h" - - - $(IntDir)%(FileName).h - ../.git/index - ../.git/index - ../.git/index - ../.git/index - - - - - - - - - - $(BuildDependsOn);FinalCopy - - - - - - - - \ No newline at end of file diff --git a/windows/LibCryptoPP.vcxproj b/windows/LibCryptoPP.vcxproj deleted file mode 100644 index 032ae5fa6..000000000 --- a/windows/LibCryptoPP.vcxproj +++ /dev/null @@ -1,414 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Document - ml64.exe /c /nologo /Fo"$(IntDir)x64dll.obj" /Zi "%(FullPath)" - ml64.exe /c /nologo /Fo"$(IntDir)x64dll.obj" /Zi "%(FullPath)" - $(IntDir)x64dll.obj - $(IntDir)x64dll.obj - - - - Win32Proj - LibCryptoPP - {1CC213A4-3482-4211-B47B-172E90DAC7DE} - - - - StaticLibrary - true - v120 - - - StaticLibrary - true - v120 - - - StaticLibrary - false - v120 - - - StaticLibrary - false - v120 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Disabled - MultiThreadedDebugDLL - 4100;4189;4244;%(DisableSpecificWarnings) - - - Windows - true - - - - - - - Disabled - MultiThreadedDebugDLL - 4100;4189;4244;%(DisableSpecificWarnings) - - - Windows - true - - - - - - - MaxSpeed - true - true - MultiThreadedDLL - 4100;4189;4244;%(DisableSpecificWarnings) - - - Windows - true - true - true - - - - - - - MaxSpeed - true - true - MultiThreadedDLL - 4100;4189;4244;%(DisableSpecificWarnings) - - - Windows - true - true - true - - - - - - \ No newline at end of file diff --git a/windows/LibEthereum.props b/windows/LibEthereum.props deleted file mode 100644 index 8c0bcac90..000000000 --- a/windows/LibEthereum.props +++ /dev/null @@ -1,35 +0,0 @@ - - - - - ../../boost - "../../lua/lua" - - - ..\..\_build\$(ProjectName)\$(Platform)_$(Configuration)\ - ..\..\_build\$(ProjectName)\$(Platform)_$(Configuration)\ - - - - 4068;4244;4267 - true - false - include/$(ProjectName);$(IntDir);../../cryptopp;..;../libethcore;../libethereum;../libethsupport;$(BoostDir);../../leveldb/include;../secp256k1;../../miniupnp - ETH_BUILD_PLATFORM=Windows/VS2013;ETH_BUILD_TYPE=$(Configuration)-$(Platform);ETH_MINIUPNPC=1;STATICLIB;LEVELDB_PLATFORM_WINDOWS;USE_NUM_BOOST;USE_FIELD_10X26;USE_FIELD_INV_BUILTIN;_WIN32_WINNT=0x0501;WIN32;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - true - true - Level3 - - - $(BoostDir)/stage/$(Platform) - - - - - $(BoostDir) - - - $(Lua) - - - \ No newline at end of file diff --git a/windows/LibEthereum.vcxproj b/windows/LibEthereum.vcxproj deleted file mode 100644 index 30deea983..000000000 --- a/windows/LibEthereum.vcxproj +++ /dev/null @@ -1,570 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - - - - - - - - - - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - - - - - - - - - - - - - - - - - - - - - - - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - - - - - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - - - true - true - true - true - - - - stdafx.h - Create - Create - Create - Create - - - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - - - - - - - - - - - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - - - - - - - - - - - - - - - - - - - - - - - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - - - - - - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - true - true - true - true - - - - true - true - true - true - - - true - true - true - true - - - - - - {1cc213a4-3482-4211-b47b-172e90dac7de} - - - {27014763-955d-486b-9ba7-69872192e6f4} - - - {1b1ca20e-39c3-4d9b-ac37-3783048e6672} - - - {1e1175bb-c4a9-41d8-b2d1-9022f71d3cea} - - - - {826E68CB-D3EE-4A8A-B540-59A8C3F38D4F} - Win32Proj - LibEthereum - - - - StaticLibrary - true - v120 - - - StaticLibrary - true - v120 - - - StaticLibrary - false - v120 - - - StaticLibrary - false - v120 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Disabled - WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions) - false - MultiThreadedDebugDLL - Use - stdafx.h - - - Windows - true - - - - - Disabled - WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions) - false - MultiThreadedDebugDLL - stdafx.h - Use - - - Windows - true - - - - - - - MaxSpeed - true - true - WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions) - true - MultiThreadedDLL - Use - stdafx.h - - - Windows - true - true - true - - - - - MaxSpeed - true - true - WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions) - true - MultiThreadedDLL - Use - stdafx.h - - - Windows - true - true - true - - - - - - diff --git a/windows/LibEthereum.vcxproj.filters b/windows/LibEthereum.vcxproj.filters deleted file mode 100644 index 514320472..000000000 --- a/windows/LibEthereum.vcxproj.filters +++ /dev/null @@ -1,474 +0,0 @@ - - - - - Windows - - - libethereum - - - libethereum - - - libethereum - - - libethereum - - - libethereum - - - libethereum - - - libethereum - - - libethereum - - - libevm - - - libevm - - - libevm - - - libevmcore - - - liblll - - - liblll - - - liblll - - - liblll - - - liblll - - - libethereum - - - libethereum - - - libethereum - - - libethereum - - - libethereum - - - libethereum - - - libethereum - - - libdevcrypto - - - libdevcrypto - - - libdevcrypto - - - libdevcrypto - - - libdevcrypto - - - libdevcrypto - - - libdevcrypto - - - libethcore - - - libethcore - - - libethcore - - - libdevcore - - - libdevcore - - - libdevcore - - - libdevcore - - - libdevcore - - - libdevcore - - - libdevcore - - - libethcore - - - libevm - - - libethereum - - - libethereum - - - libethereum - - - libethereum - - - libethereum - - - libp2p - - - libp2p - - - libp2p - - - libp2p - - - libp2p - - - libp2p - - - libwhisper - - - libwhisper - - - libethereum - - - libdevcore - - - libdevcore - - - libethereum - - - libwebthree - - - libethcore - - - libdevcrypto - - - libdevcrypto - - - libdevcrypto - - - libethereum - - - - - Windows - - - libethereum - - - libethereum - - - libethereum - - - libethereum - - - libethereum - - - libethereum - - - libethereum - - - libethereum - - - libevm - - - libevm - - - libevm - - - libevm - - - libevmcore - - - liblll - - - libevmcore - - - liblll - - - liblll - - - liblll - - - liblll - - - liblll - - - libethereum - - - libethereum - - - libethereum - - - libethereum - - - libethereum - - - libethereum - - - libethereum - - - libdevcrypto - - - libdevcrypto - - - libdevcrypto - - - libdevcrypto - - - libdevcrypto - - - libdevcrypto - - - libdevcrypto - - - libdevcrypto - - - libdevcrypto - - - libethcore - - - libethcore - - - libethcore - - - libethcore - - - libethcore - - - libethcore - - - libdevcore - - - libdevcore - - - libdevcore - - - libdevcore - - - libdevcore - - - libdevcore - - - libdevcore - - - libdevcore - - - libdevcore - - - libdevcore - - - libethereum - - - libethereum - - - libethereum - - - libethereum - - - libethereum - - - libethereum - - - libp2p - - - libp2p - - - libp2p - - - libp2p - - - libp2p - - - libp2p - - - libp2p - - - libwhisper - - - libwhisper - - - libethereum - - - libdevcore - - - libdevcore - - - libethereum - - - libwebthree - - - libdevcrypto - - - libdevcrypto - - - libdevcrypto - - - libethereum - - - - - {2d571d8f-bacf-4c49-a0d0-c9036f5c0cc9} - - - {8275e3be-c870-44a2-8185-5a9992af8f8e} - - - {b246b3d7-af02-4125-a254-2b377214c288} - - - {37c37803-1515-47c1-b7e6-3879f4429ab3} - - - {ed9ad1b3-700c-47f9-8548-a90b5ef179ac} - - - {e6332606-e0ca-48aa-8a6b-303971ba7a93} - - - {fae2102b-d574-40fc-9f90-1b9ed0d117ac} - - - {35c32f6c-3f19-4603-8084-1b88ec9ae498} - - - {fc2cb618-ab0c-45b6-8eb9-6d88e0336fa9} - - - {36748e80-c977-4fee-84e6-699c039dff87} - - - {d838fece-fc20-42f6-bff5-97c236159b80} - - - diff --git a/windows/LibEthereum_Debug.props b/windows/LibEthereum_Debug.props deleted file mode 100644 index 6d322078a..000000000 --- a/windows/LibEthereum_Debug.props +++ /dev/null @@ -1,18 +0,0 @@ - - - - - d - d - - - - - - $(DebugSuffix) - - - $(d) - - - \ No newline at end of file diff --git a/windows/LibEthereum_Release.props b/windows/LibEthereum_Release.props deleted file mode 100644 index 8f0436f61..000000000 --- a/windows/LibEthereum_Release.props +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - $(DebugSuffix) - - - \ No newline at end of file diff --git a/windows/LibLevelDB.vcxproj b/windows/LibLevelDB.vcxproj deleted file mode 100644 index 3e2407da6..000000000 --- a/windows/LibLevelDB.vcxproj +++ /dev/null @@ -1,221 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - {27014763-955D-486B-9BA7-69872192E6F4} - Win32Proj - LibLevelDB - - - - StaticLibrary - true - v120 - - - StaticLibrary - true - v120 - - - StaticLibrary - false - v120 - - - StaticLibrary - false - v120 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Disabled - MultiThreadedDebugDLL - %(AdditionalIncludeDirectories);../../leveldb - _CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - 4018;4100;4244;4267;4389;4702;4722;4800;4996;%(DisableSpecificWarnings) - - - Windows - true - - - - - - - Disabled - MultiThreadedDebugDLL - %(AdditionalIncludeDirectories);../../leveldb - _CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - 4018;4100;4244;4267;4389;4702;4722;4800;4996;%(DisableSpecificWarnings) - - - Windows - true - - - - - - - MaxSpeed - true - true - MultiThreadedDLL - %(AdditionalIncludeDirectories);../../leveldb - _CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - 4018;4100;4244;4267;4389;4702;4722;4800;4996;%(DisableSpecificWarnings) - - - Windows - true - true - true - - - - - - - MaxSpeed - true - true - MultiThreadedDLL - %(AdditionalIncludeDirectories);../../leveldb - _CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - 4018;4100;4244;4267;4389;4702;4722;4800;4996;%(DisableSpecificWarnings) - - - Windows - true - true - true - - - - - - \ No newline at end of file diff --git a/windows/LibLevelDB.vcxproj.filters b/windows/LibLevelDB.vcxproj.filters deleted file mode 100644 index bc3306f56..000000000 --- a/windows/LibLevelDB.vcxproj.filters +++ /dev/null @@ -1,246 +0,0 @@ - - - - - {d83904b1-b5d1-4c5b-b476-96f08300d103} - - - {72573022-b7fd-4b7a-a92e-a68c06bd6366} - - - {7f821e9e-4ebf-4d18-8fb4-898bd3d81376} - - - {f285a595-6c39-4350-8d30-6f696a3a7c4c} - - - - - db - - - db - - - db - - - db - - - db - - - db - - - db - - - db - - - db - - - db - - - db - - - db - - - db - - - db - - - db - - - table - - - table - - - table - - - table - - - table - - - table - - - util - - - util - - - util - - - util - - - util - - - util - - - util - - - util - - - util - - - util - - - util - - - util - - - port - - - port - - - port - - - - - db - - - db - - - db - - - db - - - db - - - db - - - db - - - db - - - db - - - db - - - db - - - db - - - db - - - db - - - db - - - table - - - table - - - table - - - table - - - table - - - table - - - table - - - table - - - util - - - util - - - util - - - util - - - util - - - util - - - util - - - util - - - util - - - util - - - util - - - util - - - util - - - util - - - util - - - port - - - \ No newline at end of file diff --git a/windows/LibMiniUPnPc.vcxproj b/windows/LibMiniUPnPc.vcxproj deleted file mode 100644 index 07489d0e8..000000000 --- a/windows/LibMiniUPnPc.vcxproj +++ /dev/null @@ -1,182 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Win32Proj - LibMiniUPnPc - {1B1CA20E-39C3-4D9B-AC37-3783048E6672} - LibMiniUPnPc - - - - StaticLibrary - true - v120 - - - StaticLibrary - true - v120 - - - StaticLibrary - false - v120 - - - StaticLibrary - false - v120 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Disabled - MultiThreadedDebugDLL - _CRT_SECURE_NO_WARNINGS;_WINSOCK_DEPRECATED_NO_WARNINGS;MINIUPNP_STATICLIB;_WINSOCK_DEPRECATED_NO_WARNINGS;%(PreprocessorDefinitions) - 4100;4244;4245;4267;4389;%(DisableSpecificWarnings) - - - Windows - true - - - Iphlpapi.lib - - - - - - - Disabled - MultiThreadedDebugDLL - _CRT_SECURE_NO_WARNINGS;_WINSOCK_DEPRECATED_NO_WARNINGS;MINIUPNP_STATICLIB;%(PreprocessorDefinitions) - 4100;4244;4245;4267;4389;%(DisableSpecificWarnings) - - - Windows - true - - - Iphlpapi.lib - - - - - - - MaxSpeed - true - true - MultiThreadedDLL - _CRT_SECURE_NO_WARNINGS;_WINSOCK_DEPRECATED_NO_WARNINGS;MINIUPNP_STATICLIB;_WINSOCK_DEPRECATED_NO_WARNINGS;%(PreprocessorDefinitions) - 4100;4244;4245;4267;4389;%(DisableSpecificWarnings) - - - Windows - true - true - true - - - Iphlpapi.lib - - - - - - - MaxSpeed - true - true - MultiThreadedDLL - _CRT_SECURE_NO_WARNINGS;_WINSOCK_DEPRECATED_NO_WARNINGS;MINIUPNP_STATICLIB;%(PreprocessorDefinitions) - 4100;4244;4245;4267;4389;%(DisableSpecificWarnings) - - - Windows - true - true - true - - - Iphlpapi.lib - - - - - - \ No newline at end of file diff --git a/windows/LibQEthereum.props b/windows/LibQEthereum.props deleted file mode 100644 index 08ba05c69..000000000 --- a/windows/LibQEthereum.props +++ /dev/null @@ -1,70 +0,0 @@ - - - - - ../../Qt/$(Platform) - $(QtDir)/qtbase - $(QtBase)/bin - $(QtBase)/include;../../Qt/Src/qtbase/include;../../Qt/Src/qtbase/include/QtCore;../../Qt/Src/qtbase/include/QtWidgets;../../Qt/Src/qtbase/include/QtQml;../../Qt/Src/qtbase/include/QtGui;../../Qt/Src/qtdeclarative/include;../../Qt/Src/qtwebkit/include - $(QtBase)/lib;$(QtBase)/plugins/platforms;../../icu/lib64 - ..\..\icu\bin_$(Platform)\icu*52.dll;$(QtBase)\lib\Qt5Core$(d).dll;$(QtBase)\lib\Qt5Gui$(d).dll;$(QtBase)\lib\Qt5Multimedia$(d).dll;$(QtBase)\lib\Qt5MultimediaWidgets$(d).dll;$(QtBase)\lib\Qt5OpenGL$(d).dll;$(QtBase)\lib\Qt5Positioning$(d).dll;$(QtBase)\lib\Qt5PrintSupport$(d).dll;$(QtBase)\lib\Qt5Network$(d).dll;$(QtBase)\lib\Qt5Qml$(d).dll;$(QtBase)\lib\Qt5Quick$(d).dll;$(QtBase)\lib\Qt5Sensors$(d).dll;$(QtBase)\lib\Qt5Sql$(d).dll;$(QtBase)\lib\Qt5Webkit$(d).dll;$(QtBase)\lib\Qt5WebkitWidgets$(d).dll;$(QtBase)\lib\Qt5Widgets$(d).dll;$(QtBase)\plugins\**\qwindows$(d).dll;$(QtBase)\plugins\**\qgenericbearer$(d).dll;$(QtBase)\plugins\**\qnativewifibearer$(d).dll;$(QtBase)\plugins\**\qgif$(d).dll;$(QtBase)\plugins\**\qico$(d).dll;$(QtBase)\plugins\**\qjpeg$(d).dll;$(QtBase)\plugins\**\qsvg$(d).dll;$(QtBase)\plugins\**\qtsensors_dummy$(d).dll - - - <_PropertySheetDisplayName>LibQEthereum - - - - - ..;$(QtInclude);%(AdditionalIncludeDirectories) - 4718;%(DisableSpecificWarnings) - ETH_QTQML=1;%(PreprocessorDefinitions) - - - - - - - - - $(QtLib);%(AdditionalLibraryDirectories) - Qt5PlatformSupport$(d).lib;Qt5Core$(d).lib;Qt5GUI$(d).lib;Qt5Network$(d).lib;Qt5Quick$(d).lib;Qt5Qml$(d).lib;Qt5Webkit$(d).lib;Qt5WebkitWidgets$(d).lib;Qt5Widgets$(d).lib;%(AdditionalDependencies) - - - - - $(QtDir) - - - $(QtBase) - - - $(QtBin) - - - $(QtInclude) - - - $(QtLib) - - - $(CopyDlls) - - - - - - - - - - \ No newline at end of file diff --git a/windows/LibQEthereum.vcxproj b/windows/LibQEthereum.vcxproj deleted file mode 100644 index 20b29e06e..000000000 --- a/windows/LibQEthereum.vcxproj +++ /dev/null @@ -1,204 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - - - {826e68cb-d3ee-4a8a-b540-59a8c3f38d4f} - - - - - - - Create - Create - Create - Create - - - - - $(Lua) moc.lua "$(QtBin)/moc" "$(IntDir)moc_%(FileName).cpp" "@(ClCompile->'%(AdditionalIncludeDirectories)');$(IncludePath)" "@(ClCompile->'%(PreprocessorDefinitions)');_MSC_VER=1800" "%(FullPath)" - $(Lua) moc.lua "$(QtBin)/moc" "$(IntDir)moc_%(FileName).cpp" "@(ClCompile->'%(AdditionalIncludeDirectories)');$(IncludePath)" "@(ClCompile->'%(PreprocessorDefinitions)');_MSC_VER=1800" "%(FullPath)" - $(Lua) moc.lua "$(QtBin)/moc" "$(IntDir)moc_%(FileName).cpp" "@(ClCompile->'%(AdditionalIncludeDirectories)');$(IncludePath)" "@(ClCompile->'%(PreprocessorDefinitions)');_MSC_VER=1800" "%(FullPath)" - $(Lua) moc.lua "$(QtBin)/moc" "$(IntDir)moc_%(FileName).cpp" "@(ClCompile->'%(AdditionalIncludeDirectories)');$(IncludePath)" "@(ClCompile->'%(PreprocessorDefinitions)');_MSC_VER=1800" "%(FullPath)" - - - $(IntDir)moc_%(FileName).cpp - - - $(IntDir)moc_%(FileName).cpp - - - $(IntDir)moc_%(FileName).cpp - - - $(IntDir)moc_%(FileName).cpp - - - - - $(Lua) moc.lua "$(QtBin)/moc" "$(IntDir)moc_%(FileName).cpp" "@(ClCompile->'%(AdditionalIncludeDirectories)');$(IncludePath)" "@(ClCompile->'%(PreprocessorDefinitions)');_MSC_VER=1800" "%(FullPath)" - - - $(Lua) moc.lua "$(QtBin)/moc" "$(IntDir)moc_%(FileName).cpp" "@(ClCompile->'%(AdditionalIncludeDirectories)');$(IncludePath)" "@(ClCompile->'%(PreprocessorDefinitions)');_MSC_VER=1800" "%(FullPath)" - - - $(Lua) moc.lua "$(QtBin)/moc" "$(IntDir)moc_%(FileName).cpp" "@(ClCompile->'%(AdditionalIncludeDirectories)');$(IncludePath)" "@(ClCompile->'%(PreprocessorDefinitions)');_MSC_VER=1800" "%(FullPath)" - - - $(Lua) moc.lua "$(QtBin)/moc" "$(IntDir)moc_%(FileName).cpp" "@(ClCompile->'%(AdditionalIncludeDirectories)');$(IncludePath)" "@(ClCompile->'%(PreprocessorDefinitions)');_MSC_VER=1800" "%(FullPath)" - - - $(IntDir)moc_%(FileName).cpp - $(IntDir)moc_%(FileName).cpp - $(IntDir)moc_%(FileName).cpp - $(IntDir)moc_%(FileName).cpp - - - - - Win32Proj - LibQEthereum - {DF3C5B07-A1A2-4F16-B37F-A27333622CDD} - - - - StaticLibrary - true - v120 - - - StaticLibrary - true - v120 - - - StaticLibrary - false - v120 - - - StaticLibrary - false - v120 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Disabled - WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions) - false - MultiThreadedDebugDLL - Use - stdafx.h - - - Windows - true - - - - - Disabled - WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions) - false - MultiThreadedDebugDLL - stdafx.h - Use - - - Windows - true - - - - - - - MaxSpeed - true - true - WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions) - true - MultiThreadedDLL - Use - stdafx.h - - - Windows - true - true - true - - - - - MaxSpeed - true - true - WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions) - true - MultiThreadedDLL - Use - stdafx.h - - - Windows - true - true - true - - - - - - \ No newline at end of file diff --git a/windows/LibQEthereum.vcxproj.filters b/windows/LibQEthereum.vcxproj.filters deleted file mode 100644 index e38730504..000000000 --- a/windows/LibQEthereum.vcxproj.filters +++ /dev/null @@ -1,24 +0,0 @@ - - - - - {516a3655-70df-49f7-af1f-008cf4acf934} - - - - - Windows - - - - - - - Windows - - - - - - - \ No newline at end of file diff --git a/windows/LibSecp256k1.vcxproj b/windows/LibSecp256k1.vcxproj deleted file mode 100644 index 37df3b3b6..000000000 --- a/windows/LibSecp256k1.vcxproj +++ /dev/null @@ -1,183 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - CompileAsCpp - CompileAsCpp - CompileAsCpp - CompileAsCpp - - - - - - - Win32Proj - LibSecp256k1 - {1E1175BB-C4A9-41D8-B2D1-9022F71D3CEA} - LibSecp256k1 - - - - StaticLibrary - true - v120 - - - StaticLibrary - true - v120 - - - StaticLibrary - false - v120 - - - StaticLibrary - false - v120 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Level3 - Disabled - WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions) - MultiThreadedDebugDLL - 4189;4244;4267;%(DisableSpecificWarnings) - - - Windows - true - - - - - - - Level3 - Disabled - WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions) - MultiThreadedDebugDLL - 4189;4244;4267;%(DisableSpecificWarnings) - - - Windows - true - - - - - Level3 - - - MaxSpeed - true - true - WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions) - MultiThreadedDLL - 4189;4244;4267;%(DisableSpecificWarnings) - - - Windows - true - true - true - - - - - Level3 - - - MaxSpeed - true - true - WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions) - MultiThreadedDLL - 4189;4244;4267;%(DisableSpecificWarnings) - - - Windows - true - true - true - - - - - - \ No newline at end of file diff --git a/windows/LibSecp256k1.vcxproj.filters b/windows/LibSecp256k1.vcxproj.filters deleted file mode 100644 index aa4e5b9cb..000000000 --- a/windows/LibSecp256k1.vcxproj.filters +++ /dev/null @@ -1,71 +0,0 @@ - - - - - {7d4db365-bce7-45c1-861c-f5f86beca992} - - - - - impl - - - impl - - - impl - - - impl - - - impl - - - impl - - - impl - - - impl - - - impl - - - impl - - - impl - - - impl - - - impl - - - impl - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/windows/LibSerpent.vcxproj b/windows/LibSerpent.vcxproj deleted file mode 100644 index 925d4915b..000000000 --- a/windows/LibSerpent.vcxproj +++ /dev/null @@ -1,187 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - - - {1cc213a4-3482-4211-b47b-172e90dac7de} - - - {27014763-955d-486b-9ba7-69872192e6f4} - - - {1b1ca20e-39c3-4d9b-ac37-3783048e6672} - - - {1e1175bb-c4a9-41d8-b2d1-9022f71d3cea} - - - - - - - - - - - - - - - - - - - - - - - - - - Create - Create - Create - Create - - - - Win32Proj - LibSerpent - {F174E81A-2A66-4693-B917-11BB42D3658C} - - - - StaticLibrary - true - v120 - - - StaticLibrary - true - v120 - - - StaticLibrary - false - v120 - - - StaticLibrary - false - v120 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Disabled - WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions) - false - MultiThreadedDebugDLL - Use - stdafx.h - - - Windows - true - - - - - Disabled - WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions) - false - MultiThreadedDebugDLL - stdafx.h - Use - - - Windows - true - - - - - - - MaxSpeed - true - true - WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions) - true - MultiThreadedDLL - Use - stdafx.h - - - Windows - true - true - true - - - - - MaxSpeed - true - true - WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions) - true - MultiThreadedDLL - Use - stdafx.h - - - Windows - true - true - true - - - - - - \ No newline at end of file diff --git a/windows/LibSerpent.vcxproj.filters b/windows/LibSerpent.vcxproj.filters deleted file mode 100644 index 65df02da3..000000000 --- a/windows/LibSerpent.vcxproj.filters +++ /dev/null @@ -1,18 +0,0 @@ - - - - - {20ea55ad-2a66-41df-a64e-9fed221f544f} - - - - - Windows - - - - - Windows - - - \ No newline at end of file diff --git a/windows/Lllc.vcxproj b/windows/Lllc.vcxproj deleted file mode 100644 index 70306d656..000000000 --- a/windows/Lllc.vcxproj +++ /dev/null @@ -1,195 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - - Win32Proj - Ethereum - lllc - {255BDC68-B8DB-465F-8220-981E77684189} - - - - Application - true - v120 - - - Application - true - v120 - - - Application - false - v120 - - - Application - false - v120 - - - - - - - - - - - - - - - - - - - - - - - - - - - true - - - - false - - - false - - - - - - Disabled - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - MultiThreadedDebugDLL - true - - - Console - true - true - - - - - - - Disabled - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - MultiThreadedDebugDLL - true - - - Console - true - - - - - - - MaxSpeed - true - true - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - MultiThreadedDLL - true - AnySuitable - - - Console - true - true - true - true - - - - - - - MaxSpeed - true - true - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - MultiThreadedDLL - true - AnySuitable - - - Console - true - true - true - - - - - {826e68cb-d3ee-4a8a-b540-59a8c3f38d4f} - - - - - Document - $(Lua) "%(FullPath)" "$(IntDir)%(FileName).h" - - - $(IntDir)%(FileName).h - $(Lua) "%(FullPath)" "$(IntDir)%(FileName).h" - - - $(IntDir)%(FileName).h - $(Lua) "%(FullPath)" "$(IntDir)%(FileName).h" - - - $(IntDir)%(FileName).h - $(Lua) "%(FullPath)" "$(IntDir)%(FileName).h" - - - $(IntDir)%(FileName).h - ../.git/index - ../.git/index - ../.git/index - ../.git/index - - - - - - - - - - $(BuildDependsOn);FinalCopy - - - - - - - - \ No newline at end of file diff --git a/windows/Neth.vcxproj b/windows/Neth.vcxproj deleted file mode 100644 index a778b78d8..000000000 --- a/windows/Neth.vcxproj +++ /dev/null @@ -1,213 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - - Win32Proj - Nethereum - neth - {90C70663-7181-4E99-9079-54188CEB8954} - - - - Application - true - v120 - - - Application - true - v120 - - - Application - false - v120 - - - Application - false - v120 - - - - - - - - - - - - - - - - - - - - - - - - - - - true - - - - false - - - false - - - - - - Disabled - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - MultiThreadedDebugDLL - true - ncurses/include;ncurses/include/ncurses;%(AdditionalIncludeDirectories) - - - Console - true - true - $(BoostDir)/stage/$(Platform);ncurses/lib/$(Platform) - wncurses.lib;wform.lib;wmenu.lib;wpanel.lib;%(AdditionalDependencies) - - - - - - - Disabled - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - MultiThreadedDebugDLL - true - ncurses/include;ncurses/include/ncurses;ncurses/include/ncurses;%(AdditionalIncludeDirectories) - - - Console - true - $(BoostDir)/stage/$(Platform);ncurses/lib/$(Platform) - wncurses.lib;wform.lib;wmenu.lib;wpanel.lib;%(AdditionalDependencies) - - - - - - - MaxSpeed - true - true - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - MultiThreadedDLL - true - AnySuitable - ncurses/include;ncurses/include/ncurses;%(AdditionalIncludeDirectories) - - - Console - true - true - true - true - $(BoostDir)/stage/$(Platform);ncurses/lib/$(Platform) - wncurses.lib;wform.lib;wmenu.lib;wpanel.lib;%(AdditionalDependencies) - - - - - - - MaxSpeed - true - true - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - MultiThreadedDLL - true - AnySuitable - ncurses/include;ncurses/include/ncurses;%(AdditionalIncludeDirectories) - - - Console - true - true - true - $(BoostDir)/stage/$(Platform);ncurses/lib/$(Platform) - wncurses.lib;wform.lib;wmenu.lib;wpanel.lib;%(AdditionalDependencies) - - - - - {826e68cb-d3ee-4a8a-b540-59a8c3f38d4f} - - - - - Document - $(Lua) "%(FullPath)" "$(IntDir)%(FileName).h" - - - $(IntDir)%(FileName).h - $(Lua) "%(FullPath)" "$(IntDir)%(FileName).h" - - - $(IntDir)%(FileName).h - $(Lua) "%(FullPath)" "$(IntDir)%(FileName).h" - - - $(IntDir)%(FileName).h - $(Lua) "%(FullPath)" "$(IntDir)%(FileName).h" - - - $(IntDir)%(FileName).h - ../.git/index - ../.git/index - ../.git/index - ../.git/index - - - - - - - - - - $(BuildDependsOn);FinalCopy - - - - - - - - - - - - - - \ No newline at end of file diff --git a/windows/Sc.vcxproj b/windows/Sc.vcxproj deleted file mode 100644 index 8dc0e1dee..000000000 --- a/windows/Sc.vcxproj +++ /dev/null @@ -1,198 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - - Win32Proj - Ethereum - sc - {90068D1B-070E-4C41-88B0-1E243E1E5BFF} - - - - Application - true - v120 - - - Application - true - v120 - - - Application - false - v120 - - - Application - false - v120 - - - - - - - - - - - - - - - - - - - - - - - - - - - true - - - - false - - - false - - - - - - Disabled - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - MultiThreadedDebugDLL - true - - - Console - true - true - - - - - - - Disabled - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - MultiThreadedDebugDLL - true - - - Console - true - - - - - - - MaxSpeed - true - true - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - MultiThreadedDLL - true - AnySuitable - - - Console - true - true - true - true - - - - - - - MaxSpeed - true - true - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - MultiThreadedDLL - true - AnySuitable - - - Console - true - true - true - - - - - {826e68cb-d3ee-4a8a-b540-59a8c3f38d4f} - - - {f174e81a-2a66-4693-b917-11bb42d3658c} - - - - - Document - $(Lua) "%(FullPath)" "$(IntDir)%(FileName).h" - - - $(IntDir)%(FileName).h - $(Lua) "%(FullPath)" "$(IntDir)%(FileName).h" - - - $(IntDir)%(FileName).h - $(Lua) "%(FullPath)" "$(IntDir)%(FileName).h" - - - $(IntDir)%(FileName).h - $(Lua) "%(FullPath)" "$(IntDir)%(FileName).h" - - - $(IntDir)%(FileName).h - ../.git/index - ../.git/index - ../.git/index - ../.git/index - - - - - - - - - - $(BuildDependsOn);FinalCopy - - - - - - - - \ No newline at end of file diff --git a/windows/TestEthereum.vcxproj b/windows/TestEthereum.vcxproj deleted file mode 100644 index 172e6be86..000000000 --- a/windows/TestEthereum.vcxproj +++ /dev/null @@ -1,194 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - - Win32Proj - TestEthereum - TestEthereum - {3F3E389B-88DE-41D5-A73B-4F6036E18B36} - - - - Application - true - v120 - - - Application - true - v120 - - - Application - false - v120 - - - Application - false - v120 - - - - - - - - - - - - - - - - - - - - - - - true - - - true - - - false - - - false - - - - Use - Disabled - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - MultiThreadedDebugDLL - true - true - stdafx.h - Async - - - Console - true - true - - - - - Use - Disabled - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - MultiThreadedDebugDLL - true - stdafx.h - Async - - - Console - true - - - - - Use - MaxSpeed - true - true - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - MultiThreadedDLL - true - AnySuitable - true - stdafx.h - Async - - - Console - true - true - true - true - - - - - Use - MaxSpeed - true - true - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - MultiThreadedDLL - true - AnySuitable - true - stdafx.h - Async - - - Console - true - true - true - - - - - {826e68cb-d3ee-4a8a-b540-59a8c3f38d4f} - - - - - - - - - - - - - - - - - - - - - Create - Create - Create - Create - - - - - - - - - - - - - \ No newline at end of file diff --git a/windows/TestEthereum.vcxproj.filters b/windows/TestEthereum.vcxproj.filters deleted file mode 100644 index 4be707aec..000000000 --- a/windows/TestEthereum.vcxproj.filters +++ /dev/null @@ -1,38 +0,0 @@ - - - - - Windows - - - - - - - - - - - - - - - - - - - - - {0acd7e2f-2594-4c13-94cb-3247045bdbfd} - - - - - Windows - - - - - - - \ No newline at end of file diff --git a/windows/TestSecp256k1.vcxproj b/windows/TestSecp256k1.vcxproj deleted file mode 100644 index d2c113d4c..000000000 --- a/windows/TestSecp256k1.vcxproj +++ /dev/null @@ -1,171 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - - - CompileAsCpp - CompileAsCpp - CompileAsCpp - CompileAsCpp - - - - - {1e1175bb-c4a9-41d8-b2d1-9022f71d3cea} - - - - Win32Proj - TestSecp256k1 - TestSecp256k1 - {3BF049F8-AF7E-4E1C-9627-3E94C887AF24} - - - - Application - true - v120 - - - Application - true - v120 - - - Application - false - v120 - - - Application - false - v120 - - - - - - - - - - - - - - - - - - - - - - - true - - - true - - - false - - - false - - - - - - Disabled - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - MultiThreadedDebugDLL - true - true - 4189;4244;4267;%(DisableSpecificWarnings) - - - Console - true - true - - - - - - - Disabled - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - MultiThreadedDebugDLL - true - 4189;4244;4267;%(DisableSpecificWarnings) - - - Console - true - - - - - - - MaxSpeed - true - true - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - MultiThreadedDLL - true - AnySuitable - true - 4189;4244;4267;%(DisableSpecificWarnings) - - - Console - true - true - true - true - - - - - - - MaxSpeed - true - true - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - MultiThreadedDLL - true - AnySuitable - true - 4189;4244;4267;%(DisableSpecificWarnings) - - - Console - true - true - true - - - - - - \ No newline at end of file diff --git a/windows/Walleth.vcxproj b/windows/Walleth.vcxproj deleted file mode 100644 index ad76f0f01..000000000 --- a/windows/Walleth.vcxproj +++ /dev/null @@ -1,315 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - - Win32Proj - Walleth - Walleth - {326EF470-463F-4751-A22A-48BBAAD8B143} - - - - Application - true - v120 - - - Application - true - v120 - - - Application - false - v120 - - - Application - false - v120 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - true - - - - false - - - false - - - - Use - Disabled - WIN32;_DEBUG;%(PreprocessorDefinitions) - MultiThreadedDebugDLL - true - stdafx.h - - - Windows - true - true - - - - - - - - - - - - - - - Use - Disabled - WIN32;_DEBUG;%(PreprocessorDefinitions) - MultiThreadedDebugDLL - true - stdafx.h - - - Windows - true - - - - - - - - - - - - - - - - Use - MaxSpeed - true - true - WIN32;NDEBUG;%(PreprocessorDefinitions) - MultiThreadedDLL - true - AnySuitable - stdafx.h - - - Windows - true - true - true - true - - - - - - - - - - - - - - - Use - MaxSpeed - true - true - WIN32;NDEBUG;%(PreprocessorDefinitions) - MultiThreadedDLL - true - AnySuitable - stdafx.h - - - Windows - true - true - true - - - - - - - - - - - - - - - - - - Create - Create - Create - Create - - - - - - $(Lua) moc.lua "$(QtBin)/moc" "$(IntDir)moc_%(FileName).cpp" "@(ClCompile->'%(AdditionalIncludeDirectories)');$(IncludePath)" "@(ClCompile->'%(PreprocessorDefinitions)');_MSC_VER=1800" "%(FullPath)" - $(IntDir)moc_%(FileName).cpp - - - $(Lua) moc.lua "$(QtBin)/moc" "$(IntDir)moc_%(FileName).cpp" "@(ClCompile->'%(AdditionalIncludeDirectories)');$(IncludePath)" "@(ClCompile->'%(PreprocessorDefinitions)');_MSC_VER=1800" "%(FullPath)" - - - $(Lua) moc.lua "$(QtBin)/moc" "$(IntDir)moc_%(FileName).cpp" "@(ClCompile->'%(AdditionalIncludeDirectories)');$(IncludePath)" "@(ClCompile->'%(PreprocessorDefinitions)');_MSC_VER=1800" "%(FullPath)" - - - $(Lua) moc.lua "$(QtBin)/moc" "$(IntDir)moc_%(FileName).cpp" "@(ClCompile->'%(AdditionalIncludeDirectories)');$(IncludePath)" "@(ClCompile->'%(PreprocessorDefinitions)');_MSC_VER=1800" "%(FullPath)" - - - $(IntDir)moc_%(FileName).cpp - $(IntDir)moc_%(FileName).cpp - $(IntDir)moc_%(FileName).cpp - - - - - - Document - "$(QtBin)/uic" -o "$(IntDir)ui_%(FileName).h" "%(FullPath)" - "$(QtBin)/uic" -o "$(IntDir)ui_%(FileName).h" "%(FullPath)" - $(IntDir)ui_%(FileName).h - "$(QtBin)/uic" -o "$(IntDir)ui_%(FileName).h" "%(FullPath)" - "$(QtBin)/uic" -o "$(IntDir)ui_%(FileName).h" "%(FullPath)" - $(IntDir)ui_%(FileName).h - "$(QtBin)/uic" -o "$(IntDir)ui_%(FileName).h" "%(FullPath)" - "$(QtBin)/uic" -o "$(IntDir)ui_%(FileName).h" "%(FullPath)" - $(IntDir)ui_%(FileName).h - "$(QtBin)/uic" -o "$(IntDir)ui_%(FileName).h" "%(FullPath)" - "$(QtBin)/uic" -o "$(IntDir)ui_%(FileName).h" "%(FullPath)" - $(IntDir)ui_%(FileName).h - - - - - Document - $(Lua) "%(FullPath)" "$(IntDir)%(FileName).h" - - - $(Lua) "%(FullPath)" "$(IntDir)%(FileName).h" - - - $(Lua) "%(FullPath)" "$(IntDir)%(FileName).h" - - - $(Lua) "%(FullPath)" "$(IntDir)%(FileName).h" - - - $(IntDir)%(FileName).h - $(IntDir)%(FileName).h - $(IntDir)%(FileName).h - $(IntDir)%(FileName).h - ../.git/index - ../.git/index - ../.git/index - ../.git/index - - - - - {df3c5b07-a1a2-4f16-b37f-a27333622cdd} - - - - - Document - "$(QtBin)/rcc" -o "$(IntDir)qrc_%(FileName).cpp" "%(FullPath)" - "$(QtBin)/rcc" -o "$(IntDir)qrc_%(FileName).cpp" "%(FullPath)" - "$(QtBin)/rcc" -o "$(IntDir)qrc_%(FileName).cpp" "%(FullPath)" - "$(QtBin)/rcc" -o "$(IntDir)qrc_%(FileName).cpp" "%(FullPath)" - "$(QtBin)/rcc" -o "$(IntDir)qrc_%(FileName).cpp" "%(FullPath)" - "$(QtBin)/rcc" -o "$(IntDir)qrc_%(FileName).cpp" "%(FullPath)" - "$(QtBin)/rcc" -o "$(IntDir)qrc_%(FileName).cpp" "%(FullPath)" - "$(QtBin)/rcc" -o "$(IntDir)qrc_%(FileName).cpp" "%(FullPath)" - $(IntDir)qrc_%(FileName).cpp - $(IntDir)qrc_%(FileName).cpp - $(IntDir)qrc_%(FileName).cpp - $(IntDir)qrc_%(FileName).cpp - ../Walleth/Simple.qml - ../Walleth/Simple.qml - ../Walleth/Simple.qml - ../Walleth/Simple.qml - - - - - - - - - - - - - - $(BuildDependsOn);FinalCopy - - - - - - - - \ No newline at end of file diff --git a/windows/Walleth.vcxproj.filters b/windows/Walleth.vcxproj.filters deleted file mode 100644 index 804248d9f..000000000 --- a/windows/Walleth.vcxproj.filters +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - Windows - - - Windows - - - - - - - Windows - - - - - - {37f5b48c-b602-474b-8683-041898e328b5} - - - - - Windows - - - - - - \ No newline at end of file diff --git a/windows/WinMain.cpp b/windows/WinMain.cpp deleted file mode 100644 index d2fc147ca..000000000 --- a/windows/WinMain.cpp +++ /dev/null @@ -1,72 +0,0 @@ -// http://www.flipcode.com/archives/WinMain_Command_Line_Parser.shtml -// COTD Entry submitted by Max McGuire [amcguire@andrew.cmu.edu] - -#include - -extern int main(int argc, char* argv[]); - -int WINAPI WinMain(HINSTANCE /*instance*/, HINSTANCE /*prev_instance*/, char* command_line, int /*show_command*/) -{ - int argc; - char** argv; - char* arg; - int index; - int result; - - // count the arguments - argc = 1; - arg = command_line; - - while (arg[0] != 0) - { - while (arg[0] != 0 && arg[0] == ' ') - { - arg++; - } - if (arg[0] != 0) - { - argc++; - while (arg[0] != 0 && arg[0] != ' ') - { - arg++; - } - } - } - - // tokenize the arguments - argv = (char**)malloc(argc * sizeof(char*)); - arg = command_line; - index = 1; - - while (arg[0] != 0) - { - while (arg[0] != 0 && arg[0] == ' ') - { - arg++; - } - if (arg[0] != 0) - { - argv[index] = arg; - index++; - while (arg[0] != 0 && arg[0] != ' ') - { - arg++; - } - if (arg[0] != 0) - { - arg[0] = 0; - arg++; - } - } - } - - // put the program name into argv[0] - char filename[_MAX_PATH]; - GetModuleFileName(NULL, filename, _MAX_PATH); - argv[0] = filename; - - // call the user specified main function - result = main(argc, argv); - free(argv); - return result; -} diff --git a/windows/bootstrap.sh b/windows/bootstrap.sh deleted file mode 100644 index 642c3f5c8..000000000 --- a/windows/bootstrap.sh +++ /dev/null @@ -1,233 +0,0 @@ -#!/bin/bash -# @file bootstrap.sh -# @author Tim Hughes -# @date 2014 -# Script to fetch and compile depdencies for building Ethereum using Visual Studio Express 2013. -# Prerequisites: -# - Visual Studio Express 2013 for Desktop -# - On PATH: bash, git, git-svn, curl, 7z, perl, ruby, python - -error_exit() -{ - echo $1 1>&2 - exit 1 -} - -# check for existance of basic tools -for i in gawk sed curl git 7z; do - which $i &>/dev/null || error_exit "Could not find $i on PATH" -done - -# get commands before they are removed from the path -sed=`which sed` -awk=`which gawk` -which=`which which` - -path_remove() -{ - export PATH=`echo -n $PATH | "$awk" -v RS=: -v ORS=: '$0 != "'$1'"' | "$sed" 's/:$//'` -} - -path_remove_bin() -{ - path_remove "/bin" - path_remove "/usr/bin" - path_remove "/usr/local/bin" -} - -# check for native perl, python and ruby installations (needed by Qt) -( - path_remove_bin; - for i in ruby python perl; do - "$which" $i &>/dev/null || error_exit "Could not find $i on PATH" - done -) - -if [ ! -d "$VS120COMNTOOLS" ]; then - error_exit "Couldn't find Visual Studio 2013" -fi - -if [[ ! $@ ]] || [ $1 == "fetch" ]; then - # fetch ethereum (develop branch) - if [ ! -d cpp-ethereum ]; then - (set -x; git clone https://github.com/ethereum/cpp-ethereum.git) - cd cpp-ethereum - (set -x; git checkout -b develop origin/develop) - cd .. - echo - fi - - # fetch CryptoPP-5.6.2 - if [ ! -d cryptopp ]; then - (set -x; git svn clone -r 541:541 http://svn.code.sf.net/p/cryptopp/code/trunk/c5 cryptopp) - echo - fi - - # fetch MiniUPnP-1.8 - if [ ! -d miniupnp ]; then - (set -x; git clone https://github.com/miniupnp/miniupnp.git) - cd miniupnp - (set -x; git checkout tags/miniupnpd_1_8) - cd .. - echo - fi - - # fetch LevelDB (windows branch) - if [ ! -d leveldb ]; then - (set -x; git clone https://code.google.com/p/leveldb/) - cd leveldb - (set -x; git checkout origin/windows) - cd .. - echo - fi - - # fetch and unpack boost-1.55 source - if [ ! -d boost ]; then - if [ ! -f _download/boost_1_55_0.7z ]; then - (set -x; mkdir -p _download) - (set -x; curl -o _download/boost_1_55_0.7z -L http://sourceforge.net/projects/boost/files/boost/1.55.0/boost_1_55_0.7z/download) - fi - (set -x; 7z x _download/boost_1_55_0.7z) - (set -x; mv boost_1_55_0 boost) - echo - fi - - # fetch and unpack icu - if [ ! -d icu ]; then - git svn clone -rHEAD http://source.icu-project.org/repos/icu/icu/tags/release-52-1 icu - cd icu - # patch for VS2013 and Windows Qt build - git am --3way --ignore-space-change -s ../cpp-ethereum/windows/patches/icu/0*.patch - cd .. - fi - - # fetch and unpack Qt 5.1.2 source - if [ ! -d Qt ]; then - if [ ! -f _download/qt-everywhere-opensource-src-5.2.1.zip ]; then - (set -x; mkdir -p _download) - (set -x; curl -o _download/qt-everywhere-opensource-src-5.2.1.zip -L http://download.qt-project.org/official_releases/qt/5.2/5.2.1/single/qt-everywhere-opensource-src-5.2.1.zip) - fi - (set -x; mkdir Qt) - cd Qt - (set -x; 7z x ../_download/qt-everywhere-opensource-src-5.2.1.zip) - (set -x; mv qt-everywhere-opensource-src-5.2.1 Src) - cd .. - echo - fi - - # fetch jom - if [ ! -f "Qt/jom/jom.exe" ]; then - if [ ! -f "_download/jom.zip" ]; then - (set -x; mkdir -p _download) - (set -x; curl -o "_download/jom.zip" -L http://download.qt-project.org/official_releases/jom/jom.zip) - fi - (set -x; mkdir -p Qt/jom) - cd Qt/jom - (set -x; 7z x ../../_download/jom.zip) - cd ../.. - echo - fi - - # fetch and unpack Lua binaries - if [ ! -d lua ]; then - if [ ! -f _download/lua-5.2.1_Win32_bin.zip ]; then - (set -x; mkdir -p _download) - (set -x; curl -o _download/lua-5.2.1_Win32_bin.zip -L http://sourceforge.net/projects/luabinaries/files/5.2.1/Executables/lua-5.2.1_Win32_bin.zip/download) - fi - (set -x; mkdir lua) - cd lua - (set -x; 7z x ../_download/lua-5.2.1_Win32_bin.zip lua52.exe lua52.dll) - (set -x; mv lua52.exe lua.exe) - cd .. - echo - fi -fi - -compile_boost() -{ - if [ $platform == "x64" ]; then - addressModel="address-model=64" - else - addressModel="" - fi - - if [ ! -d "stage/$platform" ]; then - targets="--with-filesystem --with-system --with-thread --with-date_time --with-regex --with-test" - (set -x; ./b2 -j4 --build-type=complete link=static runtime-link=shared variant=debug,release threading=multi $addressModel $targets stage) - (set -x; mv stage/lib stage/$platform) - fi -} - -if [[ ! $@ ]] || [ $1 == "compile-boost" ]; then - # bootstrap if b2 is missing - cd boost - if [ ! -f "b2.exe" ]; then - (set -x; cmd.exe /c bootstrap.bat) - fi - - # compile boost for x86 and x64 - platform="x64"; compile_boost - platform="Win32"; compile_boost - cd .. - echo -fi - -compile_icu() -{ - if [ ! -d lib_$platform ] || [ ! -d bin_$platform ]; then - (set -x; cmd.exe /c "..\\cpp-ethereum\\windows\\compile_icu.bat $platform") - if [ $platform == "x64" ]; then - icu_suff="64" - else - icu_suff="" - fi - rm -rf lib_$platform - rm -rf bin_$platform - mv lib$icu_suff lib_$platform - mv bin$icu_suff bin_$platform - fi -} - -if [[ ! $@ ]] || [ $1 == "compile-icu" ]; then - cd icu - platform="x64"; compile_icu - platform="Win32"; compile_icu - cd .. -fi - -compile_qt() -{ - if [ ! -d $platform ]; then - ( - set -x - - # copy icu dlls to Qt bin folder (this is so the Qt tools work without global adjustment to PATH) - mkdir -p $platform/qtbase/bin - cp -a ../icu/bin_$platform/*.dll $platform/qtbase/bin/ - - ( - # remove bash paths - set +x - path_remove_bin - set -x - - # compile qt - cmd.exe /c "..\\cpp-ethereum\\windows\\compile_qt.bat $platform" - ) - ) - fi -} - -if [[ ! $@ ]] || [ $1 == "compile-qt" ]; then - # compile Qt for x86 and x64 - cd Qt - platform="x64"; compile_qt - platform="Win32"; compile_qt - cd .. - echo -fi - -# finally run MS build -cd cpp-ethereum/windows -cmd.exe /c "compile_ethereum.bat" -cd .. \ No newline at end of file diff --git a/windows/compile_ethereum.bat b/windows/compile_ethereum.bat deleted file mode 100644 index 6aa93b155..000000000 --- a/windows/compile_ethereum.bat +++ /dev/null @@ -1,14 +0,0 @@ -@echo off -rem @file compile_ethereum.bat -rem @author Tim Hughes -rem @date 2014 -echo on - -rem : import VC environment -call "%VS120COMNTOOLS%\VsDevCmd.bat" - -rem : build for x64 -msbuild /maxcpucount /p:Configuration=Release;Platform=x64 Ethereum.sln - -rem : build for Win32 -msbuild /maxcpucount /p:Configuration=Release;Platform=Win32 Ethereum.sln diff --git a/windows/compile_icu.bat b/windows/compile_icu.bat deleted file mode 100644 index 93bd21976..000000000 --- a/windows/compile_icu.bat +++ /dev/null @@ -1,11 +0,0 @@ -@echo off -rem @file compile_icu.bat -rem @author Tim Hughes -rem @date 2014 -echo on - -rem : import VC environment -call "%VS120COMNTOOLS%\VsDevCmd.bat" - -rem : build for platform -msbuild /maxcpucount /p:Configuration=Release;Platform=%1% source/allinone/icu.sln diff --git a/windows/compile_qt.bat b/windows/compile_qt.bat deleted file mode 100644 index b11fd42d5..000000000 --- a/windows/compile_qt.bat +++ /dev/null @@ -1,51 +0,0 @@ -@echo off -rem @file compileqt.bat -rem @author Tim Hughes -rem @date 2014 - -rem : enable use prefix if we want to produce standalone Qt binaries -rem : off by default since this takes longer and duplicates all the headers -set USE_PREFIX=0 - -rem : echo commands so we can see what's going on -echo on - -rem : select platform and toolset from first argument -IF %1%==x64 (set PLATFORM=x64&set TOOLSET=x86_amd64&set) ELSE (set PLATFORM=Win32&set TOOLSET=x86=) - -rem : import VC environment vars -call "%VS120COMNTOOLS%\..\..\VC\vcvarsall.bat" %TOOLSET% - -rem : assume our root Qt dir is the current dir -set QT=%CD% - -set PATH=%QT%\Src\gnuwin32\bin;%PATH% - -rem : create the build folder and add the qtbase/bin folder to the PATH -if not exist %QT%\%PLATFORM%\Makefile ( - set DO_CONFIGURE=1 - mkdir %QT%\%PLATFORM% -) else ( - set DO_CONFIGURE=0 -) -if %USE_PREFIX%==1 ( - if not exist %QT%\%PLATFORM%-Build mkdir %QT%\%PLATFORM%-Build - if not exist %QT%\%PLATFORM%\qtbase mkdir %QT%\%PLATFORM%\qtbase - cd %QT%\%PLATFORM%-Build - set QT_PREFIX=-prefix %Qt%\%PLATFORM%\qtbase - set QT_TARGETS=install -) else ( - cd %QT%\%PLATFORM% - set QT_PREFIX= - set QT_TARGETS= -) -set PATH=%CD%\qtbase\bin;%PATH% - -rem : run Qt configure with desired settings -if %DO_CONFIGURE%==1 ( - call %QT%\Src\configure.bat %QT_PREFIX% -opensource -confirm-license -debug-and-release -opengl desktop -platform win32-msvc2013 -icu -I "%QT%\..\icu\include" -L "%QT%\..\icu\lib_%PLATFORM%" -nomake tests -nomake examples -) - -rem : compile and install module-qtbase -%QT%\jom\jom - diff --git a/windows/include/LibLevelDB/port/port.h b/windows/include/LibLevelDB/port/port.h deleted file mode 100644 index ce7ae19c4..000000000 --- a/windows/include/LibLevelDB/port/port.h +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (c) 2011 The LevelDB Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. See the AUTHORS file for names of contributors. - -#ifndef STORAGE_LEVELDB_PORT_PORT_H_ -#define STORAGE_LEVELDB_PORT_PORT_H_ - -#include - -// Include the appropriate platform specific file below. If you are -// porting to a new platform, see "port_example.h" for documentation -// of what the new port_.h file must provide. -#if defined(LEVELDB_PLATFORM_POSIX) -# include "port/port_posix.h" -#elif defined(LEVELDB_PLATFORM_CHROMIUM) -# include "port/port_chromium.h" -#elif defined(LEVELDB_PLATFORM_ANDROID) -# include "port/port_android.h" -#elif defined(LEVELDB_PLATFORM_WINDOWS) -# include "port/port_win.h" -#endif - -#endif // STORAGE_LEVELDB_PORT_PORT_H_ diff --git a/windows/include/LibLevelDB/unistd.h b/windows/include/LibLevelDB/unistd.h deleted file mode 100644 index e69de29bb..000000000 diff --git a/windows/include/LibMiniUPnPc/miniupnpcstrings.h b/windows/include/LibMiniUPnPc/miniupnpcstrings.h deleted file mode 100644 index 364342ecf..000000000 --- a/windows/include/LibMiniUPnPc/miniupnpcstrings.h +++ /dev/null @@ -1,14 +0,0 @@ -/* $Id: miniupnpcstrings.h.in,v 1.4 2011/01/04 11:41:53 nanard Exp $ */ -/* Project: miniupnp - * http://miniupnp.free.fr/ or http://miniupnp.tuxfamily.org/ - * Author: Thomas Bernard - * Copyright (c) 2005-2011 Thomas Bernard - * This software is subjects to the conditions detailed - * in the LICENCE file provided within this distribution */ -#ifndef MINIUPNPCSTRINGS_H_INCLUDED -#define MINIUPNPCSTRINGS_H_INCLUDED - -#define OS_STRING "Windows" -#define MINIUPNPC_VERSION_STRING "1.9" - -#endif diff --git a/windows/moc.lua b/windows/moc.lua deleted file mode 100644 index 8a129eeae..000000000 --- a/windows/moc.lua +++ /dev/null @@ -1,38 +0,0 @@ - -local function quote(x) - return '"' .. x .. '"' -end - -local function toForward(x) - return x:gsub('\\', '/') -end - --- arguments are in this order -local cmd = arg[1] -local outFile = arg[2] -local includes = toForward(arg[3]) -local defines = arg[4] -local inFile = arg[5] - --- build list of includes -local includes2 = "" -for i in string.gmatch(includes, "[^;]+") do - includes2 = includes2.." -I "..quote(i) -end -includes = includes2; - --- build list of defines -local defines2 = "" -for i in string.gmatch(defines, "[^;]+") do - defines2 = defines2.." -D"..i -end -defines = defines2 - --- moc doesn't compile boost correctly, so skip those headers -workarounds=' -DBOOST_MP_CPP_INT_HPP -DBOOST_THREAD_WEK01082003_HPP' - --- build command -cmd = quote(cmd).." -o "..quote(outFile)..includes..defines..workarounds..' '..quote(inFile) -print(cmd) -os.execute(quote(cmd)) - diff --git a/windows/ncurses/include/ncurses/curses.h b/windows/ncurses/include/ncurses/curses.h deleted file mode 100644 index ff375d525..000000000 --- a/windows/ncurses/include/ncurses/curses.h +++ /dev/null @@ -1,1675 +0,0 @@ -/**************************************************************************** - * Copyright (c) 1998-2010,2011 Free Software Foundation, Inc. * - * * - * Permission is hereby granted, free of charge, to any person obtaining a * - * copy of this software and associated documentation files (the * - * "Software"), to deal in the Software without restriction, including * - * without limitation the rights to use, copy, modify, merge, publish, * - * distribute, distribute with modifications, sublicense, and/or sell * - * copies of the Software, and to permit persons to whom the Software is * - * furnished to do so, subject to the following conditions: * - * * - * The above copyright notice and this permission notice shall be included * - * in all copies or substantial portions of the Software. * - * * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * - * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * - * THE USE OR OTHER DEALINGS IN THE SOFTWARE. * - * * - * Except as contained in this notice, the name(s) of the above copyright * - * holders shall not be used in advertising or otherwise to promote the * - * sale, use or other dealings in this Software without prior written * - * authorization. * - ****************************************************************************/ - -/**************************************************************************** - * Author: Zeyd M. Ben-Halim 1992,1995 * - * and: Eric S. Raymond * - * and: Thomas E. Dickey 1996-on * - ****************************************************************************/ - -/* $Id: curses.h.in,v 1.220 2011/01/22 19:47:20 tom Exp $ */ - -#ifndef __NCURSES_H -#define __NCURSES_H - -#define CURSES 1 -#define CURSES_H 1 - -/* These are defined only in curses.h, and are used for conditional compiles */ -#define NCURSES_VERSION_MAJOR 5 -#define NCURSES_VERSION_MINOR 9 -#define NCURSES_VERSION_PATCH 20110404 - -/* This is defined in more than one ncurses header, for identification */ -#undef NCURSES_VERSION -#define NCURSES_VERSION "5.9" - -/* - * Identify the mouse encoding version. - */ -#define NCURSES_MOUSE_VERSION 1 - -/* - * Definitions to facilitate DLL's. - */ -#include - -/* - * User-definable tweak to disable the include of . - */ -#ifndef NCURSES_ENABLE_STDBOOL_H -#define NCURSES_ENABLE_STDBOOL_H 1 -#endif - -/* - * NCURSES_ATTR_T is used to quiet compiler warnings when building ncurses - * configured using --disable-macros. - */ -#ifdef NCURSES_NOMACROS -#ifndef NCURSES_ATTR_T -#define NCURSES_ATTR_T attr_t -#endif -#endif /* NCURSES_NOMACROS */ - -#ifndef NCURSES_ATTR_T -#define NCURSES_ATTR_T int -#endif - -/* - * Expands to 'const' if ncurses is configured using --enable-const. Note that - * doing so makes it incompatible with other implementations of X/Open Curses. - */ -#undef NCURSES_CONST -#define NCURSES_CONST /*nothing*/ - -#undef NCURSES_INLINE -#define NCURSES_INLINE inline - -/* - * The internal type used for color values - */ -#undef NCURSES_COLOR_T -#define NCURSES_COLOR_T short - -/* - * Definition used to make WINDOW and similar structs opaque. - */ -#ifndef NCURSES_OPAQUE -#define NCURSES_OPAQUE 0 -#endif - -/* - * The reentrant code relies on the opaque setting, but adds features. - */ -#ifndef NCURSES_REENTRANT -#define NCURSES_REENTRANT 0 -#endif - -/* - * Control whether bindings for interop support are added. - */ -#undef NCURSES_INTEROP_FUNCS -#define NCURSES_INTEROP_FUNCS 0 - -/* - * The internal type used for window dimensions. - */ -#undef NCURSES_SIZE_T -#define NCURSES_SIZE_T short - -/* - * Control whether tparm() supports varargs or fixed-parameter list. - */ -#undef NCURSES_TPARM_VARARGS -#define NCURSES_TPARM_VARARGS 1 - -/* - * NCURSES_CH_T is used in building the library, but not used otherwise in - * this header file, since that would make the normal/wide-character versions - * of the header incompatible. - */ -#undef NCURSES_CH_T -#define NCURSES_CH_T chtype - -#if 0 && defined(_LP64) -typedef unsigned chtype; -typedef unsigned mmask_t; -#else -typedef unsigned long chtype; -typedef unsigned long mmask_t; -#endif - -/* - * We need FILE, etc. Include this before checking any feature symbols. - */ -#include - -/* - * With XPG4, you must define _XOPEN_SOURCE_EXTENDED, it is redundant (or - * conflicting) when _XOPEN_SOURCE is 500 or greater. - */ -#undef NCURSES_WIDECHAR -#if defined(_XOPEN_SOURCE_EXTENDED) || defined(_XPG5) -#define NCURSES_WIDECHAR -#endif - -#include /* we need va_list */ -#ifdef NCURSES_WIDECHAR -#include /* we want wchar_t */ -#endif - -/* X/Open and SVr4 specify that curses implements 'bool'. However, C++ may also - * implement it. If so, we must use the C++ compiler's type to avoid conflict - * with other interfaces. - * - * A further complication is that may declare 'bool' to be a - * different type, such as an enum which is not necessarily compatible with - * C++. If we have , make 'bool' a macro, so users may #undef it. - * Otherwise, let it remain a typedef to avoid conflicts with other #define's. - * In either case, make a typedef for NCURSES_BOOL which can be used if needed - * from either C or C++. - */ - -#undef TRUE -#define TRUE 1 - -#undef FALSE -#define FALSE 0 - -typedef unsigned char NCURSES_BOOL; - -#if defined(__cplusplus) /* __cplusplus, etc. */ - -/* use the C++ compiler's bool type */ -#define NCURSES_BOOL bool - -#else /* c89, c99, etc. */ - -#if NCURSES_ENABLE_STDBOOL_H -#include -/* use whatever the C compiler decides bool really is */ -#define NCURSES_BOOL bool -#else -/* there is no predefined bool - use our own */ -#undef bool -#define bool NCURSES_BOOL -#endif - -#endif /* !__cplusplus, etc. */ - -#ifdef __cplusplus -extern "C" { -#define NCURSES_CAST(type,value) static_cast(value) -#else -#define NCURSES_CAST(type,value) (type)(value) -#endif - -/* - * X/Open attributes. In the ncurses implementation, they are identical to the - * A_ attributes. - */ -#define WA_ATTRIBUTES A_ATTRIBUTES -#define WA_NORMAL A_NORMAL -#define WA_STANDOUT A_STANDOUT -#define WA_UNDERLINE A_UNDERLINE -#define WA_REVERSE A_REVERSE -#define WA_BLINK A_BLINK -#define WA_DIM A_DIM -#define WA_BOLD A_BOLD -#define WA_ALTCHARSET A_ALTCHARSET -#define WA_INVIS A_INVIS -#define WA_PROTECT A_PROTECT -#define WA_HORIZONTAL A_HORIZONTAL -#define WA_LEFT A_LEFT -#define WA_LOW A_LOW -#define WA_RIGHT A_RIGHT -#define WA_TOP A_TOP -#define WA_VERTICAL A_VERTICAL - -/* colors */ -#define COLOR_BLACK 0 -#define COLOR_RED 1 -#define COLOR_GREEN 2 -#define COLOR_YELLOW 3 -#define COLOR_BLUE 4 -#define COLOR_MAGENTA 5 -#define COLOR_CYAN 6 -#define COLOR_WHITE 7 - -/* line graphics */ - -#if 0 || NCURSES_REENTRANT -NCURSES_WRAPPED_VAR(chtype*, acs_map); -#define acs_map NCURSES_PUBLIC_VAR(acs_map()) -#else -extern NCURSES_EXPORT_VAR(chtype) acs_map[]; -#endif - -#define NCURSES_ACS(c) (acs_map[NCURSES_CAST(unsigned char,c)]) - -/* VT100 symbols begin here */ -#define ACS_ULCORNER NCURSES_ACS('l') /* upper left corner */ -#define ACS_LLCORNER NCURSES_ACS('m') /* lower left corner */ -#define ACS_URCORNER NCURSES_ACS('k') /* upper right corner */ -#define ACS_LRCORNER NCURSES_ACS('j') /* lower right corner */ -#define ACS_LTEE NCURSES_ACS('t') /* tee pointing right */ -#define ACS_RTEE NCURSES_ACS('u') /* tee pointing left */ -#define ACS_BTEE NCURSES_ACS('v') /* tee pointing up */ -#define ACS_TTEE NCURSES_ACS('w') /* tee pointing down */ -#define ACS_HLINE NCURSES_ACS('q') /* horizontal line */ -#define ACS_VLINE NCURSES_ACS('x') /* vertical line */ -#define ACS_PLUS NCURSES_ACS('n') /* large plus or crossover */ -#define ACS_S1 NCURSES_ACS('o') /* scan line 1 */ -#define ACS_S9 NCURSES_ACS('s') /* scan line 9 */ -#define ACS_DIAMOND NCURSES_ACS('`') /* diamond */ -#define ACS_CKBOARD NCURSES_ACS('a') /* checker board (stipple) */ -#define ACS_DEGREE NCURSES_ACS('f') /* degree symbol */ -#define ACS_PLMINUS NCURSES_ACS('g') /* plus/minus */ -#define ACS_BULLET NCURSES_ACS('~') /* bullet */ -/* Teletype 5410v1 symbols begin here */ -#define ACS_LARROW NCURSES_ACS(',') /* arrow pointing left */ -#define ACS_RARROW NCURSES_ACS('+') /* arrow pointing right */ -#define ACS_DARROW NCURSES_ACS('.') /* arrow pointing down */ -#define ACS_UARROW NCURSES_ACS('-') /* arrow pointing up */ -#define ACS_BOARD NCURSES_ACS('h') /* board of squares */ -#define ACS_LANTERN NCURSES_ACS('i') /* lantern symbol */ -#define ACS_BLOCK NCURSES_ACS('0') /* solid square block */ -/* - * These aren't documented, but a lot of System Vs have them anyway - * (you can spot pprryyzz{{||}} in a lot of AT&T terminfo strings). - * The ACS_names may not match AT&T's, our source didn't know them. - */ -#define ACS_S3 NCURSES_ACS('p') /* scan line 3 */ -#define ACS_S7 NCURSES_ACS('r') /* scan line 7 */ -#define ACS_LEQUAL NCURSES_ACS('y') /* less/equal */ -#define ACS_GEQUAL NCURSES_ACS('z') /* greater/equal */ -#define ACS_PI NCURSES_ACS('{') /* Pi */ -#define ACS_NEQUAL NCURSES_ACS('|') /* not equal */ -#define ACS_STERLING NCURSES_ACS('}') /* UK pound sign */ - -/* - * Line drawing ACS names are of the form ACS_trbl, where t is the top, r - * is the right, b is the bottom, and l is the left. t, r, b, and l might - * be B (blank), S (single), D (double), or T (thick). The subset defined - * here only uses B and S. - */ -#define ACS_BSSB ACS_ULCORNER -#define ACS_SSBB ACS_LLCORNER -#define ACS_BBSS ACS_URCORNER -#define ACS_SBBS ACS_LRCORNER -#define ACS_SBSS ACS_RTEE -#define ACS_SSSB ACS_LTEE -#define ACS_SSBS ACS_BTEE -#define ACS_BSSS ACS_TTEE -#define ACS_BSBS ACS_HLINE -#define ACS_SBSB ACS_VLINE -#define ACS_SSSS ACS_PLUS - -#undef ERR -#define ERR (-1) - -#undef OK -#define OK (0) - -/* values for the _flags member */ -#define _SUBWIN 0x01 /* is this a sub-window? */ -#define _ENDLINE 0x02 /* is the window flush right? */ -#define _FULLWIN 0x04 /* is the window full-screen? */ -#define _SCROLLWIN 0x08 /* bottom edge is at screen bottom? */ -#define _ISPAD 0x10 /* is this window a pad? */ -#define _HASMOVED 0x20 /* has cursor moved since last refresh? */ -#define _WRAPPED 0x40 /* cursor was just wrappped */ - -/* - * this value is used in the firstchar and lastchar fields to mark - * unchanged lines - */ -#define _NOCHANGE -1 - -/* - * this value is used in the oldindex field to mark lines created by insertions - * and scrolls. - */ -#define _NEWINDEX -1 - -typedef struct screen SCREEN; -typedef struct _win_st WINDOW; - -typedef chtype attr_t; /* ...must be at least as wide as chtype */ - -#ifdef NCURSES_WIDECHAR - -#if 0 -#ifdef mblen /* libutf8.h defines it w/o undefining first */ -#undef mblen -#endif -#include -#endif - -#if 0 -#include /* ...to get mbstate_t, etc. */ -#endif - -#if 0 -typedef unsigned short wchar_t; -#endif - -#if 0 -typedef unsigned int wint_t; -#endif - -/* - * cchar_t stores an array of CCHARW_MAX wide characters. The first is - * normally a spacing character. The others are non-spacing. If those - * (spacing and nonspacing) do not fill the array, a null L'\0' follows. - * Otherwise, a null is assumed to follow when extracting via getcchar(). - */ -#define CCHARW_MAX 5 -typedef struct -{ - attr_t attr; - wchar_t chars[CCHARW_MAX]; -#if 0 -#undef NCURSES_EXT_COLORS -#define NCURSES_EXT_COLORS 20110404 - int ext_color; /* color pair, must be more than 16-bits */ -#endif -} -cchar_t; - -#endif /* NCURSES_WIDECHAR */ - -#if !NCURSES_OPAQUE -struct ldat; - -struct _win_st -{ - NCURSES_SIZE_T _cury, _curx; /* current cursor position */ - - /* window location and size */ - NCURSES_SIZE_T _maxy, _maxx; /* maximums of x and y, NOT window size */ - NCURSES_SIZE_T _begy, _begx; /* screen coords of upper-left-hand corner */ - - short _flags; /* window state flags */ - - /* attribute tracking */ - attr_t _attrs; /* current attribute for non-space character */ - chtype _bkgd; /* current background char/attribute pair */ - - /* option values set by user */ - bool _notimeout; /* no time out on function-key entry? */ - bool _clear; /* consider all data in the window invalid? */ - bool _leaveok; /* OK to not reset cursor on exit? */ - bool _scroll; /* OK to scroll this window? */ - bool _idlok; /* OK to use insert/delete line? */ - bool _idcok; /* OK to use insert/delete char? */ - bool _immed; /* window in immed mode? (not yet used) */ - bool _sync; /* window in sync mode? */ - bool _use_keypad; /* process function keys into KEY_ symbols? */ - int _delay; /* 0 = nodelay, <0 = blocking, >0 = delay */ - - struct ldat *_line; /* the actual line data */ - - /* global screen state */ - NCURSES_SIZE_T _regtop; /* top line of scrolling region */ - NCURSES_SIZE_T _regbottom; /* bottom line of scrolling region */ - - /* these are used only if this is a sub-window */ - int _parx; /* x coordinate of this window in parent */ - int _pary; /* y coordinate of this window in parent */ - WINDOW *_parent; /* pointer to parent if a sub-window */ - - /* these are used only if this is a pad */ - struct pdat - { - NCURSES_SIZE_T _pad_y, _pad_x; - NCURSES_SIZE_T _pad_top, _pad_left; - NCURSES_SIZE_T _pad_bottom, _pad_right; - } _pad; - - NCURSES_SIZE_T _yoffset; /* real begy is _begy + _yoffset */ - -#ifdef NCURSES_WIDECHAR - cchar_t _bkgrnd; /* current background char/attribute pair */ -#if 0 - int _color; /* current color-pair for non-space character */ -#endif -#endif -}; -#endif /* NCURSES_OPAQUE */ - -/* - * This is an extension to support events... - */ -#if 1 -#ifdef NCURSES_WGETCH_EVENTS -#if !defined(__BEOS__) || defined(__HAIKU__) - /* Fix _nc_timed_wait() on BEOS... */ -# define NCURSES_EVENT_VERSION 1 -#endif /* !defined(__BEOS__) */ - -/* - * Bits to set in _nc_event.data.flags - */ -# define _NC_EVENT_TIMEOUT_MSEC 1 -# define _NC_EVENT_FILE 2 -# define _NC_EVENT_FILE_READABLE 2 -# if 0 /* Not supported yet... */ -# define _NC_EVENT_FILE_WRITABLE 4 -# define _NC_EVENT_FILE_EXCEPTION 8 -# endif - -typedef struct -{ - int type; - union - { - long timeout_msec; /* _NC_EVENT_TIMEOUT_MSEC */ - struct - { - unsigned int flags; - int fd; - unsigned int result; - } fev; /* _NC_EVENT_FILE */ - } data; -} _nc_event; - -typedef struct -{ - int count; - int result_flags; /* _NC_EVENT_TIMEOUT_MSEC or _NC_EVENT_FILE_READABLE */ - _nc_event *events[1]; -} _nc_eventlist; - -extern NCURSES_EXPORT(int) wgetch_events (WINDOW *, _nc_eventlist *); /* experimental */ -extern NCURSES_EXPORT(int) wgetnstr_events (WINDOW *,char *,int,_nc_eventlist *);/* experimental */ - -#endif /* NCURSES_WGETCH_EVENTS */ -#endif /* NCURSES_EXT_FUNCS */ - -/* - * GCC (and some other compilers) define '__attribute__'; we're using this - * macro to alert the compiler to flag inconsistencies in printf/scanf-like - * function calls. Just in case '__attribute__' isn't defined, make a dummy. - * Old versions of G++ do not accept it anyway, at least not consistently with - * GCC. - */ -#if !(defined(__GNUC__) || defined(__GNUG__) || defined(__attribute__)) -#define __attribute__(p) /* nothing */ -#endif - -/* - * We cannot define these in ncurses_cfg.h, since they require parameters to be - * passed (that is non-portable). If you happen to be using gcc with warnings - * enabled, define - * GCC_PRINTF - * GCC_SCANF - * to improve checking of calls to printw(), etc. - */ -#ifndef GCC_PRINTFLIKE -#if defined(GCC_PRINTF) && !defined(printf) -#define GCC_PRINTFLIKE(fmt,var) __attribute__((format(printf,fmt,var))) -#else -#define GCC_PRINTFLIKE(fmt,var) /*nothing*/ -#endif -#endif - -#ifndef GCC_SCANFLIKE -#if defined(GCC_SCANF) && !defined(scanf) -#define GCC_SCANFLIKE(fmt,var) __attribute__((format(scanf,fmt,var))) -#else -#define GCC_SCANFLIKE(fmt,var) /*nothing*/ -#endif -#endif - -#ifndef GCC_NORETURN -#define GCC_NORETURN /* nothing */ -#endif - -#ifndef GCC_UNUSED -#define GCC_UNUSED /* nothing */ -#endif - -/* - * Curses uses a helper function. Define our type for this to simplify - * extending it for the sp-funcs feature. - */ -typedef int (*NCURSES_OUTC)(int); - -/* - * Function prototypes. This is the complete X/Open Curses list of required - * functions. Those marked `generated' will have sources generated from the - * macro definitions later in this file, in order to satisfy XPG4.2 - * requirements. - */ - -extern NCURSES_EXPORT(int) addch (const chtype); /* generated */ -extern NCURSES_EXPORT(int) addchnstr (const chtype *, int); /* generated */ -extern NCURSES_EXPORT(int) addchstr (const chtype *); /* generated */ -extern NCURSES_EXPORT(int) addnstr (const char *, int); /* generated */ -extern NCURSES_EXPORT(int) addstr (const char *); /* generated */ -extern NCURSES_EXPORT(int) attroff (NCURSES_ATTR_T); /* generated */ -extern NCURSES_EXPORT(int) attron (NCURSES_ATTR_T); /* generated */ -extern NCURSES_EXPORT(int) attrset (NCURSES_ATTR_T); /* generated */ -extern NCURSES_EXPORT(int) attr_get (attr_t *, short *, void *); /* generated */ -extern NCURSES_EXPORT(int) attr_off (attr_t, void *); /* generated */ -extern NCURSES_EXPORT(int) attr_on (attr_t, void *); /* generated */ -extern NCURSES_EXPORT(int) attr_set (attr_t, short, void *); /* generated */ -extern NCURSES_EXPORT(int) baudrate (void); /* implemented */ -extern NCURSES_EXPORT(int) beep (void); /* implemented */ -extern NCURSES_EXPORT(int) bkgd (chtype); /* generated */ -extern NCURSES_EXPORT(void) bkgdset (chtype); /* generated */ -extern NCURSES_EXPORT(int) border (chtype,chtype,chtype,chtype,chtype,chtype,chtype,chtype); /* generated */ -extern NCURSES_EXPORT(int) box (WINDOW *, chtype, chtype); /* generated */ -extern NCURSES_EXPORT(bool) can_change_color (void); /* implemented */ -extern NCURSES_EXPORT(int) cbreak (void); /* implemented */ -extern NCURSES_EXPORT(int) chgat (int, attr_t, short, const void *); /* generated */ -extern NCURSES_EXPORT(int) clear (void); /* generated */ -extern NCURSES_EXPORT(int) clearok (WINDOW *,bool); /* implemented */ -extern NCURSES_EXPORT(int) clrtobot (void); /* generated */ -extern NCURSES_EXPORT(int) clrtoeol (void); /* generated */ -extern NCURSES_EXPORT(int) color_content (short,short*,short*,short*); /* implemented */ -extern NCURSES_EXPORT(int) color_set (short,void*); /* generated */ -extern NCURSES_EXPORT(int) COLOR_PAIR (int); /* generated */ -extern NCURSES_EXPORT(int) copywin (const WINDOW*,WINDOW*,int,int,int,int,int,int,int); /* implemented */ -extern NCURSES_EXPORT(int) curs_set (int); /* implemented */ -extern NCURSES_EXPORT(int) def_prog_mode (void); /* implemented */ -extern NCURSES_EXPORT(int) def_shell_mode (void); /* implemented */ -extern NCURSES_EXPORT(int) delay_output (int); /* implemented */ -extern NCURSES_EXPORT(int) delch (void); /* generated */ -extern NCURSES_EXPORT(void) delscreen (SCREEN *); /* implemented */ -extern NCURSES_EXPORT(int) delwin (WINDOW *); /* implemented */ -extern NCURSES_EXPORT(int) deleteln (void); /* generated */ -extern NCURSES_EXPORT(WINDOW *) derwin (WINDOW *,int,int,int,int); /* implemented */ -extern NCURSES_EXPORT(int) doupdate (void); /* implemented */ -extern NCURSES_EXPORT(WINDOW *) dupwin (WINDOW *); /* implemented */ -extern NCURSES_EXPORT(int) echo (void); /* implemented */ -extern NCURSES_EXPORT(int) echochar (const chtype); /* generated */ -extern NCURSES_EXPORT(int) erase (void); /* generated */ -extern NCURSES_EXPORT(int) endwin (void); /* implemented */ -extern NCURSES_EXPORT(char) erasechar (void); /* implemented */ -extern NCURSES_EXPORT(void) filter (void); /* implemented */ -extern NCURSES_EXPORT(int) flash (void); /* implemented */ -extern NCURSES_EXPORT(int) flushinp (void); /* implemented */ -extern NCURSES_EXPORT(chtype) getbkgd (WINDOW *); /* generated */ -extern NCURSES_EXPORT(int) getch (void); /* generated */ -extern NCURSES_EXPORT(int) getnstr (char *, int); /* generated */ -extern NCURSES_EXPORT(int) getstr (char *); /* generated */ -extern NCURSES_EXPORT(WINDOW *) getwin (FILE *); /* implemented */ -extern NCURSES_EXPORT(int) halfdelay (int); /* implemented */ -extern NCURSES_EXPORT(bool) has_colors (void); /* implemented */ -extern NCURSES_EXPORT(bool) has_ic (void); /* implemented */ -extern NCURSES_EXPORT(bool) has_il (void); /* implemented */ -extern NCURSES_EXPORT(int) hline (chtype, int); /* generated */ -extern NCURSES_EXPORT(void) idcok (WINDOW *, bool); /* implemented */ -extern NCURSES_EXPORT(int) idlok (WINDOW *, bool); /* implemented */ -extern NCURSES_EXPORT(void) immedok (WINDOW *, bool); /* implemented */ -extern NCURSES_EXPORT(chtype) inch (void); /* generated */ -extern NCURSES_EXPORT(int) inchnstr (chtype *, int); /* generated */ -extern NCURSES_EXPORT(int) inchstr (chtype *); /* generated */ -extern NCURSES_EXPORT(WINDOW *) initscr (void); /* implemented */ -extern NCURSES_EXPORT(int) init_color (short,short,short,short); /* implemented */ -extern NCURSES_EXPORT(int) init_pair (short,short,short); /* implemented */ -extern NCURSES_EXPORT(int) innstr (char *, int); /* generated */ -extern NCURSES_EXPORT(int) insch (chtype); /* generated */ -extern NCURSES_EXPORT(int) insdelln (int); /* generated */ -extern NCURSES_EXPORT(int) insertln (void); /* generated */ -extern NCURSES_EXPORT(int) insnstr (const char *, int); /* generated */ -extern NCURSES_EXPORT(int) insstr (const char *); /* generated */ -extern NCURSES_EXPORT(int) instr (char *); /* generated */ -extern NCURSES_EXPORT(int) intrflush (WINDOW *,bool); /* implemented */ -extern NCURSES_EXPORT(bool) isendwin (void); /* implemented */ -extern NCURSES_EXPORT(bool) is_linetouched (WINDOW *,int); /* implemented */ -extern NCURSES_EXPORT(bool) is_wintouched (WINDOW *); /* implemented */ -extern NCURSES_EXPORT(NCURSES_CONST char *) keyname (int); /* implemented */ -extern NCURSES_EXPORT(int) keypad (WINDOW *,bool); /* implemented */ -extern NCURSES_EXPORT(char) killchar (void); /* implemented */ -extern NCURSES_EXPORT(int) leaveok (WINDOW *,bool); /* implemented */ -extern NCURSES_EXPORT(char *) longname (void); /* implemented */ -extern NCURSES_EXPORT(int) meta (WINDOW *,bool); /* implemented */ -extern NCURSES_EXPORT(int) move (int, int); /* generated */ -extern NCURSES_EXPORT(int) mvaddch (int, int, const chtype); /* generated */ -extern NCURSES_EXPORT(int) mvaddchnstr (int, int, const chtype *, int); /* generated */ -extern NCURSES_EXPORT(int) mvaddchstr (int, int, const chtype *); /* generated */ -extern NCURSES_EXPORT(int) mvaddnstr (int, int, const char *, int); /* generated */ -extern NCURSES_EXPORT(int) mvaddstr (int, int, const char *); /* generated */ -extern NCURSES_EXPORT(int) mvchgat (int, int, int, attr_t, short, const void *); /* generated */ -extern NCURSES_EXPORT(int) mvcur (int,int,int,int); /* implemented */ -extern NCURSES_EXPORT(int) mvdelch (int, int); /* generated */ -extern NCURSES_EXPORT(int) mvderwin (WINDOW *, int, int); /* implemented */ -extern NCURSES_EXPORT(int) mvgetch (int, int); /* generated */ -extern NCURSES_EXPORT(int) mvgetnstr (int, int, char *, int); /* generated */ -extern NCURSES_EXPORT(int) mvgetstr (int, int, char *); /* generated */ -extern NCURSES_EXPORT(int) mvhline (int, int, chtype, int); /* generated */ -extern NCURSES_EXPORT(chtype) mvinch (int, int); /* generated */ -extern NCURSES_EXPORT(int) mvinchnstr (int, int, chtype *, int); /* generated */ -extern NCURSES_EXPORT(int) mvinchstr (int, int, chtype *); /* generated */ -extern NCURSES_EXPORT(int) mvinnstr (int, int, char *, int); /* generated */ -extern NCURSES_EXPORT(int) mvinsch (int, int, chtype); /* generated */ -extern NCURSES_EXPORT(int) mvinsnstr (int, int, const char *, int); /* generated */ -extern NCURSES_EXPORT(int) mvinsstr (int, int, const char *); /* generated */ -extern NCURSES_EXPORT(int) mvinstr (int, int, char *); /* generated */ -extern NCURSES_EXPORT(int) mvprintw (int,int, const char *,...) /* implemented */ - GCC_PRINTFLIKE(3,4); -extern NCURSES_EXPORT(int) mvscanw (int,int, NCURSES_CONST char *,...) /* implemented */ - GCC_SCANFLIKE(3,4); -extern NCURSES_EXPORT(int) mvvline (int, int, chtype, int); /* generated */ -extern NCURSES_EXPORT(int) mvwaddch (WINDOW *, int, int, const chtype); /* generated */ -extern NCURSES_EXPORT(int) mvwaddchnstr (WINDOW *, int, int, const chtype *, int);/* generated */ -extern NCURSES_EXPORT(int) mvwaddchstr (WINDOW *, int, int, const chtype *); /* generated */ -extern NCURSES_EXPORT(int) mvwaddnstr (WINDOW *, int, int, const char *, int); /* generated */ -extern NCURSES_EXPORT(int) mvwaddstr (WINDOW *, int, int, const char *); /* generated */ -extern NCURSES_EXPORT(int) mvwchgat (WINDOW *, int, int, int, attr_t, short, const void *);/* generated */ -extern NCURSES_EXPORT(int) mvwdelch (WINDOW *, int, int); /* generated */ -extern NCURSES_EXPORT(int) mvwgetch (WINDOW *, int, int); /* generated */ -extern NCURSES_EXPORT(int) mvwgetnstr (WINDOW *, int, int, char *, int); /* generated */ -extern NCURSES_EXPORT(int) mvwgetstr (WINDOW *, int, int, char *); /* generated */ -extern NCURSES_EXPORT(int) mvwhline (WINDOW *, int, int, chtype, int); /* generated */ -extern NCURSES_EXPORT(int) mvwin (WINDOW *,int,int); /* implemented */ -extern NCURSES_EXPORT(chtype) mvwinch (WINDOW *, int, int); /* generated */ -extern NCURSES_EXPORT(int) mvwinchnstr (WINDOW *, int, int, chtype *, int); /* generated */ -extern NCURSES_EXPORT(int) mvwinchstr (WINDOW *, int, int, chtype *); /* generated */ -extern NCURSES_EXPORT(int) mvwinnstr (WINDOW *, int, int, char *, int); /* generated */ -extern NCURSES_EXPORT(int) mvwinsch (WINDOW *, int, int, chtype); /* generated */ -extern NCURSES_EXPORT(int) mvwinsnstr (WINDOW *, int, int, const char *, int); /* generated */ -extern NCURSES_EXPORT(int) mvwinsstr (WINDOW *, int, int, const char *); /* generated */ -extern NCURSES_EXPORT(int) mvwinstr (WINDOW *, int, int, char *); /* generated */ -extern NCURSES_EXPORT(int) mvwprintw (WINDOW*,int,int, const char *,...) /* implemented */ - GCC_PRINTFLIKE(4,5); -extern NCURSES_EXPORT(int) mvwscanw (WINDOW *,int,int, NCURSES_CONST char *,...) /* implemented */ - GCC_SCANFLIKE(4,5); -extern NCURSES_EXPORT(int) mvwvline (WINDOW *,int, int, chtype, int); /* generated */ -extern NCURSES_EXPORT(int) napms (int); /* implemented */ -extern NCURSES_EXPORT(WINDOW *) newpad (int,int); /* implemented */ -extern NCURSES_EXPORT(SCREEN *) newterm (NCURSES_CONST char *,FILE *,FILE *); /* implemented */ -extern NCURSES_EXPORT(WINDOW *) newwin (int,int,int,int); /* implemented */ -extern NCURSES_EXPORT(int) nl (void); /* implemented */ -extern NCURSES_EXPORT(int) nocbreak (void); /* implemented */ -extern NCURSES_EXPORT(int) nodelay (WINDOW *,bool); /* implemented */ -extern NCURSES_EXPORT(int) noecho (void); /* implemented */ -extern NCURSES_EXPORT(int) nonl (void); /* implemented */ -extern NCURSES_EXPORT(void) noqiflush (void); /* implemented */ -extern NCURSES_EXPORT(int) noraw (void); /* implemented */ -extern NCURSES_EXPORT(int) notimeout (WINDOW *,bool); /* implemented */ -extern NCURSES_EXPORT(int) overlay (const WINDOW*,WINDOW *); /* implemented */ -extern NCURSES_EXPORT(int) overwrite (const WINDOW*,WINDOW *); /* implemented */ -extern NCURSES_EXPORT(int) pair_content (short,short*,short*); /* implemented */ -extern NCURSES_EXPORT(int) PAIR_NUMBER (int); /* generated */ -extern NCURSES_EXPORT(int) pechochar (WINDOW *, const chtype); /* implemented */ -extern NCURSES_EXPORT(int) pnoutrefresh (WINDOW*,int,int,int,int,int,int);/* implemented */ -extern NCURSES_EXPORT(int) prefresh (WINDOW *,int,int,int,int,int,int); /* implemented */ -extern NCURSES_EXPORT(int) printw (const char *,...) /* implemented */ - GCC_PRINTFLIKE(1,2); -extern NCURSES_EXPORT(int) putwin (WINDOW *, FILE *); /* implemented */ -extern NCURSES_EXPORT(void) qiflush (void); /* implemented */ -extern NCURSES_EXPORT(int) raw (void); /* implemented */ -extern NCURSES_EXPORT(int) redrawwin (WINDOW *); /* generated */ -extern NCURSES_EXPORT(int) refresh (void); /* generated */ -extern NCURSES_EXPORT(int) resetty (void); /* implemented */ -extern NCURSES_EXPORT(int) reset_prog_mode (void); /* implemented */ -extern NCURSES_EXPORT(int) reset_shell_mode (void); /* implemented */ -extern NCURSES_EXPORT(int) ripoffline (int, int (*)(WINDOW *, int)); /* implemented */ -extern NCURSES_EXPORT(int) savetty (void); /* implemented */ -extern NCURSES_EXPORT(int) scanw (NCURSES_CONST char *,...) /* implemented */ - GCC_SCANFLIKE(1,2); -extern NCURSES_EXPORT(int) scr_dump (const char *); /* implemented */ -extern NCURSES_EXPORT(int) scr_init (const char *); /* implemented */ -extern NCURSES_EXPORT(int) scrl (int); /* generated */ -extern NCURSES_EXPORT(int) scroll (WINDOW *); /* generated */ -extern NCURSES_EXPORT(int) scrollok (WINDOW *,bool); /* implemented */ -extern NCURSES_EXPORT(int) scr_restore (const char *); /* implemented */ -extern NCURSES_EXPORT(int) scr_set (const char *); /* implemented */ -extern NCURSES_EXPORT(int) setscrreg (int,int); /* generated */ -extern NCURSES_EXPORT(SCREEN *) set_term (SCREEN *); /* implemented */ -extern NCURSES_EXPORT(int) slk_attroff (const chtype); /* implemented */ -extern NCURSES_EXPORT(int) slk_attr_off (const attr_t, void *); /* generated:WIDEC */ -extern NCURSES_EXPORT(int) slk_attron (const chtype); /* implemented */ -extern NCURSES_EXPORT(int) slk_attr_on (attr_t,void*); /* generated:WIDEC */ -extern NCURSES_EXPORT(int) slk_attrset (const chtype); /* implemented */ -extern NCURSES_EXPORT(attr_t) slk_attr (void); /* implemented */ -extern NCURSES_EXPORT(int) slk_attr_set (const attr_t,short,void*); /* implemented */ -extern NCURSES_EXPORT(int) slk_clear (void); /* implemented */ -extern NCURSES_EXPORT(int) slk_color (short); /* implemented */ -extern NCURSES_EXPORT(int) slk_init (int); /* implemented */ -extern NCURSES_EXPORT(char *) slk_label (int); /* implemented */ -extern NCURSES_EXPORT(int) slk_noutrefresh (void); /* implemented */ -extern NCURSES_EXPORT(int) slk_refresh (void); /* implemented */ -extern NCURSES_EXPORT(int) slk_restore (void); /* implemented */ -extern NCURSES_EXPORT(int) slk_set (int,const char *,int); /* implemented */ -extern NCURSES_EXPORT(int) slk_touch (void); /* implemented */ -extern NCURSES_EXPORT(int) standout (void); /* generated */ -extern NCURSES_EXPORT(int) standend (void); /* generated */ -extern NCURSES_EXPORT(int) start_color (void); /* implemented */ -extern NCURSES_EXPORT(WINDOW *) subpad (WINDOW *, int, int, int, int); /* implemented */ -extern NCURSES_EXPORT(WINDOW *) subwin (WINDOW *, int, int, int, int); /* implemented */ -extern NCURSES_EXPORT(int) syncok (WINDOW *, bool); /* implemented */ -extern NCURSES_EXPORT(chtype) termattrs (void); /* implemented */ -extern NCURSES_EXPORT(char *) termname (void); /* implemented */ -extern NCURSES_EXPORT(void) timeout (int); /* generated */ -extern NCURSES_EXPORT(int) touchline (WINDOW *, int, int); /* generated */ -extern NCURSES_EXPORT(int) touchwin (WINDOW *); /* generated */ -extern NCURSES_EXPORT(int) typeahead (int); /* implemented */ -extern NCURSES_EXPORT(int) ungetch (int); /* implemented */ -extern NCURSES_EXPORT(int) untouchwin (WINDOW *); /* generated */ -extern NCURSES_EXPORT(void) use_env (bool); /* implemented */ -extern NCURSES_EXPORT(int) vidattr (chtype); /* implemented */ -extern NCURSES_EXPORT(int) vidputs (chtype, NCURSES_OUTC); /* implemented */ -extern NCURSES_EXPORT(int) vline (chtype, int); /* generated */ -extern NCURSES_EXPORT(int) vwprintw (WINDOW *, const char *,va_list); /* implemented */ -extern NCURSES_EXPORT(int) vw_printw (WINDOW *, const char *,va_list); /* generated */ -extern NCURSES_EXPORT(int) vwscanw (WINDOW *, NCURSES_CONST char *,va_list); /* implemented */ -extern NCURSES_EXPORT(int) vw_scanw (WINDOW *, NCURSES_CONST char *,va_list); /* generated */ -extern NCURSES_EXPORT(int) waddch (WINDOW *, const chtype); /* implemented */ -extern NCURSES_EXPORT(int) waddchnstr (WINDOW *,const chtype *,int); /* implemented */ -extern NCURSES_EXPORT(int) waddchstr (WINDOW *,const chtype *); /* generated */ -extern NCURSES_EXPORT(int) waddnstr (WINDOW *,const char *,int); /* implemented */ -extern NCURSES_EXPORT(int) waddstr (WINDOW *,const char *); /* generated */ -extern NCURSES_EXPORT(int) wattron (WINDOW *, int); /* generated */ -extern NCURSES_EXPORT(int) wattroff (WINDOW *, int); /* generated */ -extern NCURSES_EXPORT(int) wattrset (WINDOW *, int); /* generated */ -extern NCURSES_EXPORT(int) wattr_get (WINDOW *, attr_t *, short *, void *); /* generated */ -extern NCURSES_EXPORT(int) wattr_on (WINDOW *, attr_t, void *); /* implemented */ -extern NCURSES_EXPORT(int) wattr_off (WINDOW *, attr_t, void *); /* implemented */ -extern NCURSES_EXPORT(int) wattr_set (WINDOW *, attr_t, short, void *); /* generated */ -extern NCURSES_EXPORT(int) wbkgd (WINDOW *, chtype); /* implemented */ -extern NCURSES_EXPORT(void) wbkgdset (WINDOW *,chtype); /* implemented */ -extern NCURSES_EXPORT(int) wborder (WINDOW *,chtype,chtype,chtype,chtype,chtype,chtype,chtype,chtype); /* implemented */ -extern NCURSES_EXPORT(int) wchgat (WINDOW *, int, attr_t, short, const void *);/* implemented */ -extern NCURSES_EXPORT(int) wclear (WINDOW *); /* implemented */ -extern NCURSES_EXPORT(int) wclrtobot (WINDOW *); /* implemented */ -extern NCURSES_EXPORT(int) wclrtoeol (WINDOW *); /* implemented */ -extern NCURSES_EXPORT(int) wcolor_set (WINDOW*,short,void*); /* implemented */ -extern NCURSES_EXPORT(void) wcursyncup (WINDOW *); /* implemented */ -extern NCURSES_EXPORT(int) wdelch (WINDOW *); /* implemented */ -extern NCURSES_EXPORT(int) wdeleteln (WINDOW *); /* generated */ -extern NCURSES_EXPORT(int) wechochar (WINDOW *, const chtype); /* implemented */ -extern NCURSES_EXPORT(int) werase (WINDOW *); /* implemented */ -extern NCURSES_EXPORT(int) wgetch (WINDOW *); /* implemented */ -extern NCURSES_EXPORT(int) wgetnstr (WINDOW *,char *,int); /* implemented */ -extern NCURSES_EXPORT(int) wgetstr (WINDOW *, char *); /* generated */ -extern NCURSES_EXPORT(int) whline (WINDOW *, chtype, int); /* implemented */ -extern NCURSES_EXPORT(chtype) winch (WINDOW *); /* implemented */ -extern NCURSES_EXPORT(int) winchnstr (WINDOW *, chtype *, int); /* implemented */ -extern NCURSES_EXPORT(int) winchstr (WINDOW *, chtype *); /* generated */ -extern NCURSES_EXPORT(int) winnstr (WINDOW *, char *, int); /* implemented */ -extern NCURSES_EXPORT(int) winsch (WINDOW *, chtype); /* implemented */ -extern NCURSES_EXPORT(int) winsdelln (WINDOW *,int); /* implemented */ -extern NCURSES_EXPORT(int) winsertln (WINDOW *); /* generated */ -extern NCURSES_EXPORT(int) winsnstr (WINDOW *, const char *,int); /* implemented */ -extern NCURSES_EXPORT(int) winsstr (WINDOW *, const char *); /* generated */ -extern NCURSES_EXPORT(int) winstr (WINDOW *, char *); /* generated */ -extern NCURSES_EXPORT(int) wmove (WINDOW *,int,int); /* implemented */ -extern NCURSES_EXPORT(int) wnoutrefresh (WINDOW *); /* implemented */ -extern NCURSES_EXPORT(int) wprintw (WINDOW *, const char *,...) /* implemented */ - GCC_PRINTFLIKE(2,3); -extern NCURSES_EXPORT(int) wredrawln (WINDOW *,int,int); /* implemented */ -extern NCURSES_EXPORT(int) wrefresh (WINDOW *); /* implemented */ -extern NCURSES_EXPORT(int) wscanw (WINDOW *, NCURSES_CONST char *,...) /* implemented */ - GCC_SCANFLIKE(2,3); -extern NCURSES_EXPORT(int) wscrl (WINDOW *,int); /* implemented */ -extern NCURSES_EXPORT(int) wsetscrreg (WINDOW *,int,int); /* implemented */ -extern NCURSES_EXPORT(int) wstandout (WINDOW *); /* generated */ -extern NCURSES_EXPORT(int) wstandend (WINDOW *); /* generated */ -extern NCURSES_EXPORT(void) wsyncdown (WINDOW *); /* implemented */ -extern NCURSES_EXPORT(void) wsyncup (WINDOW *); /* implemented */ -extern NCURSES_EXPORT(void) wtimeout (WINDOW *,int); /* implemented */ -extern NCURSES_EXPORT(int) wtouchln (WINDOW *,int,int,int); /* implemented */ -extern NCURSES_EXPORT(int) wvline (WINDOW *,chtype,int); /* implemented */ - -/* - * These are also declared in : - */ -extern NCURSES_EXPORT(int) tigetflag (NCURSES_CONST char *); /* implemented */ -extern NCURSES_EXPORT(int) tigetnum (NCURSES_CONST char *); /* implemented */ -extern NCURSES_EXPORT(char *) tigetstr (NCURSES_CONST char *); /* implemented */ -extern NCURSES_EXPORT(int) putp (const char *); /* implemented */ - -#if NCURSES_TPARM_VARARGS -extern NCURSES_EXPORT(char *) tparm (NCURSES_CONST char *, ...); /* special */ -#else -extern NCURSES_EXPORT(char *) tparm (NCURSES_CONST char *, long,long,long,long,long,long,long,long,long); /* special */ -extern NCURSES_EXPORT(char *) tparm_varargs (NCURSES_CONST char *, ...); /* special */ -#endif - -extern NCURSES_EXPORT(char *) tiparm (const char *, ...); /* special */ - -/* - * These functions are not in X/Open, but we use them in macro definitions: - */ -extern NCURSES_EXPORT(int) getattrs (const WINDOW *); /* generated */ -extern NCURSES_EXPORT(int) getcurx (const WINDOW *); /* generated */ -extern NCURSES_EXPORT(int) getcury (const WINDOW *); /* generated */ -extern NCURSES_EXPORT(int) getbegx (const WINDOW *); /* generated */ -extern NCURSES_EXPORT(int) getbegy (const WINDOW *); /* generated */ -extern NCURSES_EXPORT(int) getmaxx (const WINDOW *); /* generated */ -extern NCURSES_EXPORT(int) getmaxy (const WINDOW *); /* generated */ -extern NCURSES_EXPORT(int) getparx (const WINDOW *); /* generated */ -extern NCURSES_EXPORT(int) getpary (const WINDOW *); /* generated */ - -/* - * vid_attr() was implemented originally based on a draft of X/Open curses. - */ -#ifndef NCURSES_WIDECHAR -#define vid_attr(a,pair,opts) vidattr(a) -#endif - -/* - * These functions are extensions - not in X/Open Curses. - */ -#if 1 -#undef NCURSES_EXT_FUNCS -#define NCURSES_EXT_FUNCS 20110404 -typedef int (*NCURSES_WINDOW_CB)(WINDOW *, void *); -typedef int (*NCURSES_SCREEN_CB)(SCREEN *, void *); -extern NCURSES_EXPORT(bool) is_term_resized (int, int); -extern NCURSES_EXPORT(char *) keybound (int, int); -extern NCURSES_EXPORT(const char *) curses_version (void); -extern NCURSES_EXPORT(int) assume_default_colors (int, int); -extern NCURSES_EXPORT(int) define_key (const char *, int); -extern NCURSES_EXPORT(int) get_escdelay (void); -extern NCURSES_EXPORT(int) key_defined (const char *); -extern NCURSES_EXPORT(int) keyok (int, bool); -extern NCURSES_EXPORT(int) resize_term (int, int); -extern NCURSES_EXPORT(int) resizeterm (int, int); -extern NCURSES_EXPORT(int) set_escdelay (int); -extern NCURSES_EXPORT(int) set_tabsize (int); -extern NCURSES_EXPORT(int) use_default_colors (void); -extern NCURSES_EXPORT(int) use_extended_names (bool); -extern NCURSES_EXPORT(int) use_legacy_coding (int); -extern NCURSES_EXPORT(int) use_screen (SCREEN *, NCURSES_SCREEN_CB, void *); -extern NCURSES_EXPORT(int) use_window (WINDOW *, NCURSES_WINDOW_CB, void *); -extern NCURSES_EXPORT(int) wresize (WINDOW *, int, int); -extern NCURSES_EXPORT(void) nofilter(void); - -/* - * These extensions provide access to information stored in the WINDOW even - * when NCURSES_OPAQUE is set: - */ -extern NCURSES_EXPORT(WINDOW *) wgetparent (const WINDOW *); /* generated */ -extern NCURSES_EXPORT(bool) is_cleared (const WINDOW *); /* generated */ -extern NCURSES_EXPORT(bool) is_idcok (const WINDOW *); /* generated */ -extern NCURSES_EXPORT(bool) is_idlok (const WINDOW *); /* generated */ -extern NCURSES_EXPORT(bool) is_immedok (const WINDOW *); /* generated */ -extern NCURSES_EXPORT(bool) is_keypad (const WINDOW *); /* generated */ -extern NCURSES_EXPORT(bool) is_leaveok (const WINDOW *); /* generated */ -extern NCURSES_EXPORT(bool) is_nodelay (const WINDOW *); /* generated */ -extern NCURSES_EXPORT(bool) is_notimeout (const WINDOW *); /* generated */ -extern NCURSES_EXPORT(bool) is_pad (const WINDOW *); /* generated */ -extern NCURSES_EXPORT(bool) is_scrollok (const WINDOW *); /* generated */ -extern NCURSES_EXPORT(bool) is_subwin (const WINDOW *); /* generated */ -extern NCURSES_EXPORT(bool) is_syncok (const WINDOW *); /* generated */ -extern NCURSES_EXPORT(int) wgetscrreg (const WINDOW *, int *, int *); /* generated */ - -#else -#define curses_version() NCURSES_VERSION -#endif - -/* - * Extra extension-functions, which pass a SCREEN pointer rather than using - * a global variable SP. - */ -#if 1 -#undef NCURSES_SP_FUNCS -#define NCURSES_SP_FUNCS 20110404 -#define NCURSES_SP_NAME(name) name##_sp - -/* Define the sp-funcs helper function */ -#define NCURSES_SP_OUTC NCURSES_SP_NAME(NCURSES_OUTC) -typedef int (*NCURSES_SP_OUTC)(SCREEN*, int); - -extern NCURSES_EXPORT(SCREEN *) new_prescr (void); /* implemented:SP_FUNC */ - -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(baudrate) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(beep) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(bool) NCURSES_SP_NAME(can_change_color) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(cbreak) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(curs_set) (SCREEN*, int); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(color_content) (SCREEN*, short, short*, short*, short*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(def_prog_mode) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(def_shell_mode) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(delay_output) (SCREEN*, int); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(doupdate) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(echo) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(endwin) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(char) NCURSES_SP_NAME(erasechar) (SCREEN*);/* implemented:SP_FUNC */ -extern NCURSES_EXPORT(void) NCURSES_SP_NAME(filter) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(flash) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(flushinp) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(WINDOW *) NCURSES_SP_NAME(getwin) (SCREEN*, FILE *); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(halfdelay) (SCREEN*, int); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(bool) NCURSES_SP_NAME(has_colors) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(bool) NCURSES_SP_NAME(has_ic) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(bool) NCURSES_SP_NAME(has_il) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(init_color) (SCREEN*, short, short, short, short); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(init_pair) (SCREEN*, short, short, short); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(intrflush) (SCREEN*, WINDOW*, bool); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(bool) NCURSES_SP_NAME(isendwin) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(NCURSES_CONST char *) NCURSES_SP_NAME(keyname) (SCREEN*, int); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(char) NCURSES_SP_NAME(killchar) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(char *) NCURSES_SP_NAME(longname) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(mvcur) (SCREEN*, int, int, int, int); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(napms) (SCREEN*, int); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(WINDOW *) NCURSES_SP_NAME(newpad) (SCREEN*, int, int); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(SCREEN *) NCURSES_SP_NAME(newterm) (SCREEN*, NCURSES_CONST char *, FILE *, FILE *); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(WINDOW *) NCURSES_SP_NAME(newwin) (SCREEN*, int, int, int, int); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(nl) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(nocbreak) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(noecho) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(nonl) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(void) NCURSES_SP_NAME(noqiflush) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(noraw) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(pair_content) (SCREEN*, short, short*, short*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(void) NCURSES_SP_NAME(qiflush) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(raw) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(reset_prog_mode) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(reset_shell_mode) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(resetty) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(ripoffline) (SCREEN*, int, int (*)(WINDOW *, int)); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(savetty) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(scr_init) (SCREEN*, const char *); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(scr_restore) (SCREEN*, const char *); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(scr_set) (SCREEN*, const char *); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(slk_attroff) (SCREEN*, const chtype); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(slk_attron) (SCREEN*, const chtype); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(slk_attrset) (SCREEN*, const chtype); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(attr_t) NCURSES_SP_NAME(slk_attr) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(slk_attr_set) (SCREEN*, const attr_t, short, void*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(slk_clear) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(slk_color) (SCREEN*, short); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(slk_init) (SCREEN*, int); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(char *) NCURSES_SP_NAME(slk_label) (SCREEN*, int); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(slk_noutrefresh) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(slk_refresh) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(slk_restore) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(slk_set) (SCREEN*, int, const char *, int); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(slk_touch) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(start_color) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(chtype) NCURSES_SP_NAME(termattrs) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(char *) NCURSES_SP_NAME(termname) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(typeahead) (SCREEN*, int); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(ungetch) (SCREEN*, int); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(void) NCURSES_SP_NAME(use_env) (SCREEN*, bool); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(vidattr) (SCREEN*, chtype); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(vidputs) (SCREEN*, chtype, NCURSES_SP_OUTC); /* implemented:SP_FUNC */ -#if 1 -extern NCURSES_EXPORT(char *) NCURSES_SP_NAME(keybound) (SCREEN*, int, int); /* implemented:EXT_SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(assume_default_colors) (SCREEN*, int, int); /* implemented:EXT_SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(define_key) (SCREEN*, const char *, int); /* implemented:EXT_SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(get_escdelay) (SCREEN*); /* implemented:EXT_SP_FUNC */ -extern NCURSES_EXPORT(bool) NCURSES_SP_NAME(is_term_resized) (SCREEN*, int, int); /* implemented:EXT_SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(key_defined) (SCREEN*, const char *); /* implemented:EXT_SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(keyok) (SCREEN*, int, bool); /* implemented:EXT_SP_FUNC */ -extern NCURSES_EXPORT(void) NCURSES_SP_NAME(nofilter) (SCREEN*); /* implemented */ /* implemented:EXT_SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(resize_term) (SCREEN*, int, int); /* implemented:EXT_SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(resizeterm) (SCREEN*, int, int); /* implemented:EXT_SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(set_escdelay) (SCREEN*, int); /* implemented:EXT_SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(set_tabsize) (SCREEN*, int); /* implemented:EXT_SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(use_default_colors) (SCREEN*); /* implemented:EXT_SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(use_legacy_coding) (SCREEN*, int); /* implemented:EXT_SP_FUNC */ -#endif -#else -#undef NCURSES_SP_FUNCS -#define NCURSES_SP_FUNCS 0 -#define NCURSES_SP_NAME(name) name -#define NCURSES_SP_OUTC NCURSES_OUTC -#endif - -/* attributes */ - -#define NCURSES_ATTR_SHIFT 8 -#define NCURSES_BITS(mask,shift) ((mask) << ((shift) + NCURSES_ATTR_SHIFT)) - -#define A_NORMAL (1UL - 1UL) -#define A_ATTRIBUTES NCURSES_BITS(~(1UL - 1UL),0) -#define A_CHARTEXT (NCURSES_BITS(1UL,0) - 1UL) -#define A_COLOR NCURSES_BITS(((1UL) << 8) - 1UL,0) -#define A_STANDOUT NCURSES_BITS(1UL,8) -#define A_UNDERLINE NCURSES_BITS(1UL,9) -#define A_REVERSE NCURSES_BITS(1UL,10) -#define A_BLINK NCURSES_BITS(1UL,11) -#define A_DIM NCURSES_BITS(1UL,12) -#define A_BOLD NCURSES_BITS(1UL,13) -#define A_ALTCHARSET NCURSES_BITS(1UL,14) -#define A_INVIS NCURSES_BITS(1UL,15) -#define A_PROTECT NCURSES_BITS(1UL,16) -#define A_HORIZONTAL NCURSES_BITS(1UL,17) -#define A_LEFT NCURSES_BITS(1UL,18) -#define A_LOW NCURSES_BITS(1UL,19) -#define A_RIGHT NCURSES_BITS(1UL,20) -#define A_TOP NCURSES_BITS(1UL,21) -#define A_VERTICAL NCURSES_BITS(1UL,22) - -/* - * Most of the pseudo functions are macros that either provide compatibility - * with older versions of curses, or provide inline functionality to improve - * performance. - */ - -/* - * These pseudo functions are always implemented as macros: - */ - -#define getyx(win,y,x) (y = getcury(win), x = getcurx(win)) -#define getbegyx(win,y,x) (y = getbegy(win), x = getbegx(win)) -#define getmaxyx(win,y,x) (y = getmaxy(win), x = getmaxx(win)) -#define getparyx(win,y,x) (y = getpary(win), x = getparx(win)) - -#define getsyx(y,x) do { if (newscr) { \ - if (is_leaveok(newscr)) \ - (y) = (x) = -1; \ - else \ - getyx(newscr,(y), (x)); \ - } \ - } while(0) - -#define setsyx(y,x) do { if (newscr) { \ - if ((y) == -1 && (x) == -1) \ - leaveok(newscr, TRUE); \ - else { \ - leaveok(newscr, FALSE); \ - wmove(newscr, (y), (x)); \ - } \ - } \ - } while(0) - -#ifndef NCURSES_NOMACROS - -/* - * These miscellaneous pseudo functions are provided for compatibility: - */ - -#define wgetstr(w, s) wgetnstr(w, s, -1) -#define getnstr(s, n) wgetnstr(stdscr, s, n) - -#define setterm(term) setupterm(term, 1, (int *)0) - -#define fixterm() reset_prog_mode() -#define resetterm() reset_shell_mode() -#define saveterm() def_prog_mode() -#define crmode() cbreak() -#define nocrmode() nocbreak() -#define gettmode() - -/* It seems older SYSV curses versions define these */ -#if !NCURSES_OPAQUE -#define getattrs(win) NCURSES_CAST(int, (win) ? (win)->_attrs : A_NORMAL) -#define getcurx(win) ((win) ? (win)->_curx : ERR) -#define getcury(win) ((win) ? (win)->_cury : ERR) -#define getbegx(win) ((win) ? (win)->_begx : ERR) -#define getbegy(win) ((win) ? (win)->_begy : ERR) -#define getmaxx(win) ((win) ? ((win)->_maxx + 1) : ERR) -#define getmaxy(win) ((win) ? ((win)->_maxy + 1) : ERR) -#define getparx(win) ((win) ? (win)->_parx : ERR) -#define getpary(win) ((win) ? (win)->_pary : ERR) -#endif /* NCURSES_OPAQUE */ - -#define wstandout(win) (wattrset(win,A_STANDOUT)) -#define wstandend(win) (wattrset(win,A_NORMAL)) - -#define wattron(win,at) wattr_on(win, NCURSES_CAST(attr_t, at), NULL) -#define wattroff(win,at) wattr_off(win, NCURSES_CAST(attr_t, at), NULL) - -#if !NCURSES_OPAQUE -#if defined(NCURSES_WIDECHAR) && 0 -#define wattrset(win,at) ((win) \ - ? ((win)->_color = PAIR_NUMBER(at), \ - (win)->_attrs = NCURSES_CAST(attr_t, at), \ - OK) \ - : ERR) -#else -#define wattrset(win,at) ((win) \ - ? ((win)->_attrs = NCURSES_CAST(attr_t, at), \ - OK) \ - : ERR) -#endif -#endif /* NCURSES_OPAQUE */ - -#define scroll(win) wscrl(win,1) - -#define touchwin(win) wtouchln((win), 0, getmaxy(win), 1) -#define touchline(win, s, c) wtouchln((win), s, c, 1) -#define untouchwin(win) wtouchln((win), 0, getmaxy(win), 0) - -#define box(win, v, h) wborder(win, v, v, h, h, 0, 0, 0, 0) -#define border(ls, rs, ts, bs, tl, tr, bl, br) wborder(stdscr, ls, rs, ts, bs, tl, tr, bl, br) -#define hline(ch, n) whline(stdscr, ch, n) -#define vline(ch, n) wvline(stdscr, ch, n) - -#define winstr(w, s) winnstr(w, s, -1) -#define winchstr(w, s) winchnstr(w, s, -1) -#define winsstr(w, s) winsnstr(w, s, -1) - -#if !NCURSES_OPAQUE -#define redrawwin(win) wredrawln(win, 0, (win)->_maxy+1) -#endif /* NCURSES_OPAQUE */ - -#define waddstr(win,str) waddnstr(win,str,-1) -#define waddchstr(win,str) waddchnstr(win,str,-1) - -/* - * These apply to the first 256 color pairs. - */ -#define COLOR_PAIR(n) NCURSES_BITS(n, 0) -#define PAIR_NUMBER(a) (NCURSES_CAST(int,((NCURSES_CAST(unsigned long,a) & A_COLOR) >> NCURSES_ATTR_SHIFT))) - -/* - * pseudo functions for standard screen - */ - -#define addch(ch) waddch(stdscr,ch) -#define addchnstr(str,n) waddchnstr(stdscr,str,n) -#define addchstr(str) waddchstr(stdscr,str) -#define addnstr(str,n) waddnstr(stdscr,str,n) -#define addstr(str) waddnstr(stdscr,str,-1) -#define attroff(at) wattroff(stdscr,at) -#define attron(at) wattron(stdscr,at) -#define attrset(at) wattrset(stdscr,at) -#define attr_get(ap,cp,o) wattr_get(stdscr,ap,cp,o) -#define attr_off(a,o) wattr_off(stdscr,a,o) -#define attr_on(a,o) wattr_on(stdscr,a,o) -#define attr_set(a,c,o) wattr_set(stdscr,a,c,o) -#define bkgd(ch) wbkgd(stdscr,ch) -#define bkgdset(ch) wbkgdset(stdscr,ch) -#define chgat(n,a,c,o) wchgat(stdscr,n,a,c,o) -#define clear() wclear(stdscr) -#define clrtobot() wclrtobot(stdscr) -#define clrtoeol() wclrtoeol(stdscr) -#define color_set(c,o) wcolor_set(stdscr,c,o) -#define delch() wdelch(stdscr) -#define deleteln() winsdelln(stdscr,-1) -#define echochar(c) wechochar(stdscr,c) -#define erase() werase(stdscr) -#define getch() wgetch(stdscr) -#define getstr(str) wgetstr(stdscr,str) -#define inch() winch(stdscr) -#define inchnstr(s,n) winchnstr(stdscr,s,n) -#define inchstr(s) winchstr(stdscr,s) -#define innstr(s,n) winnstr(stdscr,s,n) -#define insch(c) winsch(stdscr,c) -#define insdelln(n) winsdelln(stdscr,n) -#define insertln() winsdelln(stdscr,1) -#define insnstr(s,n) winsnstr(stdscr,s,n) -#define insstr(s) winsstr(stdscr,s) -#define instr(s) winstr(stdscr,s) -#define move(y,x) wmove(stdscr,y,x) -#define refresh() wrefresh(stdscr) -#define scrl(n) wscrl(stdscr,n) -#define setscrreg(t,b) wsetscrreg(stdscr,t,b) -#define standend() wstandend(stdscr) -#define standout() wstandout(stdscr) -#define timeout(delay) wtimeout(stdscr,delay) -#define wdeleteln(win) winsdelln(win,-1) -#define winsertln(win) winsdelln(win,1) - -/* - * mv functions - */ - -#define mvwaddch(win,y,x,ch) (wmove(win,y,x) == ERR ? ERR : waddch(win,ch)) -#define mvwaddchnstr(win,y,x,str,n) (wmove(win,y,x) == ERR ? ERR : waddchnstr(win,str,n)) -#define mvwaddchstr(win,y,x,str) (wmove(win,y,x) == ERR ? ERR : waddchnstr(win,str,-1)) -#define mvwaddnstr(win,y,x,str,n) (wmove(win,y,x) == ERR ? ERR : waddnstr(win,str,n)) -#define mvwaddstr(win,y,x,str) (wmove(win,y,x) == ERR ? ERR : waddnstr(win,str,-1)) -#define mvwdelch(win,y,x) (wmove(win,y,x) == ERR ? ERR : wdelch(win)) -#define mvwchgat(win,y,x,n,a,c,o) (wmove(win,y,x) == ERR ? ERR : wchgat(win,n,a,c,o)) -#define mvwgetch(win,y,x) (wmove(win,y,x) == ERR ? ERR : wgetch(win)) -#define mvwgetnstr(win,y,x,str,n) (wmove(win,y,x) == ERR ? ERR : wgetnstr(win,str,n)) -#define mvwgetstr(win,y,x,str) (wmove(win,y,x) == ERR ? ERR : wgetstr(win,str)) -#define mvwhline(win,y,x,c,n) (wmove(win,y,x) == ERR ? ERR : whline(win,c,n)) -#define mvwinch(win,y,x) (wmove(win,y,x) == ERR ? NCURSES_CAST(chtype, ERR) : winch(win)) -#define mvwinchnstr(win,y,x,s,n) (wmove(win,y,x) == ERR ? ERR : winchnstr(win,s,n)) -#define mvwinchstr(win,y,x,s) (wmove(win,y,x) == ERR ? ERR : winchstr(win,s)) -#define mvwinnstr(win,y,x,s,n) (wmove(win,y,x) == ERR ? ERR : winnstr(win,s,n)) -#define mvwinsch(win,y,x,c) (wmove(win,y,x) == ERR ? ERR : winsch(win,c)) -#define mvwinsnstr(win,y,x,s,n) (wmove(win,y,x) == ERR ? ERR : winsnstr(win,s,n)) -#define mvwinsstr(win,y,x,s) (wmove(win,y,x) == ERR ? ERR : winsstr(win,s)) -#define mvwinstr(win,y,x,s) (wmove(win,y,x) == ERR ? ERR : winstr(win,s)) -#define mvwvline(win,y,x,c,n) (wmove(win,y,x) == ERR ? ERR : wvline(win,c,n)) - -#define mvaddch(y,x,ch) mvwaddch(stdscr,y,x,ch) -#define mvaddchnstr(y,x,str,n) mvwaddchnstr(stdscr,y,x,str,n) -#define mvaddchstr(y,x,str) mvwaddchstr(stdscr,y,x,str) -#define mvaddnstr(y,x,str,n) mvwaddnstr(stdscr,y,x,str,n) -#define mvaddstr(y,x,str) mvwaddstr(stdscr,y,x,str) -#define mvchgat(y,x,n,a,c,o) mvwchgat(stdscr,y,x,n,a,c,o) -#define mvdelch(y,x) mvwdelch(stdscr,y,x) -#define mvgetch(y,x) mvwgetch(stdscr,y,x) -#define mvgetnstr(y,x,str,n) mvwgetnstr(stdscr,y,x,str,n) -#define mvgetstr(y,x,str) mvwgetstr(stdscr,y,x,str) -#define mvhline(y,x,c,n) mvwhline(stdscr,y,x,c,n) -#define mvinch(y,x) mvwinch(stdscr,y,x) -#define mvinchnstr(y,x,s,n) mvwinchnstr(stdscr,y,x,s,n) -#define mvinchstr(y,x,s) mvwinchstr(stdscr,y,x,s) -#define mvinnstr(y,x,s,n) mvwinnstr(stdscr,y,x,s,n) -#define mvinsch(y,x,c) mvwinsch(stdscr,y,x,c) -#define mvinsnstr(y,x,s,n) mvwinsnstr(stdscr,y,x,s,n) -#define mvinsstr(y,x,s) mvwinsstr(stdscr,y,x,s) -#define mvinstr(y,x,s) mvwinstr(stdscr,y,x,s) -#define mvvline(y,x,c,n) mvwvline(stdscr,y,x,c,n) - -/* - * Some wide-character functions can be implemented without the extensions. - */ -#if !NCURSES_OPAQUE -#define getbkgd(win) ((win)->_bkgd) -#endif /* NCURSES_OPAQUE */ - -#define slk_attr_off(a,v) ((v) ? ERR : slk_attroff(a)) -#define slk_attr_on(a,v) ((v) ? ERR : slk_attron(a)) - -#if !NCURSES_OPAQUE -#if defined(NCURSES_WIDECHAR) && 0 -#define wattr_set(win,a,p,opts) ((win)->_attrs = ((a) & ~A_COLOR), \ - (win)->_color = (p), \ - OK) -#define wattr_get(win,a,p,opts) ((void)((a) != (void *)0 && (*(a) = (win)->_attrs)), \ - (void)((p) != (void *)0 && (*(p) = (short)(win)->_color)), \ - OK) -#else -#define wattr_set(win,a,p,opts) ((win)->_attrs = (((a) & ~A_COLOR) | (attr_t)COLOR_PAIR(p)), OK) -#define wattr_get(win,a,p,opts) ((void)((a) != (void *)0 && (*(a) = (win)->_attrs)), \ - (void)((p) != (void *)0 && (*(p) = (short)PAIR_NUMBER((win)->_attrs))), \ - OK) -#endif -#endif /* NCURSES_OPAQUE */ - -/* - * X/Open curses deprecates SVr4 vwprintw/vwscanw, which are supposed to use - * varargs.h. It adds new calls vw_printw/vw_scanw, which are supposed to - * use POSIX stdarg.h. The ncurses versions of vwprintw/vwscanw already - * use stdarg.h, so... - */ -#define vw_printw vwprintw -#define vw_scanw vwscanw - -/* - * Export fallback function for use in C++ binding. - */ -#if !1 -#define vsscanf(a,b,c) _nc_vsscanf(a,b,c) -NCURSES_EXPORT(int) vsscanf(const char *, const char *, va_list); -#endif - -/* - * These macros are extensions - not in X/Open Curses. - */ -#if 1 -#if !NCURSES_OPAQUE -#define is_cleared(win) ((win) ? (win)->_clear : FALSE) -#define is_idcok(win) ((win) ? (win)->_idcok : FALSE) -#define is_idlok(win) ((win) ? (win)->_idlok : FALSE) -#define is_immedok(win) ((win) ? (win)->_immed : FALSE) -#define is_keypad(win) ((win) ? (win)->_use_keypad : FALSE) -#define is_leaveok(win) ((win) ? (win)->_leaveok : FALSE) -#define is_nodelay(win) ((win) ? ((win)->_delay == 0) : FALSE) -#define is_notimeout(win) ((win) ? (win)->_notimeout : FALSE) -#define is_pad(win) ((win) ? ((win)->_flags & _ISPAD) != 0 : FALSE) -#define is_scrollok(win) ((win) ? (win)->_scroll : FALSE) -#define is_subwin(win) ((win) ? ((win)->_flags & _SUBWIN) != 0 : FALSE) -#define is_syncok(win) ((win) ? (win)->_sync : FALSE) -#define wgetparent(win) ((win) ? (win)->_parent : 0) -#define wgetscrreg(win,t,b) ((win) ? (*(t) = (win)->_regtop, *(b) = (win)->_regbottom, OK) : ERR) -#endif -#endif - -#endif /* NCURSES_NOMACROS */ - -/* - * Public variables. - * - * Notes: - * a. ESCDELAY was an undocumented feature under AIX curses. - * It gives the ESC expire time in milliseconds. - * b. ttytype is needed for backward compatibility - */ -#if NCURSES_REENTRANT - -NCURSES_WRAPPED_VAR(WINDOW *, curscr); -NCURSES_WRAPPED_VAR(WINDOW *, newscr); -NCURSES_WRAPPED_VAR(WINDOW *, stdscr); -NCURSES_WRAPPED_VAR(char *, ttytype); -NCURSES_WRAPPED_VAR(int, COLORS); -NCURSES_WRAPPED_VAR(int, COLOR_PAIRS); -NCURSES_WRAPPED_VAR(int, COLS); -NCURSES_WRAPPED_VAR(int, ESCDELAY); -NCURSES_WRAPPED_VAR(int, LINES); -NCURSES_WRAPPED_VAR(int, TABSIZE); - -#define curscr NCURSES_PUBLIC_VAR(curscr()) -#define newscr NCURSES_PUBLIC_VAR(newscr()) -#define stdscr NCURSES_PUBLIC_VAR(stdscr()) -#define ttytype NCURSES_PUBLIC_VAR(ttytype()) -#define COLORS NCURSES_PUBLIC_VAR(COLORS()) -#define COLOR_PAIRS NCURSES_PUBLIC_VAR(COLOR_PAIRS()) -#define COLS NCURSES_PUBLIC_VAR(COLS()) -#define ESCDELAY NCURSES_PUBLIC_VAR(ESCDELAY()) -#define LINES NCURSES_PUBLIC_VAR(LINES()) -#define TABSIZE NCURSES_PUBLIC_VAR(TABSIZE()) - -#else - -extern NCURSES_EXPORT_VAR(WINDOW *) curscr; -extern NCURSES_EXPORT_VAR(WINDOW *) newscr; -extern NCURSES_EXPORT_VAR(WINDOW *) stdscr; -extern NCURSES_EXPORT_VAR(char) ttytype[]; -extern NCURSES_EXPORT_VAR(int) COLORS; -extern NCURSES_EXPORT_VAR(int) COLOR_PAIRS; -extern NCURSES_EXPORT_VAR(int) COLS; -extern NCURSES_EXPORT_VAR(int) ESCDELAY; -extern NCURSES_EXPORT_VAR(int) LINES; -extern NCURSES_EXPORT_VAR(int) TABSIZE; - -#endif - -/* - * Pseudo-character tokens outside ASCII range. The curses wgetch() function - * will return any given one of these only if the corresponding k- capability - * is defined in your terminal's terminfo entry. - * - * Some keys (KEY_A1, etc) are arranged like this: - * a1 up a3 - * left b2 right - * c1 down c3 - * - * A few key codes do not depend upon the terminfo entry. - */ -#define KEY_CODE_YES 0400 /* A wchar_t contains a key code */ -#define KEY_MIN 0401 /* Minimum curses key */ -#define KEY_BREAK 0401 /* Break key (unreliable) */ -#define KEY_SRESET 0530 /* Soft (partial) reset (unreliable) */ -#define KEY_RESET 0531 /* Reset or hard reset (unreliable) */ -/* - * These definitions were generated by ./MKkey_defs.sh ./Caps - */ -#define KEY_DOWN 0402 /* down-arrow key */ -#define KEY_UP 0403 /* up-arrow key */ -#define KEY_LEFT 0404 /* left-arrow key */ -#define KEY_RIGHT 0405 /* right-arrow key */ -#define KEY_HOME 0406 /* home key */ -#define KEY_BACKSPACE 0407 /* backspace key */ -#define KEY_F0 0410 /* Function keys. Space for 64 */ -#define KEY_F(n) (KEY_F0+(n)) /* Value of function key n */ -#define KEY_DL 0510 /* delete-line key */ -#define KEY_IL 0511 /* insert-line key */ -#define KEY_DC 0512 /* delete-character key */ -#define KEY_IC 0513 /* insert-character key */ -#define KEY_EIC 0514 /* sent by rmir or smir in insert mode */ -#define KEY_CLEAR 0515 /* clear-screen or erase key */ -#define KEY_EOS 0516 /* clear-to-end-of-screen key */ -#define KEY_EOL 0517 /* clear-to-end-of-line key */ -#define KEY_SF 0520 /* scroll-forward key */ -#define KEY_SR 0521 /* scroll-backward key */ -#define KEY_NPAGE 0522 /* next-page key */ -#define KEY_PPAGE 0523 /* previous-page key */ -#define KEY_STAB 0524 /* set-tab key */ -#define KEY_CTAB 0525 /* clear-tab key */ -#define KEY_CATAB 0526 /* clear-all-tabs key */ -#define KEY_ENTER 0527 /* enter/send key */ -#define KEY_PRINT 0532 /* print key */ -#define KEY_LL 0533 /* lower-left key (home down) */ -#define KEY_A1 0534 /* upper left of keypad */ -#define KEY_A3 0535 /* upper right of keypad */ -#define KEY_B2 0536 /* center of keypad */ -#define KEY_C1 0537 /* lower left of keypad */ -#define KEY_C3 0540 /* lower right of keypad */ -#define KEY_BTAB 0541 /* back-tab key */ -#define KEY_BEG 0542 /* begin key */ -#define KEY_CANCEL 0543 /* cancel key */ -#define KEY_CLOSE 0544 /* close key */ -#define KEY_COMMAND 0545 /* command key */ -#define KEY_COPY 0546 /* copy key */ -#define KEY_CREATE 0547 /* create key */ -#define KEY_END 0550 /* end key */ -#define KEY_EXIT 0551 /* exit key */ -#define KEY_FIND 0552 /* find key */ -#define KEY_HELP 0553 /* help key */ -#define KEY_MARK 0554 /* mark key */ -#define KEY_MESSAGE 0555 /* message key */ -#define KEY_MOVE 0556 /* move key */ -#define KEY_NEXT 0557 /* next key */ -#define KEY_OPEN 0560 /* open key */ -#define KEY_OPTIONS 0561 /* options key */ -#define KEY_PREVIOUS 0562 /* previous key */ -#define KEY_REDO 0563 /* redo key */ -#define KEY_REFERENCE 0564 /* reference key */ -#define KEY_REFRESH 0565 /* refresh key */ -#define KEY_REPLACE 0566 /* replace key */ -#define KEY_RESTART 0567 /* restart key */ -#define KEY_RESUME 0570 /* resume key */ -#define KEY_SAVE 0571 /* save key */ -#define KEY_SBEG 0572 /* shifted begin key */ -#define KEY_SCANCEL 0573 /* shifted cancel key */ -#define KEY_SCOMMAND 0574 /* shifted command key */ -#define KEY_SCOPY 0575 /* shifted copy key */ -#define KEY_SCREATE 0576 /* shifted create key */ -#define KEY_SDC 0577 /* shifted delete-character key */ -#define KEY_SDL 0600 /* shifted delete-line key */ -#define KEY_SELECT 0601 /* select key */ -#define KEY_SEND 0602 /* shifted end key */ -#define KEY_SEOL 0603 /* shifted clear-to-end-of-line key */ -#define KEY_SEXIT 0604 /* shifted exit key */ -#define KEY_SFIND 0605 /* shifted find key */ -#define KEY_SHELP 0606 /* shifted help key */ -#define KEY_SHOME 0607 /* shifted home key */ -#define KEY_SIC 0610 /* shifted insert-character key */ -#define KEY_SLEFT 0611 /* shifted left-arrow key */ -#define KEY_SMESSAGE 0612 /* shifted message key */ -#define KEY_SMOVE 0613 /* shifted move key */ -#define KEY_SNEXT 0614 /* shifted next key */ -#define KEY_SOPTIONS 0615 /* shifted options key */ -#define KEY_SPREVIOUS 0616 /* shifted previous key */ -#define KEY_SPRINT 0617 /* shifted print key */ -#define KEY_SREDO 0620 /* shifted redo key */ -#define KEY_SREPLACE 0621 /* shifted replace key */ -#define KEY_SRIGHT 0622 /* shifted right-arrow key */ -#define KEY_SRSUME 0623 /* shifted resume key */ -#define KEY_SSAVE 0624 /* shifted save key */ -#define KEY_SSUSPEND 0625 /* shifted suspend key */ -#define KEY_SUNDO 0626 /* shifted undo key */ -#define KEY_SUSPEND 0627 /* suspend key */ -#define KEY_UNDO 0630 /* undo key */ -#define KEY_MOUSE 0631 /* Mouse event has occurred */ -#define KEY_RESIZE 0632 /* Terminal resize event */ -#define KEY_EVENT 0633 /* We were interrupted by an event */ - -#define KEY_MAX 0777 /* Maximum key value is 0633 */ -/* $Id: curses.tail,v 1.20 2010/03/28 19:10:55 tom Exp $ */ -/* - * vile:cmode: - * This file is part of ncurses, designed to be appended after curses.h.in - * (see that file for the relevant copyright). - */ - -/* mouse interface */ - -#if NCURSES_MOUSE_VERSION > 1 -#define NCURSES_MOUSE_MASK(b,m) ((m) << (((b) - 1) * 5)) -#else -#define NCURSES_MOUSE_MASK(b,m) ((m) << (((b) - 1) * 6)) -#endif - -#define NCURSES_BUTTON_RELEASED 001L -#define NCURSES_BUTTON_PRESSED 002L -#define NCURSES_BUTTON_CLICKED 004L -#define NCURSES_DOUBLE_CLICKED 010L -#define NCURSES_TRIPLE_CLICKED 020L -#define NCURSES_RESERVED_EVENT 040L - -/* event masks */ -#define BUTTON1_RELEASED NCURSES_MOUSE_MASK(1, NCURSES_BUTTON_RELEASED) -#define BUTTON1_PRESSED NCURSES_MOUSE_MASK(1, NCURSES_BUTTON_PRESSED) -#define BUTTON1_CLICKED NCURSES_MOUSE_MASK(1, NCURSES_BUTTON_CLICKED) -#define BUTTON1_DOUBLE_CLICKED NCURSES_MOUSE_MASK(1, NCURSES_DOUBLE_CLICKED) -#define BUTTON1_TRIPLE_CLICKED NCURSES_MOUSE_MASK(1, NCURSES_TRIPLE_CLICKED) - -#define BUTTON2_RELEASED NCURSES_MOUSE_MASK(2, NCURSES_BUTTON_RELEASED) -#define BUTTON2_PRESSED NCURSES_MOUSE_MASK(2, NCURSES_BUTTON_PRESSED) -#define BUTTON2_CLICKED NCURSES_MOUSE_MASK(2, NCURSES_BUTTON_CLICKED) -#define BUTTON2_DOUBLE_CLICKED NCURSES_MOUSE_MASK(2, NCURSES_DOUBLE_CLICKED) -#define BUTTON2_TRIPLE_CLICKED NCURSES_MOUSE_MASK(2, NCURSES_TRIPLE_CLICKED) - -#define BUTTON3_RELEASED NCURSES_MOUSE_MASK(3, NCURSES_BUTTON_RELEASED) -#define BUTTON3_PRESSED NCURSES_MOUSE_MASK(3, NCURSES_BUTTON_PRESSED) -#define BUTTON3_CLICKED NCURSES_MOUSE_MASK(3, NCURSES_BUTTON_CLICKED) -#define BUTTON3_DOUBLE_CLICKED NCURSES_MOUSE_MASK(3, NCURSES_DOUBLE_CLICKED) -#define BUTTON3_TRIPLE_CLICKED NCURSES_MOUSE_MASK(3, NCURSES_TRIPLE_CLICKED) - -#define BUTTON4_RELEASED NCURSES_MOUSE_MASK(4, NCURSES_BUTTON_RELEASED) -#define BUTTON4_PRESSED NCURSES_MOUSE_MASK(4, NCURSES_BUTTON_PRESSED) -#define BUTTON4_CLICKED NCURSES_MOUSE_MASK(4, NCURSES_BUTTON_CLICKED) -#define BUTTON4_DOUBLE_CLICKED NCURSES_MOUSE_MASK(4, NCURSES_DOUBLE_CLICKED) -#define BUTTON4_TRIPLE_CLICKED NCURSES_MOUSE_MASK(4, NCURSES_TRIPLE_CLICKED) - -/* - * In 32 bits the version-1 scheme does not provide enough space for a 5th - * button, unless we choose to change the ABI by omitting the reserved-events. - */ -#if NCURSES_MOUSE_VERSION > 1 - -#define BUTTON5_RELEASED NCURSES_MOUSE_MASK(5, NCURSES_BUTTON_RELEASED) -#define BUTTON5_PRESSED NCURSES_MOUSE_MASK(5, NCURSES_BUTTON_PRESSED) -#define BUTTON5_CLICKED NCURSES_MOUSE_MASK(5, NCURSES_BUTTON_CLICKED) -#define BUTTON5_DOUBLE_CLICKED NCURSES_MOUSE_MASK(5, NCURSES_DOUBLE_CLICKED) -#define BUTTON5_TRIPLE_CLICKED NCURSES_MOUSE_MASK(5, NCURSES_TRIPLE_CLICKED) - -#define BUTTON_CTRL NCURSES_MOUSE_MASK(6, 0001L) -#define BUTTON_SHIFT NCURSES_MOUSE_MASK(6, 0002L) -#define BUTTON_ALT NCURSES_MOUSE_MASK(6, 0004L) -#define REPORT_MOUSE_POSITION NCURSES_MOUSE_MASK(6, 0010L) - -#else - -#define BUTTON1_RESERVED_EVENT NCURSES_MOUSE_MASK(1, NCURSES_RESERVED_EVENT) -#define BUTTON2_RESERVED_EVENT NCURSES_MOUSE_MASK(2, NCURSES_RESERVED_EVENT) -#define BUTTON3_RESERVED_EVENT NCURSES_MOUSE_MASK(3, NCURSES_RESERVED_EVENT) -#define BUTTON4_RESERVED_EVENT NCURSES_MOUSE_MASK(4, NCURSES_RESERVED_EVENT) - -#define BUTTON_CTRL NCURSES_MOUSE_MASK(5, 0001L) -#define BUTTON_SHIFT NCURSES_MOUSE_MASK(5, 0002L) -#define BUTTON_ALT NCURSES_MOUSE_MASK(5, 0004L) -#define REPORT_MOUSE_POSITION NCURSES_MOUSE_MASK(5, 0010L) - -#endif - -#define ALL_MOUSE_EVENTS (REPORT_MOUSE_POSITION - 1) - -/* macros to extract single event-bits from masks */ -#define BUTTON_RELEASE(e, x) ((e) & NCURSES_MOUSE_MASK(x, 001)) -#define BUTTON_PRESS(e, x) ((e) & NCURSES_MOUSE_MASK(x, 002)) -#define BUTTON_CLICK(e, x) ((e) & NCURSES_MOUSE_MASK(x, 004)) -#define BUTTON_DOUBLE_CLICK(e, x) ((e) & NCURSES_MOUSE_MASK(x, 010)) -#define BUTTON_TRIPLE_CLICK(e, x) ((e) & NCURSES_MOUSE_MASK(x, 020)) -#define BUTTON_RESERVED_EVENT(e, x) ((e) & NCURSES_MOUSE_MASK(x, 040)) - -typedef struct -{ - short id; /* ID to distinguish multiple devices */ - int x, y, z; /* event coordinates (character-cell) */ - mmask_t bstate; /* button state bits */ -} -MEVENT; - -extern NCURSES_EXPORT(bool) has_mouse(void); -extern NCURSES_EXPORT(int) getmouse (MEVENT *); -extern NCURSES_EXPORT(int) ungetmouse (MEVENT *); -extern NCURSES_EXPORT(mmask_t) mousemask (mmask_t, mmask_t *); -extern NCURSES_EXPORT(bool) wenclose (const WINDOW *, int, int); -extern NCURSES_EXPORT(int) mouseinterval (int); -extern NCURSES_EXPORT(bool) wmouse_trafo (const WINDOW*, int*, int*, bool); -extern NCURSES_EXPORT(bool) mouse_trafo (int*, int*, bool); /* generated */ - -#if NCURSES_SP_FUNCS -extern NCURSES_EXPORT(bool) NCURSES_SP_NAME(has_mouse) (SCREEN*); -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(getmouse) (SCREEN*, MEVENT *); -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(ungetmouse) (SCREEN*,MEVENT *); -extern NCURSES_EXPORT(mmask_t) NCURSES_SP_NAME(mousemask) (SCREEN*, mmask_t, mmask_t *); -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(mouseinterval) (SCREEN*, int); -#endif - -#define mouse_trafo(y,x,to_screen) wmouse_trafo(stdscr,y,x,to_screen) - -/* other non-XSI functions */ - -extern NCURSES_EXPORT(int) mcprint (char *, int); /* direct data to printer */ -extern NCURSES_EXPORT(int) has_key (int); /* do we have given key? */ - -#if NCURSES_SP_FUNCS -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(has_key) (SCREEN*, int); /* do we have given key? */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(mcprint) (SCREEN*, char *, int); /* direct data to printer */ -#endif - -/* Debugging : use with libncurses_g.a */ - -extern NCURSES_EXPORT(void) _tracef (const char *, ...) GCC_PRINTFLIKE(1,2); -extern NCURSES_EXPORT(void) _tracedump (const char *, WINDOW *); -extern NCURSES_EXPORT(char *) _traceattr (attr_t); -extern NCURSES_EXPORT(char *) _traceattr2 (int, chtype); -extern NCURSES_EXPORT(char *) _nc_tracebits (void); -extern NCURSES_EXPORT(char *) _tracechar (int); -extern NCURSES_EXPORT(char *) _tracechtype (chtype); -extern NCURSES_EXPORT(char *) _tracechtype2 (int, chtype); -#ifdef NCURSES_WIDECHAR -#define _tracech_t _tracecchar_t -extern NCURSES_EXPORT(char *) _tracecchar_t (const cchar_t *); -#define _tracech_t2 _tracecchar_t2 -extern NCURSES_EXPORT(char *) _tracecchar_t2 (int, const cchar_t *); -#else -#define _tracech_t _tracechtype -#define _tracech_t2 _tracechtype2 -#endif -extern NCURSES_EXPORT(char *) _tracemouse (const MEVENT *); -extern NCURSES_EXPORT(void) trace (const unsigned int); - -/* trace masks */ -#define TRACE_DISABLE 0x0000 /* turn off tracing */ -#define TRACE_TIMES 0x0001 /* trace user and system times of updates */ -#define TRACE_TPUTS 0x0002 /* trace tputs calls */ -#define TRACE_UPDATE 0x0004 /* trace update actions, old & new screens */ -#define TRACE_MOVE 0x0008 /* trace cursor moves and scrolls */ -#define TRACE_CHARPUT 0x0010 /* trace all character outputs */ -#define TRACE_ORDINARY 0x001F /* trace all update actions */ -#define TRACE_CALLS 0x0020 /* trace all curses calls */ -#define TRACE_VIRTPUT 0x0040 /* trace virtual character puts */ -#define TRACE_IEVENT 0x0080 /* trace low-level input processing */ -#define TRACE_BITS 0x0100 /* trace state of TTY control bits */ -#define TRACE_ICALLS 0x0200 /* trace internal/nested calls */ -#define TRACE_CCALLS 0x0400 /* trace per-character calls */ -#define TRACE_DATABASE 0x0800 /* trace read/write of terminfo/termcap data */ -#define TRACE_ATTRS 0x1000 /* trace attribute updates */ - -#define TRACE_SHIFT 13 /* number of bits in the trace masks */ -#define TRACE_MAXIMUM ((1 << TRACE_SHIFT) - 1) /* maximum trace level */ - -#if defined(TRACE) || defined(NCURSES_TEST) -extern NCURSES_EXPORT_VAR(int) _nc_optimize_enable; /* enable optimizations */ -extern NCURSES_EXPORT(const char *) _nc_visbuf (const char *); -#define OPTIMIZE_MVCUR 0x01 /* cursor movement optimization */ -#define OPTIMIZE_HASHMAP 0x02 /* diff hashing to detect scrolls */ -#define OPTIMIZE_SCROLL 0x04 /* scroll optimization */ -#define OPTIMIZE_ALL 0xff /* enable all optimizations (dflt) */ -#endif - -#include - -#ifdef __cplusplus - -#ifndef NCURSES_NOMACROS - -/* these names conflict with STL */ -#undef box -#undef clear -#undef erase -#undef move -#undef refresh - -#endif /* NCURSES_NOMACROS */ - -} -#endif - -#endif /* __NCURSES_H */ diff --git a/windows/ncurses/include/ncurses/cursesapp.h b/windows/ncurses/include/ncurses/cursesapp.h deleted file mode 100644 index f619c1f04..000000000 --- a/windows/ncurses/include/ncurses/cursesapp.h +++ /dev/null @@ -1,176 +0,0 @@ -// * This makes emacs happy -*-Mode: C++;-*- -/**************************************************************************** - * Copyright (c) 1998-2003,2005 Free Software Foundation, Inc. * - * * - * Permission is hereby granted, free of charge, to any person obtaining a * - * copy of this software and associated documentation files (the * - * "Software"), to deal in the Software without restriction, including * - * without limitation the rights to use, copy, modify, merge, publish, * - * distribute, distribute with modifications, sublicense, and/or sell * - * copies of the Software, and to permit persons to whom the Software is * - * furnished to do so, subject to the following conditions: * - * * - * The above copyright notice and this permission notice shall be included * - * in all copies or substantial portions of the Software. * - * * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * - * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * - * THE USE OR OTHER DEALINGS IN THE SOFTWARE. * - * * - * Except as contained in this notice, the name(s) of the above copyright * - * holders shall not be used in advertising or otherwise to promote the * - * sale, use or other dealings in this Software without prior written * - * authorization. * - ****************************************************************************/ - -/**************************************************************************** - * Author: Juergen Pfeifer, 1997 * - ****************************************************************************/ - -// $Id: cursesapp.h,v 1.11 2005/05/28 21:57:44 tom Exp $ - -#ifndef NCURSES_CURSESAPP_H_incl -#define NCURSES_CURSESAPP_H_incl - -#include - -class NCURSES_IMPEXP NCursesApplication { -public: - typedef struct _slk_link { // This structure is used to maintain - struct _slk_link* prev; // a stack of SLKs - Soft_Label_Key_Set* SLKs; - } SLK_Link; -private: - static int rinit(NCursesWindow& w); // Internal Init function for title - static NCursesApplication* theApp; // Global ref. to the application - - static SLK_Link* slk_stack; - -protected: - static NCursesWindow* titleWindow; // The Title Window (if any) - - bool b_Colors; // Is this a color application? - NCursesWindow* Root_Window; // This is the stdscr equiv. - - // Initialization of attributes; - // Rewrite this in your derived class if you prefer other settings - virtual void init(bool bColors); - - // The number of lines for the title window. Default is no title window - // You may rewrite this in your derived class - virtual int titlesize() const { - return 0; - } - - // This method is called to put something into the title window initially - // You may rewrite this in your derived class - virtual void title() { - } - - // The layout used for the Soft Label Keys. Default is to have no SLKs. - // You may rewrite this in your derived class - virtual Soft_Label_Key_Set::Label_Layout useSLKs() const { - return Soft_Label_Key_Set::None; - } - - // This method is called to initialize the SLKs. Default is nothing. - // You may rewrite this in your derived class - virtual void init_labels(Soft_Label_Key_Set& S) const { - } - - // Your derived class must implement this method. The return value must - // be the exit value of your application. - virtual int run() = 0; - - // The constructor is protected, so you may use it in your derived - // class constructor. The argument tells whether or not you want colors. - NCursesApplication(bool wantColors = FALSE); - - NCursesApplication& operator=(const NCursesApplication& rhs) - { - if (this != &rhs) { - *this = rhs; - } - return *this; - } - - NCursesApplication(const NCursesApplication& rhs) - : b_Colors(rhs.b_Colors), - Root_Window(rhs.Root_Window) - { - } - -public: - virtual ~NCursesApplication(); - - // Get a pointer to the current application object - static NCursesApplication* getApplication() { - return theApp; - } - - // This method runs the application and returns its exit value - int operator()(void); - - // Process the commandline arguments. The default implementation simply - // ignores them. Your derived class may rewrite this. - virtual void handleArgs(int argc, char* argv[]) { - } - - // Does this application use colors? - inline bool useColors() const { - return b_Colors; - } - - // Push the Key Set S onto the SLK Stack. S then becomes the current set - // of Soft Labelled Keys. - void push(Soft_Label_Key_Set& S); - - // Throw away the current set of SLKs and make the previous one the - // new current set. - bool pop(); - - // Retrieve the current set of Soft Labelled Keys. - Soft_Label_Key_Set* top() const; - - // Attributes to use for menu and forms foregrounds - virtual chtype foregrounds() const { - return b_Colors ? COLOR_PAIR(1) : A_BOLD; - } - - // Attributes to use for menu and forms backgrounds - virtual chtype backgrounds() const { - return b_Colors ? COLOR_PAIR(2) : A_NORMAL; - } - - // Attributes to use for inactive (menu) elements - virtual chtype inactives() const { - return b_Colors ? (COLOR_PAIR(3)|A_DIM) : A_DIM; - } - - // Attributes to use for (form) labels and SLKs - virtual chtype labels() const { - return b_Colors ? COLOR_PAIR(4) : A_NORMAL; - } - - // Attributes to use for form backgrounds - virtual chtype dialog_backgrounds() const { - return b_Colors ? COLOR_PAIR(4) : A_NORMAL; - } - - // Attributes to use as default for (form) window backgrounds - virtual chtype window_backgrounds() const { - return b_Colors ? COLOR_PAIR(5) : A_NORMAL; - } - - // Attributes to use for the title window - virtual chtype screen_titles() const { - return b_Colors ? COLOR_PAIR(6) : A_BOLD; - } - -}; - -#endif /* NCURSES_CURSESAPP_H_incl */ diff --git a/windows/ncurses/include/ncurses/cursesf.h b/windows/ncurses/include/ncurses/cursesf.h deleted file mode 100644 index 215eb295d..000000000 --- a/windows/ncurses/include/ncurses/cursesf.h +++ /dev/null @@ -1,967 +0,0 @@ -// * This makes emacs happy -*-Mode: C++;-*- -/**************************************************************************** - * Copyright (c) 1998-2004,2005 Free Software Foundation, Inc. * - * * - * Permission is hereby granted, free of charge, to any person obtaining a * - * copy of this software and associated documentation files (the * - * "Software"), to deal in the Software without restriction, including * - * without limitation the rights to use, copy, modify, merge, publish, * - * distribute, distribute with modifications, sublicense, and/or sell * - * copies of the Software, and to permit persons to whom the Software is * - * furnished to do so, subject to the following conditions: * - * * - * The above copyright notice and this permission notice shall be included * - * in all copies or substantial portions of the Software. * - * * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * - * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * - * THE USE OR OTHER DEALINGS IN THE SOFTWARE. * - * * - * Except as contained in this notice, the name(s) of the above copyright * - * holders shall not be used in advertising or otherwise to promote the * - * sale, use or other dealings in this Software without prior written * - * authorization. * - ****************************************************************************/ - -/**************************************************************************** - * Author: Juergen Pfeifer, 1997 * - ****************************************************************************/ - -// $Id: cursesf.h,v 1.28 2005/08/13 18:08:24 tom Exp $ - -#ifndef NCURSES_CURSESF_H_incl -#define NCURSES_CURSESF_H_incl 1 - -#include - -#ifndef __EXT_QNX -#include -#endif - -extern "C" { -# include -} -// -// ------------------------------------------------------------------------- -// The abstract base class for buitin and user defined Fieldtypes. -// ------------------------------------------------------------------------- -// -class NCURSES_IMPEXP NCursesFormField; // forward declaration - -// Class to represent builtin field types as well as C++ written new -// fieldtypes (see classes UserDefineFieldType... -class NCURSES_IMPEXP NCursesFieldType -{ - friend class NCursesFormField; - -protected: - FIELDTYPE* fieldtype; - - inline void OnError(int err) const THROWS(NCursesFormException) { - if (err!=E_OK) - THROW(new NCursesFormException (err)); - } - - NCursesFieldType(FIELDTYPE *f) : fieldtype(f) { - } - - virtual ~NCursesFieldType() {} - - // Set the fields f fieldtype to this one. - virtual void set(NCursesFormField& f) = 0; - -public: - NCursesFieldType() - : fieldtype(STATIC_CAST(FIELDTYPE*)(0)) - { - } - - NCursesFieldType& operator=(const NCursesFieldType& rhs) - { - if (this != &rhs) { - *this = rhs; - } - return *this; - } - - NCursesFieldType(const NCursesFieldType& rhs) - : fieldtype(rhs.fieldtype) - { - } - -}; - -// -// ------------------------------------------------------------------------- -// The class representing a forms field, wrapping the lowlevel FIELD struct -// ------------------------------------------------------------------------- -// -class NCURSES_IMPEXP NCursesFormField -{ - friend class NCursesForm; - -protected: - FIELD *field; // lowlevel structure - NCursesFieldType* ftype; // Associated field type - - // Error handler - inline void OnError (int err) const THROWS(NCursesFormException) { - if (err != E_OK) - THROW(new NCursesFormException (err)); - } - -public: - // Create a 'Null' field. Can be used to delimit a field list - NCursesFormField() - : field(STATIC_CAST(FIELD*)(0)), - ftype(STATIC_CAST(NCursesFieldType*)(0)) - { - } - - // Create a new field - NCursesFormField (int rows, - int ncols, - int first_row = 0, - int first_col = 0, - int offscreen_rows = 0, - int additional_buffers = 0) - : field(0), - ftype(STATIC_CAST(NCursesFieldType*)(0)) - { - field = ::new_field(rows, ncols, first_row, first_col, - offscreen_rows, additional_buffers); - if (!field) - OnError(errno); - } - - NCursesFormField& operator=(const NCursesFormField& rhs) - { - if (this != &rhs) { - *this = rhs; - } - return *this; - } - - NCursesFormField(const NCursesFormField& rhs) - : field(rhs.field), ftype(rhs.ftype) - { - } - - virtual ~NCursesFormField (); - - // Duplicate the field at a new position - inline NCursesFormField* dup(int first_row, int first_col) - { - NCursesFormField* f = new NCursesFormField(); - if (!f) - OnError(E_SYSTEM_ERROR); - else { - f->ftype = ftype; - f->field = ::dup_field(field,first_row,first_col); - if (!f->field) - OnError(errno); - } - return f; - } - - // Link the field to a new location - inline NCursesFormField* link(int first_row, int first_col) { - NCursesFormField* f = new NCursesFormField(); - if (!f) - OnError(E_SYSTEM_ERROR); - else { - f->ftype = ftype; - f->field = ::link_field(field,first_row,first_col); - if (!f->field) - OnError(errno); - } - return f; - } - - // Get the lowlevel field representation - inline FIELD* get_field() const { - return field; - } - - // Retrieve info about the field - inline void info(int& rows, int& ncols, - int& first_row, int& first_col, - int& offscreen_rows, int& additional_buffers) const { - OnError(::field_info(field, &rows, &ncols, - &first_row, &first_col, - &offscreen_rows, &additional_buffers)); - } - - // Retrieve info about the fields dynamic properties. - inline void dynamic_info(int& dynamic_rows, int& dynamic_cols, - int& max_growth) const { - OnError(::dynamic_field_info(field, &dynamic_rows, &dynamic_cols, - &max_growth)); - } - - // For a dynamic field you may set the maximum growth limit. - // A zero means unlimited growth. - inline void set_maximum_growth(int growth = 0) { - OnError(::set_max_field(field,growth)); - } - - // Move the field to a new position - inline void move(int row, int col) { - OnError(::move_field(field,row,col)); - } - - // Mark the field to start a new page - inline void new_page(bool pageFlag = FALSE) { - OnError(::set_new_page(field,pageFlag)); - } - - // Retrieve whether or not the field starts a new page. - inline bool is_new_page() const { - return ::new_page(field); - } - - // Set the justification for the field - inline void set_justification(int just) { - OnError(::set_field_just(field,just)); - } - - // Retrieve the fields justification - inline int justification() const { - return ::field_just(field); - } - // Set the foreground attribute for the field - inline void set_foreground(chtype foreground) { - OnError(::set_field_fore(field,foreground)); - } - - // Retrieve the fields foreground attribute - inline chtype fore() const { - return ::field_fore(field); - } - - // Set the background attribute for the field - inline void set_background(chtype background) { - OnError(::set_field_back(field,background)); - } - - // Retrieve the fields background attribute - inline chtype back() const { - return ::field_back(field); - } - - // Set the padding character for the field - inline void set_pad_character(int padding) { - OnError(::set_field_pad(field, padding)); - } - - // Retrieve the fields padding character - inline int pad() const { - return ::field_pad(field); - } - - // Switch on the fields options - inline void options_on (Field_Options opts) { - OnError (::field_opts_on (field, opts)); - } - - // Switch off the fields options - inline void options_off (Field_Options opts) { - OnError (::field_opts_off (field, opts)); - } - - // Retrieve the fields options - inline Field_Options options () const { - return ::field_opts (field); - } - - // Set the fields options - inline void set_options (Field_Options opts) { - OnError (::set_field_opts (field, opts)); - } - - // Mark the field as changed - inline void set_changed(bool changeFlag = TRUE) { - OnError(::set_field_status(field,changeFlag)); - } - - // Test whether or not the field is marked as changed - inline bool changed() const { - return ::field_status(field); - } - - // Return the index of the field in the field array of a form - // or -1 if the field is not associated to a form - inline int (index)() const { - return ::field_index(field); - } - - // Store a value in a fields buffer. The default buffer is nr. 0 - inline void set_value(const char *val, int buffer = 0) { - OnError(::set_field_buffer(field,buffer,val)); - } - - // Retrieve the value of a fields buffer. The default buffer is nr. 0 - inline char* value(int buffer = 0) const { - return ::field_buffer(field,buffer); - } - - // Set the validation type of the field. - inline void set_fieldtype(NCursesFieldType& f) { - ftype = &f; - f.set(*this); // A good friend may do that... - } - - // Retrieve the validation type of the field. - inline NCursesFieldType* fieldtype() const { - return ftype; - } - -}; - - // This are the built-in hook functions in this C++ binding. In C++ we use - // virtual member functions (see below On_..._Init and On_..._Termination) - // to provide this functionality in an object oriented manner. -extern "C" { - void _nc_xx_frm_init(FORM *); - void _nc_xx_frm_term(FORM *); - void _nc_xx_fld_init(FORM *); - void _nc_xx_fld_term(FORM *); -} - -// -// ------------------------------------------------------------------------- -// The class representing a form, wrapping the lowlevel FORM struct -// ------------------------------------------------------------------------- -// -class NCURSES_IMPEXP NCursesForm : public NCursesPanel -{ -protected: - FORM* form; // the lowlevel structure - -private: - NCursesWindow* sub; // the subwindow object - bool b_sub_owner; // is this our own subwindow? - bool b_framed; // has the form a border? - bool b_autoDelete; // Delete fields when deleting form? - - NCursesFormField** my_fields; // The array of fields for this form - - // This structure is used for the form's user data field to link the - // FORM* to the C++ object and to provide extra space for a user pointer. - typedef struct { - void* m_user; // the pointer for the user's data - const NCursesForm* m_back; // backward pointer to C++ object - const FORM* m_owner; - } UserHook; - - // Get the backward pointer to the C++ object from a FORM - static inline NCursesForm* getHook(const FORM *f) { - UserHook* hook = reinterpret_cast(::form_userptr(f)); - assert(hook != 0 && hook->m_owner==f); - return const_cast(hook->m_back); - } - - friend void _nc_xx_frm_init(FORM *); - friend void _nc_xx_frm_term(FORM *); - friend void _nc_xx_fld_init(FORM *); - friend void _nc_xx_fld_term(FORM *); - - // Calculate FIELD* array for the menu - FIELD** mapFields(NCursesFormField* nfields[]); - -protected: - // internal routines - inline void set_user(void *user) { - UserHook* uptr = reinterpret_cast(::form_userptr (form)); - assert (uptr != 0 && uptr->m_back==this && uptr->m_owner==form); - uptr->m_user = user; - } - - inline void *get_user() { - UserHook* uptr = reinterpret_cast(::form_userptr (form)); - assert (uptr != 0 && uptr->m_back==this && uptr->m_owner==form); - return uptr->m_user; - } - - void InitForm (NCursesFormField* Fields[], - bool with_frame, - bool autoDeleteFields); - - inline void OnError (int err) const THROWS(NCursesFormException) { - if (err != E_OK) - THROW(new NCursesFormException (err)); - } - - // this wraps the form_driver call. - virtual int driver (int c) ; - - // 'Internal' constructor, builds an object without association to a - // field array. - NCursesForm( int nlines, - int ncols, - int begin_y = 0, - int begin_x = 0) - : NCursesPanel(nlines, ncols, begin_y, begin_x), - form (STATIC_CAST(FORM*)(0)), - sub(0), - b_sub_owner(0), - b_framed(0), - b_autoDelete(0), - my_fields(0) - { - } - -public: - // Create form for the default panel. - NCursesForm (NCursesFormField* Fields[], - bool with_frame=FALSE, // reserve space for a frame? - bool autoDelete_Fields=FALSE) // do automatic cleanup? - : NCursesPanel(), - form(0), - sub(0), - b_sub_owner(0), - b_framed(0), - b_autoDelete(0), - my_fields(0) - { - InitForm(Fields, with_frame, autoDelete_Fields); - } - - // Create a form in a panel with the given position and size. - NCursesForm (NCursesFormField* Fields[], - int nlines, - int ncols, - int begin_y, - int begin_x, - bool with_frame=FALSE, // reserve space for a frame? - bool autoDelete_Fields=FALSE) // do automatic cleanup? - : NCursesPanel(nlines, ncols, begin_y, begin_x), - form(0), - sub(0), - b_sub_owner(0), - b_framed(0), - b_autoDelete(0), - my_fields(0) - { - InitForm(Fields, with_frame, autoDelete_Fields); - } - - NCursesForm& operator=(const NCursesForm& rhs) - { - if (this != &rhs) { - *this = rhs; - NCursesPanel::operator=(rhs); - } - return *this; - } - - NCursesForm(const NCursesForm& rhs) - : NCursesPanel(rhs), - form(rhs.form), - sub(rhs.sub), - b_sub_owner(rhs.b_sub_owner), - b_framed(rhs.b_framed), - b_autoDelete(rhs.b_autoDelete), - my_fields(rhs.my_fields) - { - } - - virtual ~NCursesForm(); - - // Set the default attributes for the form - virtual void setDefaultAttributes(); - - // Retrieve current field of the form. - inline NCursesFormField* current_field() const { - return my_fields[::field_index(::current_field(form))]; - } - - // Set the forms subwindow - void setSubWindow(NCursesWindow& sub); - - // Set these fields for the form - inline void setFields(NCursesFormField* Fields[]) { - OnError(::set_form_fields(form,mapFields(Fields))); - } - - // Remove the form from the screen - inline void unpost (void) { - OnError (::unpost_form (form)); - } - - // Post the form to the screen if flag is true, unpost it otherwise - inline void post(bool flag = TRUE) { - OnError (flag ? ::post_form(form) : ::unpost_form (form)); - } - - // Decorations - inline void frame(const char *title=NULL, const char* btitle=NULL) { - if (b_framed) - NCursesPanel::frame(title,btitle); - else - OnError(E_SYSTEM_ERROR); - } - - inline void boldframe(const char *title=NULL, const char* btitle=NULL) { - if (b_framed) - NCursesPanel::boldframe(title,btitle); - else - OnError(E_SYSTEM_ERROR); - } - - inline void label(const char *topLabel, const char *bottomLabel) { - if (b_framed) - NCursesPanel::label(topLabel,bottomLabel); - else - OnError(E_SYSTEM_ERROR); - } - - // ----- - // Hooks - // ----- - - // Called after the form gets repositioned in its window. - // This is especially true if the form is posted. - virtual void On_Form_Init(); - - // Called before the form gets repositioned in its window. - // This is especially true if the form is unposted. - virtual void On_Form_Termination(); - - // Called after the field became the current field - virtual void On_Field_Init(NCursesFormField& field); - - // Called before this field is left as current field. - virtual void On_Field_Termination(NCursesFormField& field); - - // Calculate required window size for the form. - void scale(int& rows, int& ncols) const { - OnError(::scale_form(form,&rows,&ncols)); - } - - // Retrieve number of fields in the form. - int count() const { - return ::field_count(form); - } - - // Make the page the current page of the form. - void set_page(int pageNum) { - OnError(::set_form_page(form, pageNum)); - } - - // Retrieve current page number - int page() const { - return ::form_page(form); - } - - // Switch on the forms options - inline void options_on (Form_Options opts) { - OnError (::form_opts_on (form, opts)); - } - - // Switch off the forms options - inline void options_off (Form_Options opts) { - OnError (::form_opts_off (form, opts)); - } - - // Retrieve the forms options - inline Form_Options options () const { - return ::form_opts (form); - } - - // Set the forms options - inline void set_options (Form_Options opts) { - OnError (::set_form_opts (form, opts)); - } - - // Are there more data in the current field after the data shown - inline bool data_ahead() const { - return ::data_ahead(form); - } - - // Are there more data in the current field before the data shown - inline bool data_behind() const { - return ::data_behind(form); - } - - // Position the cursor to the current field - inline void position_cursor () { - OnError (::pos_form_cursor (form)); - } - // Set the current field - inline void set_current(NCursesFormField& F) { - OnError (::set_current_field(form, F.field)); - } - - // Provide a default key virtualization. Translate the keyboard - // code c into a form request code. - // The default implementation provides a hopefully straightforward - // mapping for the most common keystrokes and form requests. - virtual int virtualize(int c); - - // Operators - inline NCursesFormField* operator[](int i) const { - if ( (i < 0) || (i >= ::field_count (form)) ) - OnError (E_BAD_ARGUMENT); - return my_fields[i]; - } - - // Perform the menu's operation - // Return the field where you left the form. - virtual NCursesFormField* operator()(void); - - // Exception handlers. The default is a Beep. - virtual void On_Request_Denied(int c) const; - virtual void On_Invalid_Field(int c) const; - virtual void On_Unknown_Command(int c) const; - -}; - -// -// ------------------------------------------------------------------------- -// This is the typical C++ typesafe way to allow to attach -// user data to a field of a form. Its assumed that the user -// data belongs to some class T. Use T as template argument -// to create a UserField. -// ------------------------------------------------------------------------- -template class NCURSES_IMPEXP NCursesUserField : public NCursesFormField -{ -public: - NCursesUserField (int rows, - int ncols, - int first_row = 0, - int first_col = 0, - const T* p_UserData = STATIC_CAST(T*)(0), - int offscreen_rows = 0, - int additional_buffers = 0) - : NCursesFormField (rows, ncols, - first_row, first_col, - offscreen_rows, additional_buffers) { - if (field) - OnError(::set_field_userptr(field, STATIC_CAST(void *)(p_UserData))); - } - - virtual ~NCursesUserField() {}; - - inline const T* UserData (void) const { - return reinterpret_cast(::field_userptr (field)); - } - - inline virtual void setUserData(const T* p_UserData) { - if (field) - OnError (::set_field_userptr (field, STATIC_CAST(void *)(p_UserData))); - } -}; -// -// ------------------------------------------------------------------------- -// The same mechanism is used to attach user data to a form -// ------------------------------------------------------------------------- -// -template class NCURSES_IMPEXP NCursesUserForm : public NCursesForm -{ -protected: - // 'Internal' constructor, builds an object without association to a - // field array. - NCursesUserForm( int nlines, - int ncols, - int begin_y = 0, - int begin_x = 0, - const T* p_UserData = STATIC_CAST(T*)(0)) - : NCursesForm(nlines,ncols,begin_y,begin_x) { - if (form) - set_user (const_cast(p_UserData)); - } - -public: - NCursesUserForm (NCursesFormField Fields[], - const T* p_UserData = STATIC_CAST(T*)(0), - bool with_frame=FALSE, - bool autoDelete_Fields=FALSE) - : NCursesForm (Fields, with_frame, autoDelete_Fields) { - if (form) - set_user (const_cast(p_UserData)); - }; - - NCursesUserForm (NCursesFormField Fields[], - int nlines, - int ncols, - int begin_y = 0, - int begin_x = 0, - const T* p_UserData = STATIC_CAST(T*)(0), - bool with_frame=FALSE, - bool autoDelete_Fields=FALSE) - : NCursesForm (Fields, nlines, ncols, begin_y, begin_x, - with_frame, autoDelete_Fields) { - if (form) - set_user (const_cast(p_UserData)); - }; - - virtual ~NCursesUserForm() { - }; - - inline T* UserData (void) const { - return reinterpret_cast(get_user ()); - }; - - inline virtual void setUserData (const T* p_UserData) { - if (form) - set_user (const_cast(p_UserData)); - } - -}; -// -// ------------------------------------------------------------------------- -// Builtin Fieldtypes -// ------------------------------------------------------------------------- -// -class NCURSES_IMPEXP Alpha_Field : public NCursesFieldType -{ -private: - int min_field_width; - - void set(NCursesFormField& f) { - OnError(::set_field_type(f.get_field(),fieldtype,min_field_width)); - } - -public: - Alpha_Field(int width) - : NCursesFieldType(TYPE_ALPHA), - min_field_width(width) { - } -}; - -class NCURSES_IMPEXP Alphanumeric_Field : public NCursesFieldType -{ -private: - int min_field_width; - - void set(NCursesFormField& f) { - OnError(::set_field_type(f.get_field(),fieldtype,min_field_width)); - } - -public: - Alphanumeric_Field(int width) - : NCursesFieldType(TYPE_ALNUM), - min_field_width(width) { - } -}; - -class NCURSES_IMPEXP Integer_Field : public NCursesFieldType -{ -private: - int precision; - long lower_limit, upper_limit; - - void set(NCursesFormField& f) { - OnError(::set_field_type(f.get_field(),fieldtype, - precision,lower_limit,upper_limit)); - } - -public: - Integer_Field(int prec, long low=0L, long high=0L) - : NCursesFieldType(TYPE_INTEGER), - precision(prec), lower_limit(low), upper_limit(high) { - } -}; - -class NCURSES_IMPEXP Numeric_Field : public NCursesFieldType -{ -private: - int precision; - double lower_limit, upper_limit; - - void set(NCursesFormField& f) { - OnError(::set_field_type(f.get_field(),fieldtype, - precision,lower_limit,upper_limit)); - } - -public: - Numeric_Field(int prec, double low=0.0, double high=0.0) - : NCursesFieldType(TYPE_NUMERIC), - precision(prec), lower_limit(low), upper_limit(high) { - } -}; - -class NCURSES_IMPEXP Regular_Expression_Field : public NCursesFieldType -{ -private: - char* regex; - - void set(NCursesFormField& f) { - OnError(::set_field_type(f.get_field(),fieldtype,regex)); - } - - void copy_regex(const char *source) - { - regex = new char[1 + ::strlen(source)]; - (::strcpy)(regex, source); - } - -public: - Regular_Expression_Field(const char *expr) - : NCursesFieldType(TYPE_REGEXP), - regex(NULL) - { - copy_regex(expr); - } - - Regular_Expression_Field& operator=(const Regular_Expression_Field& rhs) - { - if (this != &rhs) { - *this = rhs; - copy_regex(rhs.regex); - NCursesFieldType::operator=(rhs); - } - return *this; - } - - Regular_Expression_Field(const Regular_Expression_Field& rhs) - : NCursesFieldType(rhs), - regex(NULL) - { - copy_regex(rhs.regex); - } - - ~Regular_Expression_Field() { - delete[] regex; - } -}; - -class NCURSES_IMPEXP Enumeration_Field : public NCursesFieldType -{ -private: - const char** list; - int case_sensitive; - int non_unique_matches; - - void set(NCursesFormField& f) { - OnError(::set_field_type(f.get_field(),fieldtype, - list,case_sensitive,non_unique_matches)); - } -public: - Enumeration_Field(const char* enums[], - bool case_sens=FALSE, - bool non_unique=FALSE) - : NCursesFieldType(TYPE_ENUM), - list(enums), - case_sensitive(case_sens ? -1 : 0), - non_unique_matches(non_unique ? -1 : 0) { - } - - Enumeration_Field& operator=(const Enumeration_Field& rhs) - { - if (this != &rhs) { - *this = rhs; - NCursesFieldType::operator=(rhs); - } - return *this; - } - - Enumeration_Field(const Enumeration_Field& rhs) - : NCursesFieldType(rhs), - list(rhs.list), - case_sensitive(rhs.case_sensitive), - non_unique_matches(rhs.non_unique_matches) - { - } -}; - -class NCURSES_IMPEXP IPV4_Address_Field : public NCursesFieldType -{ -private: - void set(NCursesFormField& f) { - OnError(::set_field_type(f.get_field(),fieldtype)); - } - -public: - IPV4_Address_Field() : NCursesFieldType(TYPE_IPV4) { - } -}; - -extern "C" { - bool _nc_xx_fld_fcheck(FIELD *, const void*); - bool _nc_xx_fld_ccheck(int c, const void *); - void* _nc_xx_fld_makearg(va_list*); -} - -// -// ------------------------------------------------------------------------- -// Abstract base class for User-Defined Fieldtypes -// ------------------------------------------------------------------------- -// -class NCURSES_IMPEXP UserDefinedFieldType : public NCursesFieldType -{ - friend class UDF_Init; // Internal helper to set up statics -private: - // For all C++ defined fieldtypes we need only one generic lowlevel - // FIELDTYPE* element. - static FIELDTYPE* generic_fieldtype; - -protected: - // This are the functions required by the low level libforms functions - // to construct a fieldtype. - friend bool _nc_xx_fld_fcheck(FIELD *, const void*); - friend bool _nc_xx_fld_ccheck(int c, const void *); - friend void* _nc_xx_fld_makearg(va_list*); - - void set(NCursesFormField& f) { - OnError(::set_field_type(f.get_field(),fieldtype,&f)); - } - -protected: - // Redefine this function to do a field validation. The argument - // is a reference to the field you should validate. - virtual bool field_check(NCursesFormField& f) = 0; - - // Redefine this function to do a character validation. The argument - // is the character to be validated. - virtual bool char_check (int c) = 0; - -public: - UserDefinedFieldType() : NCursesFieldType(generic_fieldtype) { - } -}; - -extern "C" { - bool _nc_xx_next_choice(FIELD*, const void *); - bool _nc_xx_prev_choice(FIELD*, const void *); -} - -// -// ------------------------------------------------------------------------- -// Abstract base class for User-Defined Fieldtypes with Choice functions -// ------------------------------------------------------------------------- -// -class NCURSES_IMPEXP UserDefinedFieldType_With_Choice : public UserDefinedFieldType -{ - friend class UDF_Init; // Internal helper to set up statics -private: - // For all C++ defined fieldtypes with choice functions we need only one - // generic lowlevel FIELDTYPE* element. - static FIELDTYPE* generic_fieldtype_with_choice; - - // This are the functions required by the low level libforms functions - // to construct a fieldtype with choice functions. - friend bool _nc_xx_next_choice(FIELD*, const void *); - friend bool _nc_xx_prev_choice(FIELD*, const void *); - -protected: - // Redefine this function to do the retrieval of the next choice value. - // The argument is a reference to the field tobe examined. - virtual bool next (NCursesFormField& f) = 0; - - // Redefine this function to do the retrieval of the previous choice value. - // The argument is a reference to the field tobe examined. - virtual bool previous(NCursesFormField& f) = 0; - -public: - UserDefinedFieldType_With_Choice() { - fieldtype = generic_fieldtype_with_choice; - } -}; - -#endif /* NCURSES_CURSESF_H_incl */ diff --git a/windows/ncurses/include/ncurses/cursesm.h b/windows/ncurses/include/ncurses/cursesm.h deleted file mode 100644 index 8e0e2c66c..000000000 --- a/windows/ncurses/include/ncurses/cursesm.h +++ /dev/null @@ -1,672 +0,0 @@ -// * This makes emacs happy -*-Mode: C++;-*- -/**************************************************************************** - * Copyright (c) 1998-2003,2005 Free Software Foundation, Inc. * - * * - * Permission is hereby granted, free of charge, to any person obtaining a * - * copy of this software and associated documentation files (the * - * "Software"), to deal in the Software without restriction, including * - * without limitation the rights to use, copy, modify, merge, publish, * - * distribute, distribute with modifications, sublicense, and/or sell * - * copies of the Software, and to permit persons to whom the Software is * - * furnished to do so, subject to the following conditions: * - * * - * The above copyright notice and this permission notice shall be included * - * in all copies or substantial portions of the Software. * - * * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * - * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * - * THE USE OR OTHER DEALINGS IN THE SOFTWARE. * - * * - * Except as contained in this notice, the name(s) of the above copyright * - * holders shall not be used in advertising or otherwise to promote the * - * sale, use or other dealings in this Software without prior written * - * authorization. * - ****************************************************************************/ - -/**************************************************************************** - * Author: Juergen Pfeifer, 1997 * - ****************************************************************************/ - -// $Id: cursesm.h,v 1.25 2005/08/13 18:10:36 tom Exp $ - -#ifndef NCURSES_CURSESM_H_incl -#define NCURSES_CURSESM_H_incl 1 - -#include - -extern "C" { -# include -} -// -// ------------------------------------------------------------------------- -// This wraps the ITEM type of -// ------------------------------------------------------------------------- -// -class NCURSES_IMPEXP NCursesMenuItem -{ - friend class NCursesMenu; - -protected: - ITEM *item; - - inline void OnError (int err) const THROWS(NCursesMenuException) { - if (err != E_OK) - THROW(new NCursesMenuException (err)); - } - -public: - NCursesMenuItem (const char* p_name = NULL, - const char* p_descript = NULL) - : item(0) - { - item = p_name ? ::new_item (p_name, p_descript) : STATIC_CAST(ITEM*)(0); - if (p_name && !item) - OnError (E_SYSTEM_ERROR); - } - // Create an item. If you pass both parameters as NULL, a delimiting - // item is constructed which can be used to terminate a list of - // NCursesMenu objects. - - NCursesMenuItem& operator=(const NCursesMenuItem& rhs) - { - if (this != &rhs) { - *this = rhs; - } - return *this; - } - - NCursesMenuItem(const NCursesMenuItem& rhs) - : item(0) - { - } - - virtual ~NCursesMenuItem (); - // Release the items memory - - inline const char* name () const { - return ::item_name (item); - } - // Name of the item - - inline const char* description () const { - return ::item_description (item); - } - // Description of the item - - inline int (index) (void) const { - return ::item_index (item); - } - // Index of the item in an item array (or -1) - - inline void options_on (Item_Options opts) { - OnError (::item_opts_on (item, opts)); - } - // Switch on the items options - - inline void options_off (Item_Options opts) { - OnError (::item_opts_off (item, opts)); - } - // Switch off the item's option - - inline Item_Options options () const { - return ::item_opts (item); - } - // Retrieve the items options - - inline void set_options (Item_Options opts) { - OnError (::set_item_opts (item, opts)); - } - // Set the items options - - inline void set_value (bool f) { - OnError (::set_item_value (item,f)); - } - // Set/Reset the items selection state - - inline bool value () const { - return ::item_value (item); - } - // Retrieve the items selection state - - inline bool visible () const { - return ::item_visible (item); - } - // Retrieve visibility of the item - - virtual bool action(); - // Perform an action associated with this item; you may use this in an - // user supplied driver for a menu; you may derive from this class and - // overload action() to supply items with different actions. - // If an action returns true, the menu will be exited. The default action - // is to do nothing. -}; - -// Prototype for an items callback function. -typedef bool ITEMCALLBACK(NCursesMenuItem&); - -// If you don't like to create a child class for individual items to -// overload action(), you may use this class and provide a callback -// function pointer for items. -class NCURSES_IMPEXP NCursesMenuCallbackItem : public NCursesMenuItem -{ -private: - ITEMCALLBACK* p_fct; - -public: - NCursesMenuCallbackItem(ITEMCALLBACK* fct = NULL, - const char* p_name = NULL, - const char* p_descript = NULL ) - : NCursesMenuItem (p_name, p_descript), - p_fct (fct) { - } - - NCursesMenuCallbackItem& operator=(const NCursesMenuCallbackItem& rhs) - { - if (this != &rhs) { - *this = rhs; - } - return *this; - } - - NCursesMenuCallbackItem(const NCursesMenuCallbackItem& rhs) - : NCursesMenuItem(rhs), - p_fct(0) - { - } - - virtual ~NCursesMenuCallbackItem(); - - bool action(); -}; - - // This are the built-in hook functions in this C++ binding. In C++ we use - // virtual member functions (see below On_..._Init and On_..._Termination) - // to provide this functionality in an object oriented manner. -extern "C" { - void _nc_xx_mnu_init(MENU *); - void _nc_xx_mnu_term(MENU *); - void _nc_xx_itm_init(MENU *); - void _nc_xx_itm_term(MENU *); -} - -// -// ------------------------------------------------------------------------- -// This wraps the MENU type of -// ------------------------------------------------------------------------- -// -class NCURSES_IMPEXP NCursesMenu : public NCursesPanel -{ -protected: - MENU *menu; - -private: - NCursesWindow* sub; // the subwindow object - bool b_sub_owner; // is this our own subwindow? - bool b_framed; // has the menu a border? - bool b_autoDelete; // Delete items when deleting menu? - - NCursesMenuItem** my_items; // The array of items for this menu - - // This structure is used for the menu's user data field to link the - // MENU* to the C++ object and to provide extra space for a user pointer. - typedef struct { - void* m_user; // the pointer for the user's data - const NCursesMenu* m_back; // backward pointer to C++ object - const MENU* m_owner; - } UserHook; - - // Get the backward pointer to the C++ object from a MENU - static inline NCursesMenu* getHook(const MENU *m) { - UserHook* hook = STATIC_CAST(UserHook*)(::menu_userptr(m)); - assert(hook != 0 && hook->m_owner==m); - return const_cast(hook->m_back); - } - - friend void _nc_xx_mnu_init(MENU *); - friend void _nc_xx_mnu_term(MENU *); - friend void _nc_xx_itm_init(MENU *); - friend void _nc_xx_itm_term(MENU *); - - // Calculate ITEM* array for the menu - ITEM** mapItems(NCursesMenuItem* nitems[]); - -protected: - // internal routines - inline void set_user(void *user) { - UserHook* uptr = STATIC_CAST(UserHook*)(::menu_userptr (menu)); - assert (uptr != 0 && uptr->m_back==this && uptr->m_owner==menu); - uptr->m_user = user; - } - - inline void *get_user() { - UserHook* uptr = STATIC_CAST(UserHook*)(::menu_userptr (menu)); - assert (uptr != 0 && uptr->m_back==this && uptr->m_owner==menu); - return uptr->m_user; - } - - void InitMenu (NCursesMenuItem* menu[], - bool with_frame, - bool autoDeleteItems); - - inline void OnError (int err) const THROWS(NCursesMenuException) { - if (err != E_OK) - THROW(new NCursesMenuException (this, err)); - } - - // this wraps the menu_driver call. - virtual int driver (int c) ; - - // 'Internal' constructor to create a menu without association to - // an array of items. - NCursesMenu( int nlines, - int ncols, - int begin_y = 0, - int begin_x = 0) - : NCursesPanel(nlines,ncols,begin_y,begin_x), - menu (STATIC_CAST(MENU*)(0)), - sub(0), - b_sub_owner(0), - b_framed(0), - b_autoDelete(0), - my_items(0) - { - } - -public: - // Make a full window size menu - NCursesMenu (NCursesMenuItem* Items[], - bool with_frame=FALSE, // Reserve space for a frame? - bool autoDelete_Items=FALSE) // Autocleanup of Items? - : NCursesPanel(), - menu(0), - sub(0), - b_sub_owner(0), - b_framed(0), - b_autoDelete(0), - my_items(0) - { - InitMenu(Items, with_frame, autoDelete_Items); - } - - // Make a menu with a window of this size. - NCursesMenu (NCursesMenuItem* Items[], - int nlines, - int ncols, - int begin_y = 0, - int begin_x = 0, - bool with_frame=FALSE, // Reserve space for a frame? - bool autoDelete_Items=FALSE) // Autocleanup of Items? - : NCursesPanel(nlines, ncols, begin_y, begin_x), - menu(0), - sub(0), - b_sub_owner(0), - b_framed(0), - b_autoDelete(0), - my_items(0) - { - InitMenu(Items, with_frame, autoDelete_Items); - } - - NCursesMenu& operator=(const NCursesMenu& rhs) - { - if (this != &rhs) { - *this = rhs; - NCursesPanel::operator=(rhs); - } - return *this; - } - - NCursesMenu(const NCursesMenu& rhs) - : NCursesPanel(rhs), - menu(rhs.menu), - sub(rhs.sub), - b_sub_owner(rhs.b_sub_owner), - b_framed(rhs.b_framed), - b_autoDelete(rhs.b_autoDelete), - my_items(rhs.my_items) - { - } - - virtual ~NCursesMenu (); - - // Retrieve the menus subwindow - inline NCursesWindow& subWindow() const { - assert(sub!=NULL); - return *sub; - } - - // Set the menus subwindow - void setSubWindow(NCursesWindow& sub); - - // Set these items for the menu - inline void setItems(NCursesMenuItem* Items[]) { - OnError(::set_menu_items(menu,mapItems(Items))); - } - - // Remove the menu from the screen - inline void unpost (void) { - OnError (::unpost_menu (menu)); - } - - // Post the menu to the screen if flag is true, unpost it otherwise - inline void post(bool flag = TRUE) { - flag ? OnError (::post_menu(menu)) : OnError (::unpost_menu (menu)); - } - - // Get the numer of rows and columns for this menu - inline void scale (int& mrows, int& mcols) const { - OnError (::scale_menu (menu, &mrows, &mcols)); - } - - // Set the format of this menu - inline void set_format(int mrows, int mcols) { - OnError (::set_menu_format(menu, mrows, mcols)); - } - - // Get the format of this menu - inline void menu_format(int& rows,int& ncols) { - ::menu_format(menu,&rows,&ncols); - } - - // Items of the menu - inline NCursesMenuItem* items() const { - return *my_items; - } - - // Get the number of items in this menu - inline int count() const { - return ::item_count(menu); - } - - // Get the current item (i.e. the one the cursor is located) - inline NCursesMenuItem* current_item() const { - return my_items[::item_index(::current_item(menu))]; - } - - // Get the marker string - inline const char* mark() const { - return ::menu_mark(menu); - } - - // Set the marker string - inline void set_mark(const char *marker) { - OnError (::set_menu_mark (menu, marker)); - } - - // Get the name of the request code c - inline static const char* request_name(int c) { - return ::menu_request_name(c); - } - - // Get the current pattern - inline char* pattern() const { - return ::menu_pattern(menu); - } - - // true if there is a pattern match, false otherwise. - bool set_pattern (const char *pat); - - // set the default attributes for the menu - // i.e. set fore, back and grey attribute - virtual void setDefaultAttributes(); - - // Get the menus background attributes - inline chtype back() const { - return ::menu_back(menu); - } - - // Get the menus foreground attributes - inline chtype fore() const { - return ::menu_fore(menu); - } - - // Get the menus grey attributes (used for unselectable items) - inline chtype grey() const { - return ::menu_grey(menu); - } - - // Set the menus background attributes - inline chtype set_background(chtype a) { - return ::set_menu_back(menu,a); - } - - // Set the menus foreground attributes - inline chtype set_foreground(chtype a) { - return ::set_menu_fore(menu,a); - } - - // Set the menus grey attributes (used for unselectable items) - inline chtype set_grey(chtype a) { - return ::set_menu_grey(menu,a); - } - - inline void options_on (Menu_Options opts) { - OnError (::menu_opts_on (menu,opts)); - } - - inline void options_off(Menu_Options opts) { - OnError (::menu_opts_off(menu,opts)); - } - - inline Menu_Options options() const { - return ::menu_opts(menu); - } - - inline void set_options (Menu_Options opts) { - OnError (::set_menu_opts (menu,opts)); - } - - inline int pad() const { - return ::menu_pad(menu); - } - - inline void set_pad (int padch) { - OnError (::set_menu_pad (menu, padch)); - } - - // Position the cursor to the current item - inline void position_cursor () const { - OnError (::pos_menu_cursor (menu)); - } - - // Set the current item - inline void set_current(NCursesMenuItem& I) { - OnError (::set_current_item(menu, I.item)); - } - - // Get the current top row of the menu - inline int top_row (void) const { - return ::top_row (menu); - } - - // Set the current top row of the menu - inline void set_top_row (int row) { - OnError (::set_top_row (menu, row)); - } - - // spacing control - // Set the spacing for the menu - inline void setSpacing(int spc_description, - int spc_rows, - int spc_columns) { - OnError(::set_menu_spacing(menu, - spc_description, - spc_rows, - spc_columns)); - } - - // Get the spacing info for the menu - inline void Spacing(int& spc_description, - int& spc_rows, - int& spc_columns) const { - OnError(::menu_spacing(menu, - &spc_description, - &spc_rows, - &spc_columns)); - } - - // Decorations - inline void frame(const char *title=NULL, const char* btitle=NULL) { - if (b_framed) - NCursesPanel::frame(title,btitle); - else - OnError(E_SYSTEM_ERROR); - } - - inline void boldframe(const char *title=NULL, const char* btitle=NULL) { - if (b_framed) - NCursesPanel::boldframe(title,btitle); - else - OnError(E_SYSTEM_ERROR); - } - - inline void label(const char *topLabel, const char *bottomLabel) { - if (b_framed) - NCursesPanel::label(topLabel,bottomLabel); - else - OnError(E_SYSTEM_ERROR); - } - - // ----- - // Hooks - // ----- - - // Called after the menu gets repositioned in its window. - // This is especially true if the menu is posted. - virtual void On_Menu_Init(); - - // Called before the menu gets repositioned in its window. - // This is especially true if the menu is unposted. - virtual void On_Menu_Termination(); - - // Called after the item became the current item - virtual void On_Item_Init(NCursesMenuItem& item); - - // Called before this item is left as current item. - virtual void On_Item_Termination(NCursesMenuItem& item); - - // Provide a default key virtualization. Translate the keyboard - // code c into a menu request code. - // The default implementation provides a hopefully straightforward - // mapping for the most common keystrokes and menu requests. - virtual int virtualize(int c); - - - // Operators - inline NCursesMenuItem* operator[](int i) const { - if ( (i < 0) || (i >= ::item_count (menu)) ) - OnError (E_BAD_ARGUMENT); - return (my_items[i]); - } - - // Perform the menu's operation - // Return the item where you left the selection mark for a single - // selection menu, or NULL for a multivalued menu. - virtual NCursesMenuItem* operator()(void); - - // -------------------- - // Exception handlers - // Called by operator() - // -------------------- - - // Called if the request is denied - virtual void On_Request_Denied(int c) const; - - // Called if the item is not selectable - virtual void On_Not_Selectable(int c) const; - - // Called if pattern doesn't match - virtual void On_No_Match(int c) const; - - // Called if the command is unknown - virtual void On_Unknown_Command(int c) const; - -}; -// -// ------------------------------------------------------------------------- -// This is the typical C++ typesafe way to allow to attach -// user data to an item of a menu. Its assumed that the user -// data belongs to some class T. Use T as template argument -// to create a UserItem. -// ------------------------------------------------------------------------- -// -template class NCURSES_IMPEXP NCursesUserItem : public NCursesMenuItem -{ -public: - NCursesUserItem (const char* p_name, - const char* p_descript = NULL, - const T* p_UserData = STATIC_CAST(T*)(0)) - : NCursesMenuItem (p_name, p_descript) { - if (item) - OnError (::set_item_userptr (item, const_cast(reinterpret_cast(p_UserData)))); - } - - virtual ~NCursesUserItem() {} - - inline const T* UserData (void) const { - return reinterpret_cast(::item_userptr (item)); - }; - - inline virtual void setUserData(const T* p_UserData) { - if (item) - OnError (::set_item_userptr (item, const_cast(reinterpret_cast(p_UserData)))); - } -}; -// -// ------------------------------------------------------------------------- -// The same mechanism is used to attach user data to a menu -// ------------------------------------------------------------------------- -// -template class NCURSES_IMPEXP NCursesUserMenu : public NCursesMenu -{ -protected: - NCursesUserMenu( int nlines, - int ncols, - int begin_y = 0, - int begin_x = 0, - const T* p_UserData = STATIC_CAST(T*)(0)) - : NCursesMenu(nlines,ncols,begin_y,begin_x) { - if (menu) - set_user (const_cast(p_UserData)); - } - -public: - NCursesUserMenu (NCursesMenuItem Items[], - const T* p_UserData = STATIC_CAST(T*)(0), - bool with_frame=FALSE, - bool autoDelete_Items=FALSE) - : NCursesMenu (Items, with_frame, autoDelete_Items) { - if (menu) - set_user (const_cast(p_UserData)); - }; - - NCursesUserMenu (NCursesMenuItem Items[], - int nlines, - int ncols, - int begin_y = 0, - int begin_x = 0, - const T* p_UserData = STATIC_CAST(T*)(0), - bool with_frame=FALSE) - : NCursesMenu (Items, nlines, ncols, begin_y, begin_x, with_frame) { - if (menu) - set_user (const_cast(p_UserData)); - }; - - virtual ~NCursesUserMenu() { - }; - - inline T* UserData (void) const { - return reinterpret_cast(get_user ()); - }; - - inline virtual void setUserData (const T* p_UserData) { - if (menu) - set_user (const_cast(p_UserData)); - } -}; - -#endif /* NCURSES_CURSESM_H_incl */ diff --git a/windows/ncurses/include/ncurses/cursesp.h b/windows/ncurses/include/ncurses/cursesp.h deleted file mode 100644 index 720f999d0..000000000 --- a/windows/ncurses/include/ncurses/cursesp.h +++ /dev/null @@ -1,268 +0,0 @@ -// * This makes emacs happy -*-Mode: C++;-*- -/**************************************************************************** - * Copyright (c) 1998-2007,2008 Free Software Foundation, Inc. * - * * - * Permission is hereby granted, free of charge, to any person obtaining a * - * copy of this software and associated documentation files (the * - * "Software"), to deal in the Software without restriction, including * - * without limitation the rights to use, copy, modify, merge, publish, * - * distribute, distribute with modifications, sublicense, and/or sell * - * copies of the Software, and to permit persons to whom the Software is * - * furnished to do so, subject to the following conditions: * - * * - * The above copyright notice and this permission notice shall be included * - * in all copies or substantial portions of the Software. * - * * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * - * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * - * THE USE OR OTHER DEALINGS IN THE SOFTWARE. * - * * - * Except as contained in this notice, the name(s) of the above copyright * - * holders shall not be used in advertising or otherwise to promote the * - * sale, use or other dealings in this Software without prior written * - * authorization. * - ****************************************************************************/ - -/**************************************************************************** - * Author: Juergen Pfeifer, 1997 * - ****************************************************************************/ - -#ifndef NCURSES_CURSESP_H_incl -#define NCURSES_CURSESP_H_incl 1 - -// $Id: cursesp.h,v 1.29 2008/08/16 17:20:23 tom Exp $ - -#include - -extern "C" { -# include -} - -class NCURSES_IMPEXP NCursesPanel - : public NCursesWindow -{ -protected: - PANEL *p; - static NCursesPanel *dummy; - -private: - // This structure is used for the panel's user data field to link the - // PANEL* to the C++ object and to provide extra space for a user pointer. - typedef struct { - void* m_user; // the pointer for the user's data - const NCursesPanel* m_back; // backward pointer to C++ object - const PANEL* m_owner; // the panel itself - } UserHook; - - inline UserHook *UserPointer() - { - UserHook* uptr = reinterpret_cast( - const_cast(::panel_userptr (p))); - return uptr; - } - - void init(); // Initialize the panel object - -protected: - void set_user(void *user) - { - UserHook* uptr = UserPointer(); - if (uptr != 0 && uptr->m_back==this && uptr->m_owner==p) { - uptr->m_user = user; - } - } - // Set the user pointer of the panel. - - void *get_user() - { - UserHook* uptr = UserPointer(); - void *result = 0; - if (uptr != 0 && uptr->m_back==this && uptr->m_owner==p) - result = uptr->m_user; - return result; - } - - void OnError (int err) const THROWS(NCursesPanelException) - { - if (err==ERR) - THROW(new NCursesPanelException (this, err)); - } - // If err is equal to the curses error indicator ERR, an error handler - // is called. - - // Get a keystroke. Default implementation calls getch() - virtual int getKey(void); - -public: - NCursesPanel(int nlines, - int ncols, - int begin_y = 0, - int begin_x = 0) - : NCursesWindow(nlines,ncols,begin_y,begin_x), p(0) - { - init(); - } - // Create a panel with this size starting at the requested position. - - NCursesPanel() - : NCursesWindow(::stdscr), p(0) - { - init(); - } - // This constructor creates the default Panel associated with the - // ::stdscr window - - NCursesPanel& operator=(const NCursesPanel& rhs) - { - if (this != &rhs) { - *this = rhs; - NCursesWindow::operator=(rhs); - } - return *this; - } - - NCursesPanel(const NCursesPanel& rhs) - : NCursesWindow(rhs), - p(rhs.p) - { - } - - virtual ~NCursesPanel(); - - // basic manipulation - inline void hide() - { - OnError (::hide_panel(p)); - } - // Hide the panel. It stays in the stack but becomes invisible. - - inline void show() - { - OnError (::show_panel(p)); - } - // Show the panel, i.e. make it visible. - - inline void top() - { - OnError (::top_panel(p)); - } - // Make this panel the top panel in the stack. - - inline void bottom() - { - OnError (::bottom_panel(p)); - } - // Make this panel the bottom panel in the stack. - // N.B.: The panel associated with ::stdscr is always on the bottom. So - // actually bottom() makes the panel the first above ::stdscr. - - virtual int mvwin(int y, int x) - { - OnError(::move_panel(p, y, x)); - return OK; - } - - inline bool hidden() const - { - return (::panel_hidden (p) ? TRUE : FALSE); - } - // Return TRUE if the panel is hidden, FALSE otherwise. - -/* The functions panel_above() and panel_below() are not reflected in - the NCursesPanel class. The reason for this is, that we cannot - assume that a panel retrieved by those operations is one wrapped - by a C++ class. Although this situation might be handled, we also - need a reverse mapping from PANEL to NCursesPanel which needs some - redesign of the low level stuff. At the moment, we define them in the - interface but they will always produce an error. */ - inline NCursesPanel& above() const - { - OnError(ERR); - return *dummy; - } - - inline NCursesPanel& below() const - { - OnError(ERR); - return *dummy; - } - - // Those two are rewrites of the corresponding virtual members of - // NCursesWindow - virtual int refresh(); - // Propagate all panel changes to the virtual screen and update the - // physical screen. - - virtual int noutrefresh(); - // Propagate all panel changes to the virtual screen. - - static void redraw(); - // Redraw all panels. - - // decorations - virtual void frame(const char* title=NULL, - const char* btitle=NULL); - // Put a frame around the panel and put the title centered in the top line - // and btitle in the bottom line. - - virtual void boldframe(const char* title=NULL, - const char* btitle=NULL); - // Same as frame(), but use highlighted attributes. - - virtual void label(const char* topLabel, - const char* bottomLabel); - // Put the title centered in the top line and btitle in the bottom line. - - virtual void centertext(int row,const char* label); - // Put the label text centered in the specified row. -}; - -/* We use templates to provide a typesafe mechanism to associate - * user data with a panel. A NCursesUserPanel is a panel - * associated with some user data of type T. - */ -template class NCursesUserPanel : public NCursesPanel -{ -public: - NCursesUserPanel (int nlines, - int ncols, - int begin_y = 0, - int begin_x = 0, - const T* p_UserData = STATIC_CAST(T*)(0)) - : NCursesPanel (nlines, ncols, begin_y, begin_x) - { - if (p) - set_user (const_cast(p_UserData)); - }; - // This creates an user panel of the requested size with associated - // user data pointed to by p_UserData. - - NCursesUserPanel(const T* p_UserData = STATIC_CAST(T*)(0)) : NCursesPanel() - { - if (p) - set_user(const_cast(p_UserData)); - }; - // This creates an user panel associated with the ::stdscr and user data - // pointed to by p_UserData. - - virtual ~NCursesUserPanel() {}; - - T* UserData (void) const - { - return reinterpret_cast(get_user ()); - }; - // Retrieve the user data associated with the panel. - - virtual void setUserData (const T* p_UserData) - { - if (p) - set_user (const_cast(p_UserData)); - } - // Associate the user panel with the user data pointed to by p_UserData. -}; - -#endif /* NCURSES_CURSESP_H_incl */ diff --git a/windows/ncurses/include/ncurses/cursesw.h b/windows/ncurses/include/ncurses/cursesw.h deleted file mode 100644 index 95659f2fd..000000000 --- a/windows/ncurses/include/ncurses/cursesw.h +++ /dev/null @@ -1,1556 +0,0 @@ -// * This makes emacs happy -*-Mode: C++;-*- -// vile:cppmode -/**************************************************************************** - * Copyright (c) 1998-2007,2008 Free Software Foundation, Inc. * - * * - * Permission is hereby granted, free of charge, to any person obtaining a * - * copy of this software and associated documentation files (the * - * "Software"), to deal in the Software without restriction, including * - * without limitation the rights to use, copy, modify, merge, publish, * - * distribute, distribute with modifications, sublicense, and/or sell * - * copies of the Software, and to permit persons to whom the Software is * - * furnished to do so, subject to the following conditions: * - * * - * The above copyright notice and this permission notice shall be included * - * in all copies or substantial portions of the Software. * - * * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * - * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * - * THE USE OR OTHER DEALINGS IN THE SOFTWARE. * - * * - * Except as contained in this notice, the name(s) of the above copyright * - * holders shall not be used in advertising or otherwise to promote the * - * sale, use or other dealings in this Software without prior written * - * authorization. * - ****************************************************************************/ - -#ifndef NCURSES_CURSESW_H_incl -#define NCURSES_CURSESW_H_incl 1 - -// $Id: cursesw.h,v 1.48 2008/01/19 21:09:10 tom Exp $ - -#include - -extern "C" { -# include -} - -/* SCO 3.2v4 curses.h includes term.h, which defines lines as a macro. - Undefine it here, because NCursesWindow uses lines as a method. */ -#undef lines - -/* "Convert" macros to inlines. We'll define it as another symbol to avoid - * conflict with library symbols. - */ -#undef UNDEF -#define UNDEF(name) CUR_ ##name - -#ifdef addch -inline int UNDEF(addch)(chtype ch) { return addch(ch); } -#undef addch -#define addch UNDEF(addch) -#endif - -#ifdef addchstr -inline int UNDEF(addchstr)(chtype *at) { return addchstr(at); } -#undef addchstr -#define addchstr UNDEF(addchstr) -#endif - -#ifdef addnstr -inline int UNDEF(addnstr)(const char *str, int n) -{ return addnstr(str, n); } -#undef addnstr -#define addnstr UNDEF(addnstr) -#endif - -#ifdef addstr -inline int UNDEF(addstr)(const char * str) { return addstr(str); } -#undef addstr -#define addstr UNDEF(addstr) -#endif - -#ifdef attroff -inline int UNDEF(attroff)(chtype at) { return attroff(at); } -#undef attroff -#define attroff UNDEF(attroff) -#endif - -#ifdef attron -inline int UNDEF(attron)(chtype at) { return attron(at); } -#undef attron -#define attron UNDEF(attron) -#endif - -#ifdef attrset -inline chtype UNDEF(attrset)(chtype at) { return attrset(at); } -#undef attrset -#define attrset UNDEF(attrset) -#endif - -#ifdef bkgd -inline int UNDEF(bkgd)(chtype ch) { return bkgd(ch); } -#undef bkgd -#define bkgd UNDEF(bkgd) -#endif - -#ifdef bkgdset -inline void UNDEF(bkgdset)(chtype ch) { bkgdset(ch); } -#undef bkgdset -#define bkgdset UNDEF(bkgdset) -#endif - -#ifdef border -inline int UNDEF(border)(chtype ls, chtype rs, chtype ts, chtype bs, chtype tl, chtype tr, chtype bl, chtype br) -{ return border(ls, rs, ts, bs, tl, tr, bl, br); } -#undef border -#define border UNDEF(border) -#endif - -#ifdef box -inline int UNDEF(box)(WINDOW *win, int v, int h) { return box(win, v, h); } -#undef box -#define box UNDEF(box) -#endif - -#ifdef chgat -inline int UNDEF(chgat)(int n, attr_t attr, short color, const void *opts) { - return chgat(n, attr, color, opts); } -#undef chgat -#define chgat UNDEF(chgat) -#endif - -#ifdef clear -inline int UNDEF(clear)() { return clear(); } -#undef clear -#define clear UNDEF(clear) -#endif - -#ifdef clearok -inline int UNDEF(clearok)(WINDOW* win, bool bf) { return clearok(win, bf); } -#undef clearok -#define clearok UNDEF(clearok) -#else -extern "C" NCURSES_IMPEXP int NCURSES_API clearok(WINDOW*, bool); -#endif - -#ifdef clrtobot -inline int UNDEF(clrtobot)() { return clrtobot(); } -#undef clrtobot -#define clrtobot UNDEF(clrtobot) -#endif - -#ifdef clrtoeol -inline int UNDEF(clrtoeol)() { return clrtoeol(); } -#undef clrtoeol -#define clrtoeol UNDEF(clrtoeol) -#endif - -#ifdef color_set -inline chtype UNDEF(color_set)(short p, void* opts) { return color_set(p, opts); } -#undef color_set -#define color_set UNDEF(color_set) -#endif - -#ifdef crmode -inline int UNDEF(crmode)(void) { return crmode(); } -#undef crmode -#define crmode UNDEF(crmode) -#endif - -#ifdef delch -inline int UNDEF(delch)() { return delch(); } -#undef delch -#define delch UNDEF(delch) -#endif - -#ifdef deleteln -inline int UNDEF(deleteln)() { return deleteln(); } -#undef deleteln -#define deleteln UNDEF(deleteln) -#endif - -#ifdef echochar -inline int UNDEF(echochar)(chtype ch) { return echochar(ch); } -#undef echochar -#define echochar UNDEF(echochar) -#endif - -#ifdef erase -inline int UNDEF(erase)() { return erase(); } -#undef erase -#define erase UNDEF(erase) -#endif - -#ifdef fixterm -inline int UNDEF(fixterm)(void) { return fixterm(); } -#undef fixterm -#define fixterm UNDEF(fixterm) -#endif - -#ifdef flushok -inline int UNDEF(flushok)(WINDOW* _win, bool _bf) { - return flushok(_win, _bf); } -#undef flushok -#define flushok UNDEF(flushok) -#else -#define _no_flushok -#endif - -#ifdef getattrs -inline int UNDEF(getattrs)(WINDOW *win) { return getattrs(win); } -#undef getattrs -#define getattrs UNDEF(getattrs) -#endif - -#ifdef getbegyx -inline void UNDEF(getbegyx)(WINDOW* win, int& y, int& x) { getbegyx(win, y, x); } -#undef getbegyx -#define getbegyx UNDEF(getbegyx) -#endif - -#ifdef getbkgd -inline chtype UNDEF(getbkgd)(const WINDOW *win) { return getbkgd(win); } -#undef getbkgd -#define getbkgd UNDEF(getbkgd) -#endif - -#ifdef getch -inline int UNDEF(getch)() { return getch(); } -#undef getch -#define getch UNDEF(getch) -#endif - -#ifdef getmaxyx -inline void UNDEF(getmaxyx)(WINDOW* win, int& y, int& x) { getmaxyx(win, y, x); } -#undef getmaxyx -#define getmaxyx UNDEF(getmaxyx) -#endif - -#ifdef getnstr -inline int UNDEF(getnstr)(char *_str, int n) { return getnstr(_str, n); } -#undef getnstr -#define getnstr UNDEF(getnstr) -#endif - -#ifdef getparyx -inline void UNDEF(getparyx)(WINDOW* win, int& y, int& x) { getparyx(win, y, x); } -#undef getparyx -#define getparyx UNDEF(getparyx) -#endif - -#ifdef getstr -inline int UNDEF(getstr)(char *_str) { return getstr(_str); } -#undef getstr -#define getstr UNDEF(getstr) -#endif - -#ifdef getyx -inline void UNDEF(getyx)(const WINDOW* win, int& y, int& x) { - getyx(win, y, x); } -#undef getyx -#define getyx UNDEF(getyx) -#endif - -#ifdef hline -inline int UNDEF(hline)(chtype ch, int n) { return hline(ch, n); } -#undef hline -#define hline UNDEF(hline) -#endif - -#ifdef inch -inline chtype UNDEF(inch)() { return inch(); } -#undef inch -#define inch UNDEF(inch) -#endif - -#ifdef inchstr -inline int UNDEF(inchstr)(chtype *str) { return inchstr(str); } -#undef inchstr -#define inchstr UNDEF(inchstr) -#endif - -#ifdef innstr -inline int UNDEF(innstr)(char *_str, int n) { return innstr(_str, n); } -#undef innstr -#define innstr UNDEF(innstr) -#endif - -#ifdef insch -inline int UNDEF(insch)(chtype c) { return insch(c); } -#undef insch -#define insch UNDEF(insch) -#endif - -#ifdef insdelln -inline int UNDEF(insdelln)(int n) { return insdelln(n); } -#undef insdelln -#define insdelln UNDEF(insdelln) -#endif - -#ifdef insertln -inline int UNDEF(insertln)() { return insertln(); } -#undef insertln -#define insertln UNDEF(insertln) -#endif - -#ifdef insnstr -inline int UNDEF(insnstr)(const char *_str, int n) { - return insnstr(_str, n); } -#undef insnstr -#define insnstr UNDEF(insnstr) -#endif - -#ifdef insstr -inline int UNDEF(insstr)(const char *_str) { - return insstr(_str); } -#undef insstr -#define insstr UNDEF(insstr) -#endif - -#ifdef instr -inline int UNDEF(instr)(char *_str) { return instr(_str); } -#undef instr -#define instr UNDEF(instr) -#endif - -#ifdef intrflush -inline void UNDEF(intrflush)(WINDOW *win, bool bf) { intrflush(); } -#undef intrflush -#define intrflush UNDEF(intrflush) -#endif - -#ifdef leaveok -inline int UNDEF(leaveok)(WINDOW* win, bool bf) { return leaveok(win, bf); } -#undef leaveok -#define leaveok UNDEF(leaveok) -#else -extern "C" NCURSES_IMPEXP int NCURSES_API leaveok(WINDOW* win, bool bf); -#endif - -#ifdef move -inline int UNDEF(move)(int x, int y) { return move(x, y); } -#undef move -#define move UNDEF(move) -#endif - -#ifdef mvaddch -inline int UNDEF(mvaddch)(int y, int x, chtype ch) -{ return mvaddch(y, x, ch); } -#undef mvaddch -#define mvaddch UNDEF(mvaddch) -#endif - -#ifdef mvaddnstr -inline int UNDEF(mvaddnstr)(int y, int x, const char *str, int n) -{ return mvaddnstr(y, x, str, n); } -#undef mvaddnstr -#define mvaddnstr UNDEF(mvaddnstr) -#endif - -#ifdef mvaddstr -inline int UNDEF(mvaddstr)(int y, int x, const char * str) -{ return mvaddstr(y, x, str); } -#undef mvaddstr -#define mvaddstr UNDEF(mvaddstr) -#endif - -#ifdef mvchgat -inline int UNDEF(mvchgat)(int y, int x, int n, - attr_t attr, short color, const void *opts) { - return mvchgat(y, x, n, attr, color, opts); } -#undef mvchgat -#define mvchgat UNDEF(mvchgat) -#endif - -#ifdef mvdelch -inline int UNDEF(mvdelch)(int y, int x) { return mvdelch(y, x);} -#undef mvdelch -#define mvdelch UNDEF(mvdelch) -#endif - -#ifdef mvgetch -inline int UNDEF(mvgetch)(int y, int x) { return mvgetch(y, x);} -#undef mvgetch -#define mvgetch UNDEF(mvgetch) -#endif - -#ifdef mvgetnstr -inline int UNDEF(mvgetnstr)(int y, int x, char *str, int n) { - return mvgetnstr(y, x, str, n);} -#undef mvgetnstr -#define mvgetnstr UNDEF(mvgetnstr) -#endif - -#ifdef mvgetstr -inline int UNDEF(mvgetstr)(int y, int x, char *str) {return mvgetstr(y, x, str);} -#undef mvgetstr -#define mvgetstr UNDEF(mvgetstr) -#endif - -#ifdef mvinch -inline chtype UNDEF(mvinch)(int y, int x) { return mvinch(y, x);} -#undef mvinch -#define mvinch UNDEF(mvinch) -#endif - -#ifdef mvinnstr -inline int UNDEF(mvinnstr)(int y, int x, char *_str, int n) { - return mvinnstr(y, x, _str, n); } -#undef mvinnstr -#define mvinnstr UNDEF(mvinnstr) -#endif - -#ifdef mvinsch -inline int UNDEF(mvinsch)(int y, int x, chtype c) -{ return mvinsch(y, x, c); } -#undef mvinsch -#define mvinsch UNDEF(mvinsch) -#endif - -#ifdef mvinsnstr -inline int UNDEF(mvinsnstr)(int y, int x, const char *_str, int n) { - return mvinsnstr(y, x, _str, n); } -#undef mvinsnstr -#define mvinsnstr UNDEF(mvinsnstr) -#endif - -#ifdef mvinsstr -inline int UNDEF(mvinsstr)(int y, int x, const char *_str) { - return mvinsstr(y, x, _str); } -#undef mvinsstr -#define mvinsstr UNDEF(mvinsstr) -#endif - -#ifdef mvwaddch -inline int UNDEF(mvwaddch)(WINDOW *win, int y, int x, const chtype ch) -{ return mvwaddch(win, y, x, ch); } -#undef mvwaddch -#define mvwaddch UNDEF(mvwaddch) -#endif - -#ifdef mvwaddchnstr -inline int UNDEF(mvwaddchnstr)(WINDOW *win, int y, int x, const chtype *str, int n) -{ return mvwaddchnstr(win, y, x, str, n); } -#undef mvwaddchnstr -#define mvwaddchnstr UNDEF(mvwaddchnstr) -#endif - -#ifdef mvwaddchstr -inline int UNDEF(mvwaddchstr)(WINDOW *win, int y, int x, const chtype *str) -{ return mvwaddchstr(win, y, x, str); } -#undef mvwaddchstr -#define mvwaddchstr UNDEF(mvwaddchstr) -#endif - -#ifdef mvwaddnstr -inline int UNDEF(mvwaddnstr)(WINDOW *win, int y, int x, const char *str, int n) -{ return mvwaddnstr(win, y, x, str, n); } -#undef mvwaddnstr -#define mvwaddnstr UNDEF(mvwaddnstr) -#endif - -#ifdef mvwaddstr -inline int UNDEF(mvwaddstr)(WINDOW *win, int y, int x, const char * str) -{ return mvwaddstr(win, y, x, str); } -#undef mvwaddstr -#define mvwaddstr UNDEF(mvwaddstr) -#endif - -#ifdef mvwchgat -inline int UNDEF(mvwchgat)(WINDOW *win, int y, int x, int n, - attr_t attr, short color, const void *opts) { - return mvwchgat(win, y, x, n, attr, color, opts); } -#undef mvwchgat -#define mvwchgat UNDEF(mvwchgat) -#endif - -#ifdef mvwdelch -inline int UNDEF(mvwdelch)(WINDOW *win, int y, int x) -{ return mvwdelch(win, y, x); } -#undef mvwdelch -#define mvwdelch UNDEF(mvwdelch) -#endif - -#ifdef mvwgetch -inline int UNDEF(mvwgetch)(WINDOW *win, int y, int x) { return mvwgetch(win, y, x);} -#undef mvwgetch -#define mvwgetch UNDEF(mvwgetch) -#endif - -#ifdef mvwgetnstr -inline int UNDEF(mvwgetnstr)(WINDOW *win, int y, int x, char *str, int n) -{return mvwgetnstr(win, y, x, str, n);} -#undef mvwgetnstr -#define mvwgetnstr UNDEF(mvwgetnstr) -#endif - -#ifdef mvwgetstr -inline int UNDEF(mvwgetstr)(WINDOW *win, int y, int x, char *str) -{return mvwgetstr(win, y, x, str);} -#undef mvwgetstr -#define mvwgetstr UNDEF(mvwgetstr) -#endif - -#ifdef mvwhline -inline int UNDEF(mvwhline)(WINDOW *win, int y, int x, chtype c, int n) { - return mvwhline(win, y, x, c, n); } -#undef mvwhline -#define mvwhline UNDEF(mvwhline) -#endif - -#ifdef mvwinch -inline chtype UNDEF(mvwinch)(WINDOW *win, int y, int x) { - return mvwinch(win, y, x);} -#undef mvwinch -#define mvwinch UNDEF(mvwinch) -#endif - -#ifdef mvwinchnstr -inline int UNDEF(mvwinchnstr)(WINDOW *win, int y, int x, chtype *str, int n) { return mvwinchnstr(win, y, x, str, n); } -#undef mvwinchnstr -#define mvwinchnstr UNDEF(mvwinchnstr) -#endif - -#ifdef mvwinchstr -inline int UNDEF(mvwinchstr)(WINDOW *win, int y, int x, chtype *str) { return mvwinchstr(win, y, x, str); } -#undef mvwinchstr -#define mvwinchstr UNDEF(mvwinchstr) -#endif - -#ifdef mvwinnstr -inline int UNDEF(mvwinnstr)(WINDOW *win, int y, int x, char *_str, int n) { - return mvwinnstr(win, y, x, _str, n); } -#undef mvwinnstr -#define mvwinnstr UNDEF(mvwinnstr) -#endif - -#ifdef mvwinsch -inline int UNDEF(mvwinsch)(WINDOW *win, int y, int x, chtype c) -{ return mvwinsch(win, y, x, c); } -#undef mvwinsch -#define mvwinsch UNDEF(mvwinsch) -#endif - -#ifdef mvwinsnstr -inline int UNDEF(mvwinsnstr)(WINDOW *w, int y, int x, const char *_str, int n) { - return mvwinsnstr(w, y, x, _str, n); } -#undef mvwinsnstr -#define mvwinsnstr UNDEF(mvwinsnstr) -#endif - -#ifdef mvwinsstr -inline int UNDEF(mvwinsstr)(WINDOW *w, int y, int x, const char *_str) { - return mvwinsstr(w, y, x, _str); } -#undef mvwinsstr -#define mvwinsstr UNDEF(mvwinsstr) -#endif - -#ifdef mvwvline -inline int UNDEF(mvwvline)(WINDOW *win, int y, int x, chtype c, int n) { - return mvwvline(win, y, x, c, n); } -#undef mvwvline -#define mvwvline UNDEF(mvwvline) -#endif - -#ifdef napms -inline void UNDEF(napms)(unsigned long x) { napms(x); } -#undef napms -#define napms UNDEF(napms) -#endif - -#ifdef nocrmode -inline int UNDEF(nocrmode)(void) { return nocrmode(); } -#undef nocrmode -#define nocrmode UNDEF(nocrmode) -#endif - -#ifdef nodelay -inline void UNDEF(nodelay)() { nodelay(); } -#undef nodelay -#define nodelay UNDEF(nodelay) -#endif - -#ifdef redrawwin -inline int UNDEF(redrawwin)(WINDOW *win) { return redrawwin(win); } -#undef redrawwin -#define redrawwin UNDEF(redrawwin) -#endif - -#ifdef refresh -inline int UNDEF(refresh)() { return refresh(); } -#undef refresh -#define refresh UNDEF(refresh) -#endif - -#ifdef resetterm -inline int UNDEF(resetterm)(void) { return resetterm(); } -#undef resetterm -#define resetterm UNDEF(resetterm) -#endif - -#ifdef saveterm -inline int UNDEF(saveterm)(void) { return saveterm(); } -#undef saveterm -#define saveterm UNDEF(saveterm) -#endif - -#ifdef scrl -inline int UNDEF(scrl)(int l) { return scrl(l); } -#undef scrl -#define scrl UNDEF(scrl) -#endif - -#ifdef scroll -inline int UNDEF(scroll)(WINDOW *win) { return scroll(win); } -#undef scroll -#define scroll UNDEF(scroll) -#endif - -#ifdef scrollok -inline int UNDEF(scrollok)(WINDOW* win, bool bf) { return scrollok(win, bf); } -#undef scrollok -#define scrollok UNDEF(scrollok) -#else -#if defined(__NCURSES_H) -extern "C" NCURSES_IMPEXP int NCURSES_API scrollok(WINDOW*, bool); -#else -extern "C" NCURSES_IMPEXP int NCURSES_API scrollok(WINDOW*, char); -#endif -#endif - -#ifdef setscrreg -inline int UNDEF(setscrreg)(int t, int b) { return setscrreg(t, b); } -#undef setscrreg -#define setscrreg UNDEF(setscrreg) -#endif - -#ifdef standend -inline int UNDEF(standend)() { return standend(); } -#undef standend -#define standend UNDEF(standend) -#endif - -#ifdef standout -inline int UNDEF(standout)() { return standout(); } -#undef standout -#define standout UNDEF(standout) -#endif - -#ifdef subpad -inline WINDOW *UNDEF(subpad)(WINDOW *p, int l, int c, int y, int x) -{ return derwin(p, l, c, y, x); } -#undef subpad -#define subpad UNDEF(subpad) -#endif - -#ifdef timeout -inline void UNDEF(timeout)(int delay) { timeout(delay); } -#undef timeout -#define timeout UNDEF(timeout) -#endif - -#ifdef touchline -inline int UNDEF(touchline)(WINDOW *win, int s, int c) -{ return touchline(win, s, c); } -#undef touchline -#define touchline UNDEF(touchline) -#endif - -#ifdef touchwin -inline int UNDEF(touchwin)(WINDOW *win) { return touchwin(win); } -#undef touchwin -#define touchwin UNDEF(touchwin) -#endif - -#ifdef untouchwin -inline int UNDEF(untouchwin)(WINDOW *win) { return untouchwin(win); } -#undef untouchwin -#define untouchwin UNDEF(untouchwin) -#endif - -#ifdef vline -inline int UNDEF(vline)(chtype ch, int n) { return vline(ch, n); } -#undef vline -#define vline UNDEF(vline) -#endif - -#ifdef waddchstr -inline int UNDEF(waddchstr)(WINDOW *win, chtype *at) { return waddchstr(win, at); } -#undef waddchstr -#define waddchstr UNDEF(waddchstr) -#endif - -#ifdef waddstr -inline int UNDEF(waddstr)(WINDOW *win, char *str) { return waddstr(win, str); } -#undef waddstr -#define waddstr UNDEF(waddstr) -#endif - -#ifdef wattroff -inline int UNDEF(wattroff)(WINDOW *win, int att) { return wattroff(win, att); } -#undef wattroff -#define wattroff UNDEF(wattroff) -#endif - -#ifdef wattrset -inline int UNDEF(wattrset)(WINDOW *win, int att) { return wattrset(win, att); } -#undef wattrset -#define wattrset UNDEF(wattrset) -#endif - -#ifdef winch -inline chtype UNDEF(winch)(const WINDOW* win) { return winch(win); } -#undef winch -#define winch UNDEF(winch) -#endif - -#ifdef winchnstr -inline int UNDEF(winchnstr)(WINDOW *win, chtype *str, int n) { return winchnstr(win, str, n); } -#undef winchnstr -#define winchnstr UNDEF(winchnstr) -#endif - -#ifdef winchstr -inline int UNDEF(winchstr)(WINDOW *win, chtype *str) { return winchstr(win, str); } -#undef winchstr -#define winchstr UNDEF(winchstr) -#endif - -#ifdef winsstr -inline int UNDEF(winsstr)(WINDOW *w, const char *_str) { - return winsstr(w, _str); } -#undef winsstr -#define winsstr UNDEF(winsstr) -#endif - -#ifdef wstandend -inline int UNDEF(wstandend)(WINDOW *win) { return wstandend(win); } -#undef wstandend -#define wstandend UNDEF(wstandend) -#endif - -#ifdef wstandout -inline int UNDEF(wstandout)(WINDOW *win) { return wstandout(win); } -#undef wstandout -#define wstandout UNDEF(wstandout) -#endif - -/* - * - * C++ class for windows. - * - */ - -extern "C" int _nc_ripoffline(int, int (*init)(WINDOW*, int)); -extern "C" int _nc_xx_ripoff_init(WINDOW *, int); -extern "C" int _nc_has_mouse(void); - -class NCURSES_IMPEXP NCursesWindow -{ - friend class NCursesMenu; - friend class NCursesForm; - -private: - static bool b_initialized; - static void initialize(); - void constructing(); - friend int _nc_xx_ripoff_init(WINDOW *, int); - - void set_keyboard(); - - short getcolor(int getback) const; - short getPair() const; - - static int setpalette(short fore, short back, short pair); - static int colorInitialized; - - // This private constructor is only used during the initialization - // of windows generated by ripoffline() calls. - NCursesWindow(WINDOW* win, int ncols); - -protected: - virtual void err_handler(const char *) const THROWS(NCursesException); - // Signal an error with the given message text. - - static long count; // count of all active windows: - // We rely on the c++ promise that - // all otherwise uninitialized - // static class vars are set to 0 - - WINDOW* w; // the curses WINDOW - - bool alloced; // TRUE if we own the WINDOW - - NCursesWindow* par; // parent, if subwindow - NCursesWindow* subwins; // head of subwindows list - NCursesWindow* sib; // next subwindow of parent - - void kill_subwindows(); // disable all subwindows - // Destroy all subwindows. - - /* Only for use by derived classes. They are then in charge to - fill the member variables correctly. */ - NCursesWindow(); - -public: - NCursesWindow(WINDOW* window); // useful only for stdscr - - NCursesWindow(int nlines, // number of lines - int ncols, // number of columns - int begin_y, // line origin - int begin_x); // col origin - - NCursesWindow(NCursesWindow& par,// parent window - int nlines, // number of lines - int ncols, // number of columns - int begin_y, // absolute or relative - int begin_x, // origins: - char absrel = 'a');// if `a', begin_y & begin_x are - // absolute screen pos, else if `r', they are relative to par origin - - NCursesWindow(NCursesWindow& par,// parent window - bool do_box = TRUE); - // this is the very common case that we want to create the subwindow that - // is two lines and two columns smaller and begins at (1,1). - // We may automatically request the box around it. - - NCursesWindow& operator=(const NCursesWindow& rhs) - { - if (this != &rhs) - *this = rhs; - return *this; - } - - NCursesWindow(const NCursesWindow& rhs) - : w(rhs.w), alloced(rhs.alloced), par(rhs.par), subwins(rhs.subwins), sib(rhs.sib) - { - } - - virtual ~NCursesWindow(); - - NCursesWindow Clone(); - // Make an exact copy of the window. - - // Initialization. - static void useColors(void); - // Call this routine very early if you want to have colors. - - static int ripoffline(int ripoff_lines, - int (*init)(NCursesWindow& win)); - // This function is used to generate a window of ripped-of lines. - // If the argument is positive, lines are removed from the top, if it - // is negative lines are removed from the bottom. This enhances the - // lowlevel ripoffline() function because it uses the internal - // implementation that allows to remove more than just a single line. - // This function must be called before any other ncurses function. The - // creation of the window is deferred until ncurses gets initialized. - // The initialization function is then called. - - // ------------------------------------------------------------------------- - // terminal status - // ------------------------------------------------------------------------- - int lines() const { initialize(); return LINES; } - // Number of lines on terminal, *not* window - - int cols() const { initialize(); return COLS; } - // Number of cols on terminal, *not* window - - int tabsize() const { initialize(); return TABSIZE; } - // Size of a tab on terminal, *not* window - - static int NumberOfColors(); - // Number of available colors - - int colors() const { return NumberOfColors(); } - // Number of available colors - - // ------------------------------------------------------------------------- - // window status - // ------------------------------------------------------------------------- - int height() const { return maxy() + 1; } - // Number of lines in this window - - int width() const { return maxx() + 1; } - // Number of columns in this window - - int begx() const { return getbegx(w); } - // Column of top left corner relative to stdscr - - int begy() const { return getbegy(w); } - // Line of top left corner relative to stdscr - - int curx() const { return getcurx(w); } - // Column of top left corner relative to stdscr - - int cury() const { return getcury(w); } - // Line of top left corner relative to stdscr - - int maxx() const { return getmaxx(w) == ERR ? ERR : getmaxx(w)-1; } - // Largest x coord in window - - int maxy() const { return getmaxy(w) == ERR ? ERR : getmaxy(w)-1; } - // Largest y coord in window - - short getcolor() const; - // Actual color pair - - short foreground() const { return getcolor(0); } - // Actual foreground color - - short background() const { return getcolor(1); } - // Actual background color - - int setpalette(short fore, short back); - // Set color palette entry - - int setcolor(short pair); - // Set actually used palette entry - - // ------------------------------------------------------------------------- - // window positioning - // ------------------------------------------------------------------------- - virtual int mvwin(int begin_y, int begin_x) { - return ::mvwin(w, begin_y, begin_x); } - // Move window to new position with the new position as top left corner. - // This is virtual because it is redefined in NCursesPanel. - - // ------------------------------------------------------------------------- - // coordinate positioning - // ------------------------------------------------------------------------- - int move(int y, int x) { return ::wmove(w, y, x); } - // Move cursor the this position - - void getyx(int& y, int& x) const { ::getyx(w, y, x); } - // Get current position of the cursor - - void getbegyx(int& y, int& x) const { ::getbegyx(w, y, x); } - // Get beginning of the window - - void getmaxyx(int& y, int& x) const { ::getmaxyx(w, y, x); } - // Get size of the window - - void getparyx(int& y, int& x) const { ::getparyx(w, y, x); } - // Get parent's beginning of the window - - int mvcur(int oldrow, int oldcol, int newrow, int newcol) const { - return ::mvcur(oldrow, oldcol, newrow, newcol); } - // Perform lowlevel cursor motion that takes effect immediately. - - // ------------------------------------------------------------------------- - // input - // ------------------------------------------------------------------------- - int getch() { return ::wgetch(w); } - // Get a keystroke from the window. - - int getch(int y, int x) { return ::mvwgetch(w, y, x); } - // Move cursor to position and get a keystroke from the window - - int getstr(char* str, int n=-1) { - return ::wgetnstr(w, str, n); } - // Read a series of characters into str until a newline or carriage return - // is received. Read at most n characters. If n is negative, the limit is - // ignored. - - int getstr(int y, int x, char* str, int n=-1) { - return ::mvwgetnstr(w, y, x, str, n); } - // Move the cursor to the requested position and then perform the getstr() - // as described above. - - int instr(char *s, int n=-1) { return ::winnstr(w, s, n); } - // Get a string of characters from the window into the buffer s. Retrieve - // at most n characters, if n is negative retrieve all characters up to the - // end of the current line. Attributes are stripped from the characters. - - int instr(int y, int x, char *s, int n=-1) { - return ::mvwinnstr(w, y, x, s, n); } - // Move the cursor to the requested position and then perform the instr() - // as described above. - - int scanw(const char* fmt, ...) - // Perform a scanw function from the window. -#if __GNUG__ >= 2 - __attribute__ ((format (scanf, 2, 3))); -#else - ; -#endif - - int scanw(const char*, va_list); - // Perform a scanw function from the window. - - int scanw(int y, int x, const char* fmt, ...) - // Move the cursor to the requested position and then perform a scanw - // from the window. -#if __GNUG__ >= 2 - __attribute__ ((format (scanf, 4, 5))); -#else - ; -#endif - - int scanw(int y, int x, const char* fmt, va_list); - // Move the cursor to the requested position and then perform a scanw - // from the window. - - // ------------------------------------------------------------------------- - // output - // ------------------------------------------------------------------------- - int addch(const chtype ch) { return ::waddch(w, ch); } - // Put attributed character to the window. - - int addch(int y, int x, const chtype ch) { - return ::mvwaddch(w, y, x, ch); } - // Move cursor to the requested position and then put attributed character - // to the window. - - int echochar(const chtype ch) { return ::wechochar(w, ch); } - // Put attributed character to the window and refresh it immediately. - - int addstr(const char* str, int n=-1) { - return ::waddnstr(w, str, n); } - // Write the string str to the window, stop writing if the terminating - // NUL or the limit n is reached. If n is negative, it is ignored. - - int addstr(int y, int x, const char * str, int n=-1) { - return ::mvwaddnstr(w, y, x, str, n); } - // Move the cursor to the requested position and then perform the addchstr - // as described above. - - int addchstr(const chtype* str, int n=-1) { - return ::waddchnstr(w, str, n); } - // Write the string str to the window, stop writing if the terminating - // NUL or the limit n is reached. If n is negative, it is ignored. - - int addchstr(int y, int x, const chtype * str, int n=-1) { - return ::mvwaddchnstr(w, y, x, str, n); } - // Move the cursor to the requested position and then perform the addchstr - // as described above. - - int printw(const char* fmt, ...) - // Do a formatted print to the window. -#if (__GNUG__ >= 2) && !defined(printf) - __attribute__ ((format (printf, 2, 3))); -#else - ; -#endif - - int printw(int y, int x, const char * fmt, ...) - // Move the cursor and then do a formatted print to the window. -#if (__GNUG__ >= 2) && !defined(printf) - __attribute__ ((format (printf, 4, 5))); -#else - ; -#endif - - int printw(const char* fmt, va_list args); - // Do a formatted print to the window. - - int printw(int y, int x, const char * fmt, va_list args); - // Move the cursor and then do a formatted print to the window. - - chtype inch() const { return ::winch(w); } - // Retrieve attributed character under the current cursor position. - - chtype inch(int y, int x) { return ::mvwinch(w, y, x); } - // Move cursor to requested position and then retrieve attributed character - // at this position. - - int inchstr(chtype* str, int n=-1) { - return ::winchnstr(w, str, n); } - // Read the string str from the window, stop reading if the terminating - // NUL or the limit n is reached. If n is negative, it is ignored. - - int inchstr(int y, int x, chtype * str, int n=-1) { - return ::mvwinchnstr(w, y, x, str, n); } - // Move the cursor to the requested position and then perform the inchstr - // as described above. - - int insch(chtype ch) { return ::winsch(w, ch); } - // Insert attributed character into the window before current cursor - // position. - - int insch(int y, int x, chtype ch) { - return ::mvwinsch(w, y, x, ch); } - // Move cursor to requested position and then insert the attributed - // character before that position. - - int insertln() { return ::winsdelln(w, 1); } - // Insert an empty line above the current line. - - int insdelln(int n=1) { return ::winsdelln(w, n); } - // If n>0 insert that many lines above the current line. If n<0 delete - // that many lines beginning with the current line. - - int insstr(const char *s, int n=-1) { - return ::winsnstr(w, s, n); } - // Insert the string into the window before the current cursor position. - // Insert stops at end of string or when the limit n is reached. If n is - // negative, it is ignored. - - int insstr(int y, int x, const char *s, int n=-1) { - return ::mvwinsnstr(w, y, x, s, n); } - // Move the cursor to the requested position and then perform the insstr() - // as described above. - - int attron (chtype at) { return ::wattron (w, at); } - // Switch on the window attributes; - - int attroff(chtype at) { return ::wattroff(w, static_cast(at)); } - // Switch off the window attributes; - - int attrset(chtype at) { return ::wattrset(w, static_cast(at)); } - // Set the window attributes; - - chtype attrget() { return ::getattrs(w); } - // Get the window attributes; - - int color_set(short color_pair_number, void* opts=NULL) { - return ::wcolor_set(w, color_pair_number, opts); } - // Set the window color attribute; - - int chgat(int n, attr_t attr, short color, const void *opts=NULL) { - return ::wchgat(w, n, attr, color, opts); } - // Change the attributes of the next n characters in the current line. If - // n is negative or greater than the number of remaining characters in the - // line, the attributes will be changed up to the end of the line. - - int chgat(int y, int x, - int n, attr_t attr, short color, const void *opts=NULL) { - return ::mvwchgat(w, y, x, n, attr, color, opts); } - // Move the cursor to the requested position and then perform chgat() as - // described above. - - // ------------------------------------------------------------------------- - // background - // ------------------------------------------------------------------------- - chtype getbkgd() const { return ::getbkgd(w); } - // Get current background setting. - - int bkgd(const chtype ch) { return ::wbkgd(w, ch); } - // Set the background property and apply it to the window. - - void bkgdset(chtype ch) { ::wbkgdset(w, ch); } - // Set the background property. - - // ------------------------------------------------------------------------- - // borders - // ------------------------------------------------------------------------- - int box(chtype vert=0, chtype hor=0) { - return ::wborder(w, vert, vert, hor, hor, 0, 0, 0, 0); } - // Draw a box around the window with the given vertical and horizontal - // drawing characters. If you specify a zero as character, curses will try - // to find a "nice" character. - - int border(chtype left=0, chtype right=0, - chtype top =0, chtype bottom=0, - chtype top_left =0, chtype top_right=0, - chtype bottom_left =0, chtype bottom_right=0) { - return ::wborder(w, left, right, top, bottom, top_left, top_right, - bottom_left, bottom_right); } - // Draw a border around the window with the given characters for the - // various parts of the border. If you pass zero for a character, curses - // will try to find "nice" characters. - - // ------------------------------------------------------------------------- - // lines and boxes - // ------------------------------------------------------------------------- - int hline(int len, chtype ch=0) { return ::whline(w, ch, len); } - // Draw a horizontal line of len characters with the given character. If - // you pass zero for the character, curses will try to find a "nice" one. - - int hline(int y, int x, int len, chtype ch=0) { - return ::mvwhline(w, y, x, ch, len); } - // Move the cursor to the requested position and then draw a horizontal line. - - int vline(int len, chtype ch=0) { return ::wvline(w, ch, len); } - // Draw a vertical line of len characters with the given character. If - // you pass zero for the character, curses will try to find a "nice" one. - - int vline(int y, int x, int len, chtype ch=0) { - return ::mvwvline(w, y, x, ch, len); } - // Move the cursor to the requested position and then draw a vertical line. - - // ------------------------------------------------------------------------- - // erasure - // ------------------------------------------------------------------------- - int erase() { return ::werase(w); } - // Erase the window. - - int clear() { return ::wclear(w); } - // Clear the window. - - int clearok(bool bf) { return ::clearok(w, bf); } - // Set/Reset the clear flag. If set, the next refresh() will clear the - // screen. - - int clrtobot() { return ::wclrtobot(w); } - // Clear to the end of the window. - - int clrtoeol() { return ::wclrtoeol(w); } - // Clear to the end of the line. - - int delch() { return ::wdelch(w); } - // Delete character under the cursor. - - int delch(int y, int x) { return ::mvwdelch(w, y, x); } - // Move cursor to requested position and delete the character under the - // cursor. - - int deleteln() { return ::winsdelln(w, -1); } - // Delete the current line. - - // ------------------------------------------------------------------------- - // screen control - // ------------------------------------------------------------------------- - int scroll(int amount=1) { return ::wscrl(w, amount); } - // Scroll amount lines. If amount is positive, scroll up, otherwise - // scroll down. - - int scrollok(bool bf) { return ::scrollok(w, bf); } - // If bf is TRUE, window scrolls if cursor is moved off the bottom - // edge of the window or a scrolling region, otherwise the cursor is left - // at the bottom line. - - int setscrreg(int from, int to) { - return ::wsetscrreg(w, from, to); } - // Define a soft scrolling region. - - int idlok(bool bf) { return ::idlok(w, bf); } - // If bf is TRUE, use insert/delete line hardware support if possible. - // Otherwise do it in software. - - void idcok(bool bf) { ::idcok(w, bf); } - // If bf is TRUE, use insert/delete character hardware support if possible. - // Otherwise do it in software. - - int touchline(int s, int c) { return ::touchline(w, s, c); } - // Mark the given lines as modified. - - int touchwin() { return ::wtouchln(w, 0, height(), 1); } - // Mark the whole window as modified. - - int untouchwin() { return ::wtouchln(w, 0, height(), 0); } - // Mark the whole window as unmodified. - - int touchln(int s, int cnt, bool changed=TRUE) { - return ::wtouchln(w, s, cnt, static_cast(changed ? 1 : 0)); } - // Mark cnt lines beginning from line s as changed or unchanged, depending - // on the value of the changed flag. - - bool is_linetouched(int line) const { - return (::is_linetouched(w, line) ? TRUE:FALSE); } - // Return TRUE if line is marked as changed, FALSE otherwise - - bool is_wintouched() const { - return (::is_wintouched(w) ? TRUE:FALSE); } - // Return TRUE if window is marked as changed, FALSE otherwise - - int leaveok(bool bf) { return ::leaveok(w, bf); } - // If bf is TRUE, curses will leave the cursor after an update whereever - // it is after the update. - - int redrawln(int from, int n) { return ::wredrawln(w, from, n); } - // Redraw n lines starting from the requested line - - int redrawwin() { return ::wredrawln(w, 0, height()); } - // Redraw the whole window - - int doupdate() { return ::doupdate(); } - // Do all outputs to make the physical screen looking like the virtual one - - void syncdown() { ::wsyncdown(w); } - // Propagate the changes down to all descendant windows - - void syncup() { ::wsyncup(w); } - // Propagate the changes up in the hierarchy - - void cursyncup() { ::wcursyncup(w); } - // Position the cursor in all ancestor windows corresponding to our setting - - int syncok(bool bf) { return ::syncok(w, bf); } - // If called with bf=TRUE, syncup() is called whenever the window is changed - -#ifndef _no_flushok - int flushok(bool bf) { return ::flushok(w, bf); } -#endif - - void immedok(bool bf) { ::immedok(w, bf); } - // If called with bf=TRUE, any change in the window will cause an - // automatic immediate refresh() - - int intrflush(bool bf) { return ::intrflush(w, bf); } - - int keypad(bool bf) { return ::keypad(w, bf); } - // If called with bf=TRUE, the application will interpret function keys. - - int nodelay(bool bf) { return ::nodelay(w, bf); } - - int meta(bool bf) { return ::meta(w, bf); } - // If called with bf=TRUE, keys may generate 8-Bit characters. Otherwise - // 7-Bit characters are generated. - - int standout() { return ::wstandout(w); } - // Enable "standout" attributes - - int standend() { return ::wstandend(w); } - // Disable "standout" attributes - - // ------------------------------------------------------------------------- - // The next two are virtual, because we redefine them in the - // NCursesPanel class. - // ------------------------------------------------------------------------- - virtual int refresh() { return ::wrefresh(w); } - // Propagate the changes in this window to the virtual screen and call - // doupdate(). This is redefined in NCursesPanel. - - virtual int noutrefresh() { return ::wnoutrefresh(w); } - // Propagate the changes in this window to the virtual screen. This is - // redefined in NCursesPanel. - - // ------------------------------------------------------------------------- - // multiple window control - // ------------------------------------------------------------------------- - int overlay(NCursesWindow& win) { - return ::overlay(w, win.w); } - // Overlay this window over win. - - int overwrite(NCursesWindow& win) { - return ::overwrite(w, win.w); } - // Overwrite win with this window. - - int copywin(NCursesWindow& win, - int sminrow, int smincol, - int dminrow, int dmincol, - int dmaxrow, int dmaxcol, bool overlaywin=TRUE) { - return ::copywin(w, win.w, sminrow, smincol, dminrow, dmincol, - dmaxrow, dmaxcol, static_cast(overlaywin ? 1 : 0)); } - // Overlay or overwrite the rectangle in win given by dminrow,dmincol, - // dmaxrow,dmaxcol with the rectangle in this window beginning at - // sminrow,smincol. - - // ------------------------------------------------------------------------- - // Extended functions - // ------------------------------------------------------------------------- -#if defined(NCURSES_EXT_FUNCS) && (NCURSES_EXT_FUNCS != 0) - int wresize(int newLines, int newColumns) { - return ::wresize(w, newLines, newColumns); } -#endif - - // ------------------------------------------------------------------------- - // Mouse related - // ------------------------------------------------------------------------- - bool has_mouse() const; - // Return TRUE if terminal supports a mouse, FALSE otherwise - - // ------------------------------------------------------------------------- - // traversal support - // ------------------------------------------------------------------------- - NCursesWindow* child() { return subwins; } - // Get the first child window. - - NCursesWindow* sibling() { return sib; } - // Get the next child of my parent. - - NCursesWindow* parent() { return par; } - // Get my parent. - - bool isDescendant(NCursesWindow& win); - // Return TRUE if win is a descendant of this. -}; - -// ------------------------------------------------------------------------- -// We leave this here for compatibility reasons. -// ------------------------------------------------------------------------- -class NCURSES_IMPEXP NCursesColorWindow : public NCursesWindow -{ -public: - NCursesColorWindow(WINDOW* &window) // useful only for stdscr - : NCursesWindow(window) { - useColors(); } - - NCursesColorWindow(int nlines, // number of lines - int ncols, // number of columns - int begin_y, // line origin - int begin_x) // col origin - : NCursesWindow(nlines, ncols, begin_y, begin_x) { - useColors(); } - - NCursesColorWindow(NCursesWindow& parentWin,// parent window - int nlines, // number of lines - int ncols, // number of columns - int begin_y, // absolute or relative - int begin_x, // origins: - char absrel = 'a') // if `a', by & bx are - : NCursesWindow(parentWin, - nlines, ncols, // absolute screen pos, - begin_y, begin_x, // else if `r', they are - absrel ) { // relative to par origin - useColors(); } -}; - -// These enum definitions really belong inside the NCursesPad class, but only -// recent compilers support that feature. - - typedef enum { - REQ_PAD_REFRESH = KEY_MAX + 1, - REQ_PAD_UP, - REQ_PAD_DOWN, - REQ_PAD_LEFT, - REQ_PAD_RIGHT, - REQ_PAD_EXIT - } Pad_Request; - - const Pad_Request PAD_LOW = REQ_PAD_REFRESH; // lowest op-code - const Pad_Request PAD_HIGH = REQ_PAD_EXIT; // highest op-code - -// ------------------------------------------------------------------------- -// Pad Support. We allow an association of a pad with a "real" window -// through which the pad may be viewed. -// ------------------------------------------------------------------------- -class NCURSES_IMPEXP NCursesPad : public NCursesWindow -{ -private: - NCursesWindow* viewWin; // the "viewport" window - NCursesWindow* viewSub; // the "viewport" subwindow - - int h_gridsize, v_gridsize; - -protected: - int min_row, min_col; // top left row/col of the pads display area - - NCursesWindow* Win(void) const { - // Get the window into which the pad should be copied (if any) - return (viewSub?viewSub:(viewWin?viewWin:0)); - } - - NCursesWindow* getWindow(void) const { - return viewWin; - } - - NCursesWindow* getSubWindow(void) const { - return viewSub; - } - - virtual int driver (int key); // Virtualize keystroke key - // The driver translates the keystroke c into an Pad_Request - - virtual void OnUnknownOperation(int pad_req) { - ::beep(); - } - // This is called if the driver returns an unknown op-code - - virtual void OnNavigationError(int pad_req) { - ::beep(); - } - // This is called if a navigation request couldn't be satisfied - - virtual void OnOperation(int pad_req) { - }; - // OnOperation is called if a Pad_Operation was executed and just before - // the refresh() operation is done. - -public: - NCursesPad(int nlines, int ncols); - // create a pad with the given size - - NCursesPad& operator=(const NCursesPad& rhs) - { - if (this != &rhs) { - *this = rhs; - NCursesWindow::operator=(rhs); - } - return *this; - } - - NCursesPad(const NCursesPad& rhs) - : NCursesWindow(rhs), - viewWin(rhs.viewWin), - viewSub(rhs.viewSub), - h_gridsize(rhs.h_gridsize), - v_gridsize(rhs.v_gridsize), - min_row(rhs.min_row), - min_col(rhs.min_col) - { - } - - virtual ~NCursesPad() {} - - int echochar(const chtype ch) { return ::pechochar(w, ch); } - // Put the attributed character onto the pad and immediately do a - // prefresh(). - - int refresh(); - // If a viewport is defined the pad is displayed in this window, otherwise - // this is a noop. - - int refresh(int pminrow, int pmincol, - int sminrow, int smincol, - int smaxrow, int smaxcol) { - return ::prefresh(w, pminrow, pmincol, - sminrow, smincol, smaxrow, smaxcol); - } - // The coordinates sminrow,smincol,smaxrow,smaxcol describe a rectangle - // on the screen. refresh copies a rectangle of this size beginning - // with top left corner pminrow,pmincol onto the screen and calls doupdate(). - - int noutrefresh(); - // If a viewport is defined the pad is displayed in this window, otherwise - // this is a noop. - - int noutrefresh(int pminrow, int pmincol, - int sminrow, int smincol, - int smaxrow, int smaxcol) { - return ::pnoutrefresh(w, pminrow, pmincol, - sminrow, smincol, smaxrow, smaxcol); - } - // Does the same as refresh() but without calling doupdate(). - - virtual void setWindow(NCursesWindow& view, int v_grid = 1, int h_grid = 1); - // Add the window "view" as viewing window to the pad. - - virtual void setSubWindow(NCursesWindow& sub); - // Use the subwindow "sub" of the viewport window for the actual viewing. - // The full viewport window is usually used to provide some decorations - // like frames, titles etc. - - virtual void operator() (void); - // Perform Pad's operation -}; - -// A FramedPad is constructed always with a viewport window. This viewport -// will be framed (by a box() command) and the interior of the box is the -// viewport subwindow. On the frame we display scrollbar sliders. -class NCURSES_IMPEXP NCursesFramedPad : public NCursesPad -{ -protected: - virtual void OnOperation(int pad_req); - -public: - NCursesFramedPad(NCursesWindow& win, int nlines, int ncols, - int v_grid = 1, int h_grid = 1) - : NCursesPad(nlines, ncols) { - NCursesPad::setWindow(win, v_grid, h_grid); - NCursesPad::setSubWindow(*(new NCursesWindow(win))); - } - // Construct the FramedPad with the given Window win as viewport. - - virtual ~NCursesFramedPad() { - delete getSubWindow(); - } - - void setWindow(NCursesWindow& view, int v_grid = 1, int h_grid = 1) { - err_handler("Operation not allowed"); - } - // Disable this call; the viewport is already defined - - void setSubWindow(NCursesWindow& sub) { - err_handler("Operation not allowed"); - } - // Disable this call; the viewport subwindow is already defined - -}; - -#endif /* NCURSES_CURSESW_H_incl */ diff --git a/windows/ncurses/include/ncurses/cursslk.h b/windows/ncurses/include/ncurses/cursslk.h deleted file mode 100644 index 4c64f402e..000000000 --- a/windows/ncurses/include/ncurses/cursslk.h +++ /dev/null @@ -1,238 +0,0 @@ -// * this is for making emacs happy: -*-Mode: C++;-*- -/**************************************************************************** - * Copyright (c) 1998-2003,2005 Free Software Foundation, Inc. * - * * - * Permission is hereby granted, free of charge, to any person obtaining a * - * copy of this software and associated documentation files (the * - * "Software"), to deal in the Software without restriction, including * - * without limitation the rights to use, copy, modify, merge, publish, * - * distribute, distribute with modifications, sublicense, and/or sell * - * copies of the Software, and to permit persons to whom the Software is * - * furnished to do so, subject to the following conditions: * - * * - * The above copyright notice and this permission notice shall be included * - * in all copies or substantial portions of the Software. * - * * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * - * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * - * THE USE OR OTHER DEALINGS IN THE SOFTWARE. * - * * - * Except as contained in this notice, the name(s) of the above copyright * - * holders shall not be used in advertising or otherwise to promote the * - * sale, use or other dealings in this Software without prior written * - * authorization. * - ****************************************************************************/ - -/**************************************************************************** - * Author: Juergen Pfeifer, 1997 * - ****************************************************************************/ - -// $Id: cursslk.h,v 1.13 2005/05/28 21:58:18 tom Exp $ - -#ifndef NCURSES_CURSSLK_H_incl -#define NCURSES_CURSSLK_H_incl - -#include - -class NCURSES_IMPEXP Soft_Label_Key_Set { -public: - // This inner class represents the attributes of a Soft Label Key (SLK) - class NCURSES_IMPEXP Soft_Label_Key { - friend class Soft_Label_Key_Set; - public: - typedef enum { Left=0, Center=1, Right=2 } Justification; - - private: - char *label; // The Text of the Label - Justification format; // The Justification - int num; // The number of the Label - - Soft_Label_Key() : label(NULL), format(Left), num(-1) { - } - - virtual ~Soft_Label_Key() { - delete[] label; - }; - - public: - // Set the text of the Label - Soft_Label_Key& operator=(char *text); - - // Set the Justification of the Label - Soft_Label_Key& operator=(Justification just) { - format = just; - return *this; - } - - // Retrieve the text of the label - inline char* operator()(void) const { - return label; - } - - Soft_Label_Key& operator=(const Soft_Label_Key& rhs) - { - if (this != &rhs) { - *this = rhs; - } - return *this; - } - - Soft_Label_Key(const Soft_Label_Key& rhs) - : label(NULL), - format(rhs.format), - num(rhs.num) - { - *this = rhs.label; - } - }; - -public: - typedef enum { - None = -1, - Three_Two_Three = 0, - Four_Four = 1, - PC_Style = 2, - PC_Style_With_Index = 3 - } Label_Layout; - -private: - static long NCURSES_IMPEXP count; // Number of Key Sets - static Label_Layout NCURSES_IMPEXP format; // Layout of the Key Sets - static int NCURSES_IMPEXP num_labels; // Number Of Labels in Key Sets - bool NCURSES_IMPEXP b_attrInit; // Are attributes initialized - - Soft_Label_Key *slk_array; // The array of SLK's - - // Init the Key Set - void init(); - - // Activate or Deactivate Label# i, Label counting starts with 1! - void activate_label(int i, bool bf=TRUE); - - // Activate of Deactivate all Labels - void activate_labels(bool bf); - -protected: - inline void Error (const char* msg) const THROWS(NCursesException) { - THROW(new NCursesException (msg)); - } - - // Remove SLK's from screen - void clear() { - if (ERR==::slk_clear()) - Error("slk_clear"); - } - - // Restore them - void restore() { - if (ERR==::slk_restore()) - Error("slk_restore"); - } - -public: - - // Construct a Key Set, use the most comfortable layout as default. - // You must create a Soft_Label_Key_Set before you create any object of - // the NCursesWindow, NCursesPanel or derived classes. (Actually before - // ::initscr() is called). - Soft_Label_Key_Set(Label_Layout fmt); - - // This constructor assumes, that you already constructed a Key Set - // with a layout by the constructor above. This layout will be reused. - NCURSES_IMPEXP Soft_Label_Key_Set(); - - Soft_Label_Key_Set& operator=(const Soft_Label_Key_Set& rhs) - { - if (this != &rhs) { - *this = rhs; - init(); // allocate a new slk_array[] - } - return *this; - } - - Soft_Label_Key_Set(const Soft_Label_Key_Set& rhs) - : b_attrInit(rhs.b_attrInit), - slk_array(NULL) - { - init(); // allocate a new slk_array[] - } - - virtual ~Soft_Label_Key_Set(); - - // Get Label# i. Label counting starts with 1! - NCURSES_IMPEXP Soft_Label_Key& operator[](int i); - - // Retrieve number of Labels - inline int labels() const { return num_labels; } - - // Refresh the SLK portion of the screen - inline void refresh() { - if (ERR==::slk_refresh()) - Error("slk_refresh"); - } - - // Mark the SLK portion of the screen for refresh, defer actual refresh - // until next update call. - inline void noutrefresh() { - if (ERR==::slk_noutrefresh()) - Error("slk_noutrefresh"); - } - - // Mark the whole SLK portion of the screen as modified - inline void touch() { - if (ERR==::slk_touch()) - Error("slk_touch"); - } - - // Activate Label# i - inline void show(int i) { - activate_label(i,FALSE); - activate_label(i,TRUE); - } - - // Hide Label# i - inline void hide(int i) { - activate_label(i,FALSE); - } - - // Show all Labels - inline void show() { - activate_labels(FALSE); - activate_labels(TRUE); - } - - // Hide all Labels - inline void hide() { - activate_labels(FALSE); - } - - inline void attron(attr_t attrs) { - if (ERR==::slk_attron(attrs)) - Error("slk_attron"); - } - - inline void attroff(attr_t attrs) { - if (ERR==::slk_attroff(attrs)) - Error("slk_attroff"); - } - - inline void attrset(attr_t attrs) { - if (ERR==::slk_attrset(attrs)) - Error("slk_attrset"); - } - - inline void color(short color_pair_number) { - if (ERR==::slk_color(color_pair_number)) - Error("slk_color"); - } - - inline attr_t attr() const { - return ::slk_attr(); - } -}; - -#endif /* NCURSES_CURSSLK_H_incl */ diff --git a/windows/ncurses/include/ncurses/eti.h b/windows/ncurses/include/ncurses/eti.h deleted file mode 100644 index baa6190d8..000000000 --- a/windows/ncurses/include/ncurses/eti.h +++ /dev/null @@ -1,54 +0,0 @@ -/**************************************************************************** - * Copyright (c) 1998-2002,2003 Free Software Foundation, Inc. * - * * - * Permission is hereby granted, free of charge, to any person obtaining a * - * copy of this software and associated documentation files (the * - * "Software"), to deal in the Software without restriction, including * - * without limitation the rights to use, copy, modify, merge, publish, * - * distribute, distribute with modifications, sublicense, and/or sell * - * copies of the Software, and to permit persons to whom the Software is * - * furnished to do so, subject to the following conditions: * - * * - * The above copyright notice and this permission notice shall be included * - * in all copies or substantial portions of the Software. * - * * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * - * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * - * THE USE OR OTHER DEALINGS IN THE SOFTWARE. * - * * - * Except as contained in this notice, the name(s) of the above copyright * - * holders shall not be used in advertising or otherwise to promote the * - * sale, use or other dealings in this Software without prior written * - * authorization. * - ****************************************************************************/ - -/**************************************************************************** - * Author: Juergen Pfeifer, 1995,1997 * - ****************************************************************************/ - -/* $Id: eti.h,v 1.8 2003/10/25 15:24:29 tom Exp $ */ - -#ifndef NCURSES_ETI_H_incl -#define NCURSES_ETI_H_incl 1 - -#define E_OK (0) -#define E_SYSTEM_ERROR (-1) -#define E_BAD_ARGUMENT (-2) -#define E_POSTED (-3) -#define E_CONNECTED (-4) -#define E_BAD_STATE (-5) -#define E_NO_ROOM (-6) -#define E_NOT_POSTED (-7) -#define E_UNKNOWN_COMMAND (-8) -#define E_NO_MATCH (-9) -#define E_NOT_SELECTABLE (-10) -#define E_NOT_CONNECTED (-11) -#define E_REQUEST_DENIED (-12) -#define E_INVALID_FIELD (-13) -#define E_CURRENT (-14) - -#endif diff --git a/windows/ncurses/include/ncurses/etip.h b/windows/ncurses/include/ncurses/etip.h deleted file mode 100644 index 82e9409cf..000000000 --- a/windows/ncurses/include/ncurses/etip.h +++ /dev/null @@ -1,378 +0,0 @@ -// * This makes emacs happy -*-Mode: C++;-*- -/**************************************************************************** - * Copyright (c) 1998-2007,2008 Free Software Foundation, Inc. * - * * - * Permission is hereby granted, free of charge, to any person obtaining a * - * copy of this software and associated documentation files (the * - * "Software"), to deal in the Software without restriction, including * - * without limitation the rights to use, copy, modify, merge, publish, * - * distribute, distribute with modifications, sublicense, and/or sell * - * copies of the Software, and to permit persons to whom the Software is * - * furnished to do so, subject to the following conditions: * - * * - * The above copyright notice and this permission notice shall be included * - * in all copies or substantial portions of the Software. * - * * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * - * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * - * THE USE OR OTHER DEALINGS IN THE SOFTWARE. * - * * - * Except as contained in this notice, the name(s) of the above copyright * - * holders shall not be used in advertising or otherwise to promote the * - * sale, use or other dealings in this Software without prior written * - * authorization. * - ****************************************************************************/ - -/**************************************************************************** - * Author: Juergen Pfeifer, 1997 * - ****************************************************************************/ - -// $Id: etip.h.in,v 1.37 2008/08/30 19:27:32 tom Exp $ - -#ifndef NCURSES_ETIP_H_incl -#define NCURSES_ETIP_H_incl 1 - -// These are substituted at configure/build time -#ifndef HAVE_BUILTIN_H -#define HAVE_BUILTIN_H 0 -#endif - -#ifndef HAVE_GXX_BUILTIN_H -#define HAVE_GXX_BUILTIN_H 0 -#endif - -#ifndef HAVE_GPP_BUILTIN_H -#define HAVE_GPP_BUILTIN_H 0 -#endif - -#ifndef HAVE_IOSTREAM -#define HAVE_IOSTREAM 1 -#endif - -#ifndef HAVE_TYPEINFO -#define HAVE_TYPEINFO 1 -#endif - -#ifndef HAVE_VALUES_H -#define HAVE_VALUES_H 0 -#endif - -#ifndef ETIP_NEEDS_MATH_H -#define ETIP_NEEDS_MATH_H 0 -#endif - -#ifndef ETIP_NEEDS_MATH_EXCEPTION -#define ETIP_NEEDS_MATH_EXCEPTION 0 -#endif - -#ifndef CPP_HAS_PARAM_INIT -#define CPP_HAS_PARAM_INIT 0 -#endif - -#ifndef CPP_HAS_STATIC_CAST -#define CPP_HAS_STATIC_CAST 1 -#endif - -#ifndef IOSTREAM_NAMESPACE -#define IOSTREAM_NAMESPACE 1 -#endif - -#ifdef __GNUG__ -# if ((__GNUG__ <= 2) && (__GNUC_MINOR__ < 8)) -# if HAVE_TYPEINFO -# include -# endif -# endif -#endif - -#if defined(__GNUG__) -# if HAVE_BUILTIN_H || HAVE_GXX_BUILTIN_H || HAVE_GPP_BUILTIN_H -# if ETIP_NEEDS_MATH_H -# if ETIP_NEEDS_MATH_EXCEPTION -# undef exception -# define exception math_exception -# endif -# include -# endif -# undef exception -# define exception builtin_exception -# if HAVE_GPP_BUILTIN_H -# include -# elif HAVE_GXX_BUILTIN_H -# include -# else -# include -# endif -# undef exception -# endif -#elif defined (__SUNPRO_CC) -# include -#endif - -#include - -extern "C" { -#if HAVE_VALUES_H -# include -#endif - -#include -#include -#include -} - -// Language features -#if CPP_HAS_PARAM_INIT -#define NCURSES_PARAM_INIT(value) = value -#else -#define NCURSES_PARAM_INIT(value) /*nothing*/ -#endif - -#if CPP_HAS_STATIC_CAST -#define STATIC_CAST(s) static_cast -#else -#define STATIC_CAST(s) (s) -#endif - -// Forward Declarations -class NCURSES_IMPEXP NCursesPanel; -class NCURSES_IMPEXP NCursesMenu; -class NCURSES_IMPEXP NCursesForm; - -class NCURSES_IMPEXP NCursesException -{ -public: - const char *message; - int errorno; - - NCursesException (const char* msg, int err) - : message(msg), errorno (err) - {}; - - NCursesException (const char* msg) - : message(msg), errorno (E_SYSTEM_ERROR) - {}; - - NCursesException& operator=(const NCursesException& rhs) - { - errorno = rhs.errorno; - return *this; - } - - NCursesException(const NCursesException& rhs) - : message(rhs.message), errorno(rhs.errorno) - { - } - - virtual const char *classname() const { - return "NCursesWindow"; - } - - virtual ~NCursesException() - { - } -}; - -class NCURSES_IMPEXP NCursesPanelException : public NCursesException -{ -public: - const NCursesPanel* p; - - NCursesPanelException (const char *msg, int err) : - NCursesException (msg, err), - p (NULL) - {}; - - NCursesPanelException (const NCursesPanel* panel, - const char *msg, - int err) : - NCursesException (msg, err), - p (panel) - {}; - - NCursesPanelException (int err) : - NCursesException ("panel library error", err), - p (NULL) - {}; - - NCursesPanelException (const NCursesPanel* panel, - int err) : - NCursesException ("panel library error", err), - p (panel) - {}; - - NCursesPanelException& operator=(const NCursesPanelException& rhs) - { - if (this != &rhs) { - NCursesException::operator=(rhs); - p = rhs.p; - } - return *this; - } - - NCursesPanelException(const NCursesPanelException& rhs) - : NCursesException(rhs), p(rhs.p) - { - } - - virtual const char *classname() const { - return "NCursesPanel"; - } - - virtual ~NCursesPanelException() - { - } -}; - -class NCURSES_IMPEXP NCursesMenuException : public NCursesException -{ -public: - const NCursesMenu* m; - - NCursesMenuException (const char *msg, int err) : - NCursesException (msg, err), - m (NULL) - {}; - - NCursesMenuException (const NCursesMenu* menu, - const char *msg, - int err) : - NCursesException (msg, err), - m (menu) - {}; - - NCursesMenuException (int err) : - NCursesException ("menu library error", err), - m (NULL) - {}; - - NCursesMenuException (const NCursesMenu* menu, - int err) : - NCursesException ("menu library error", err), - m (menu) - {}; - - NCursesMenuException& operator=(const NCursesMenuException& rhs) - { - if (this != &rhs) { - NCursesException::operator=(rhs); - m = rhs.m; - } - return *this; - } - - NCursesMenuException(const NCursesMenuException& rhs) - : NCursesException(rhs), m(rhs.m) - { - } - - virtual const char *classname() const { - return "NCursesMenu"; - } - - virtual ~NCursesMenuException() - { - } -}; - -class NCURSES_IMPEXP NCursesFormException : public NCursesException -{ -public: - const NCursesForm* f; - - NCursesFormException (const char *msg, int err) : - NCursesException (msg, err), - f (NULL) - {}; - - NCursesFormException (const NCursesForm* form, - const char *msg, - int err) : - NCursesException (msg, err), - f (form) - {}; - - NCursesFormException (int err) : - NCursesException ("form library error", err), - f (NULL) - {}; - - NCursesFormException (const NCursesForm* form, - int err) : - NCursesException ("form library error", err), - f (form) - {}; - - NCursesFormException& operator=(const NCursesFormException& rhs) - { - if (this != &rhs) { - NCursesException::operator=(rhs); - f = rhs.f; - } - return *this; - } - - NCursesFormException(const NCursesFormException& rhs) - : NCursesException(rhs), f(rhs.f) - { - } - - virtual const char *classname() const { - return "NCursesForm"; - } - - virtual ~NCursesFormException() - { - } -}; - -#if !((defined(__GNUG__) && defined(__EXCEPTIONS)) || defined(__SUNPRO_CC)) -# if HAVE_IOSTREAM -# include -# if IOSTREAM_NAMESPACE -using std::cerr; -using std::endl; -# endif -# else -# include -# endif - extern "C" void exit(int); -#endif - -inline void THROW(const NCursesException *e) { -#if defined(__GNUG__) && defined(__EXCEPTIONS) -# if ((__GNUG__ <= 2) && (__GNUC_MINOR__ < 8)) - (*lib_error_handler)(e ? e->classname() : "", e ? e->message : ""); -#else -#define CPP_HAS_TRY_CATCH 1 -#endif -#elif defined(__SUNPRO_CC) -# if !defined(__SUNPRO_CC_COMPAT) || (__SUNPRO_CC_COMPAT < 5) - genericerror(1, ((e != 0) ? (char *)(e->message) : "")); -#else -#define CPP_HAS_TRY_CATCH 1 -#endif -#else - if (e) - cerr << e->message << endl; - exit(0); -#endif - -#ifndef CPP_HAS_TRY_CATCH -#define CPP_HAS_TRY_CATCH 0 -#define NCURSES_CPP_TRY /* nothing */ -#define NCURSES_CPP_CATCH(e) if (false) -#define THROWS(s) /* nothing */ -#elif CPP_HAS_TRY_CATCH - throw *e; -#define NCURSES_CPP_TRY try -#define NCURSES_CPP_CATCH(e) catch(e) -#define THROWS(s) throw(s) -#endif -} - -#endif /* NCURSES_ETIP_H_incl */ diff --git a/windows/ncurses/include/ncurses/form.h b/windows/ncurses/include/ncurses/form.h deleted file mode 100644 index 80886ac3a..000000000 --- a/windows/ncurses/include/ncurses/form.h +++ /dev/null @@ -1,422 +0,0 @@ -/**************************************************************************** - * Copyright (c) 1998-2004,2009 Free Software Foundation, Inc. * - * * - * Permission is hereby granted, free of charge, to any person obtaining a * - * copy of this software and associated documentation files (the * - * "Software"), to deal in the Software without restriction, including * - * without limitation the rights to use, copy, modify, merge, publish, * - * distribute, distribute with modifications, sublicense, and/or sell * - * copies of the Software, and to permit persons to whom the Software is * - * furnished to do so, subject to the following conditions: * - * * - * The above copyright notice and this permission notice shall be included * - * in all copies or substantial portions of the Software. * - * * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * - * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * - * THE USE OR OTHER DEALINGS IN THE SOFTWARE. * - * * - * Except as contained in this notice, the name(s) of the above copyright * - * holders shall not be used in advertising or otherwise to promote the * - * sale, use or other dealings in this Software without prior written * - * authorization. * - ****************************************************************************/ - -/**************************************************************************** - * Author: Juergen Pfeifer, 1995,1997 * - ****************************************************************************/ - -/* $Id: form.h,v 0.21 2009/11/07 19:31:11 tom Exp $ */ - -#ifndef FORM_H -#define FORM_H - -#include -#include - -#ifdef __cplusplus - extern "C" { -#endif - -#ifndef FORM_PRIV_H -typedef void *FIELD_CELL; -#endif - -#ifndef NCURSES_FIELD_INTERNALS -#define NCURSES_FIELD_INTERNALS /* nothing */ -#endif - -typedef int Form_Options; -typedef int Field_Options; - - /********** - * _PAGE * - **********/ - -typedef struct { - short pmin; /* index of first field on page */ - short pmax; /* index of last field on page */ - short smin; /* index of top leftmost field on page */ - short smax; /* index of bottom rightmost field on page */ -} _PAGE; - - /********** - * FIELD * - **********/ - -typedef struct fieldnode { - unsigned short status; /* flags */ - short rows; /* size in rows */ - short cols; /* size in cols */ - short frow; /* first row */ - short fcol; /* first col */ - int drows; /* dynamic rows */ - int dcols; /* dynamic cols */ - int maxgrow; /* maximum field growth */ - int nrow; /* off-screen rows */ - short nbuf; /* additional buffers */ - short just; /* justification */ - short page; /* page on form */ - short index; /* into form -> field */ - int pad; /* pad character */ - chtype fore; /* foreground attribute */ - chtype back; /* background attribute */ - Field_Options opts; /* options */ - struct fieldnode * snext; /* sorted order pointer */ - struct fieldnode * sprev; /* sorted order pointer */ - struct fieldnode * link; /* linked field chain */ - struct formnode * form; /* containing form */ - struct typenode * type; /* field type */ - void * arg; /* argument for type */ - FIELD_CELL * buf; /* field buffers */ - void * usrptr; /* user pointer */ - /* - * The wide-character configuration requires extra information. Because - * there are existing applications that manipulate the members of FIELD - * directly, we cannot make the struct opaque. Offsets of members up to - * this point are the same in the narrow- and wide-character configuration. - * But note that the type of buf depends on the configuration, and is made - * opaque for that reason. - */ - NCURSES_FIELD_INTERNALS -} FIELD; - - - /********* - * FORM * - *********/ - -typedef struct formnode { - unsigned short status; /* flags */ - short rows; /* size in rows */ - short cols; /* size in cols */ - int currow; /* current row in field window */ - int curcol; /* current col in field window */ - int toprow; /* in scrollable field window */ - int begincol; /* in horiz. scrollable field */ - short maxfield; /* number of fields */ - short maxpage; /* number of pages */ - short curpage; /* index into page */ - Form_Options opts; /* options */ - WINDOW * win; /* window */ - WINDOW * sub; /* subwindow */ - WINDOW * w; /* window for current field */ - FIELD ** field; /* field [maxfield] */ - FIELD * current; /* current field */ - _PAGE * page; /* page [maxpage] */ - void * usrptr; /* user pointer */ - - void (*forminit)(struct formnode *); - void (*formterm)(struct formnode *); - void (*fieldinit)(struct formnode *); - void (*fieldterm)(struct formnode *); - -} FORM; - - - /************** - * FIELDTYPE * - **************/ - -typedef struct typenode { - unsigned short status; /* flags */ - long ref; /* reference count */ - struct typenode * left; /* ptr to operand for | */ - struct typenode * right; /* ptr to operand for | */ - - void* (*makearg)(va_list *); /* make fieldtype arg */ - void* (*copyarg)(const void *); /* copy fieldtype arg */ - void (*freearg)(void *); /* free fieldtype arg */ - -#if NCURSES_INTEROP_FUNCS - union { - bool (*ofcheck)(FIELD *,const void *); /* field validation */ - bool (*gfcheck)(FORM*,FIELD *,const void*); /* generic field validation */ - } fieldcheck; - union { - bool (*occheck)(int,const void *); /* character validation */ - bool (*gccheck)(int,FORM*, - FIELD*,const void*); /* generic char validation */ - } charcheck; - union { - bool (*onext)(FIELD *,const void *); /* enumerate next value */ - bool (*gnext)(FORM*,FIELD*,const void*); /* generic enumerate next */ - } enum_next; - union { - bool (*oprev)(FIELD *,const void *); /* enumerate prev value */ - bool (*gprev)(FORM*,FIELD*,const void*); /* generic enumerate prev */ - } enum_prev; - void* (*genericarg)(void*); /* Alternate Arg method */ -#else - bool (*fcheck)(FIELD *,const void *); /* field validation */ - bool (*ccheck)(int,const void *); /* character validation */ - - bool (*next)(FIELD *,const void *); /* enumerate next value */ - bool (*prev)(FIELD *,const void *); /* enumerate prev value */ -#endif -} FIELDTYPE; - -typedef void (*Form_Hook)(FORM *); - - /*************************** - * miscellaneous #defines * - ***************************/ - -/* field justification */ -#define NO_JUSTIFICATION (0) -#define JUSTIFY_LEFT (1) -#define JUSTIFY_CENTER (2) -#define JUSTIFY_RIGHT (3) - -/* field options */ -#define O_VISIBLE (0x0001U) -#define O_ACTIVE (0x0002U) -#define O_PUBLIC (0x0004U) -#define O_EDIT (0x0008U) -#define O_WRAP (0x0010U) -#define O_BLANK (0x0020U) -#define O_AUTOSKIP (0x0040U) -#define O_NULLOK (0x0080U) -#define O_PASSOK (0x0100U) -#define O_STATIC (0x0200U) - -/* form options */ -#define O_NL_OVERLOAD (0x0001U) -#define O_BS_OVERLOAD (0x0002U) - -/* form driver commands */ -#define REQ_NEXT_PAGE (KEY_MAX + 1) /* move to next page */ -#define REQ_PREV_PAGE (KEY_MAX + 2) /* move to previous page */ -#define REQ_FIRST_PAGE (KEY_MAX + 3) /* move to first page */ -#define REQ_LAST_PAGE (KEY_MAX + 4) /* move to last page */ - -#define REQ_NEXT_FIELD (KEY_MAX + 5) /* move to next field */ -#define REQ_PREV_FIELD (KEY_MAX + 6) /* move to previous field */ -#define REQ_FIRST_FIELD (KEY_MAX + 7) /* move to first field */ -#define REQ_LAST_FIELD (KEY_MAX + 8) /* move to last field */ -#define REQ_SNEXT_FIELD (KEY_MAX + 9) /* move to sorted next field */ -#define REQ_SPREV_FIELD (KEY_MAX + 10) /* move to sorted prev field */ -#define REQ_SFIRST_FIELD (KEY_MAX + 11) /* move to sorted first field */ -#define REQ_SLAST_FIELD (KEY_MAX + 12) /* move to sorted last field */ -#define REQ_LEFT_FIELD (KEY_MAX + 13) /* move to left to field */ -#define REQ_RIGHT_FIELD (KEY_MAX + 14) /* move to right to field */ -#define REQ_UP_FIELD (KEY_MAX + 15) /* move to up to field */ -#define REQ_DOWN_FIELD (KEY_MAX + 16) /* move to down to field */ - -#define REQ_NEXT_CHAR (KEY_MAX + 17) /* move to next char in field */ -#define REQ_PREV_CHAR (KEY_MAX + 18) /* move to prev char in field */ -#define REQ_NEXT_LINE (KEY_MAX + 19) /* move to next line in field */ -#define REQ_PREV_LINE (KEY_MAX + 20) /* move to prev line in field */ -#define REQ_NEXT_WORD (KEY_MAX + 21) /* move to next word in field */ -#define REQ_PREV_WORD (KEY_MAX + 22) /* move to prev word in field */ -#define REQ_BEG_FIELD (KEY_MAX + 23) /* move to first char in field */ -#define REQ_END_FIELD (KEY_MAX + 24) /* move after last char in fld */ -#define REQ_BEG_LINE (KEY_MAX + 25) /* move to beginning of line */ -#define REQ_END_LINE (KEY_MAX + 26) /* move after last char in line */ -#define REQ_LEFT_CHAR (KEY_MAX + 27) /* move left in field */ -#define REQ_RIGHT_CHAR (KEY_MAX + 28) /* move right in field */ -#define REQ_UP_CHAR (KEY_MAX + 29) /* move up in field */ -#define REQ_DOWN_CHAR (KEY_MAX + 30) /* move down in field */ - -#define REQ_NEW_LINE (KEY_MAX + 31) /* insert/overlay new line */ -#define REQ_INS_CHAR (KEY_MAX + 32) /* insert blank char at cursor */ -#define REQ_INS_LINE (KEY_MAX + 33) /* insert blank line at cursor */ -#define REQ_DEL_CHAR (KEY_MAX + 34) /* delete char at cursor */ -#define REQ_DEL_PREV (KEY_MAX + 35) /* delete char before cursor */ -#define REQ_DEL_LINE (KEY_MAX + 36) /* delete line at cursor */ -#define REQ_DEL_WORD (KEY_MAX + 37) /* delete word at cursor */ -#define REQ_CLR_EOL (KEY_MAX + 38) /* clear to end of line */ -#define REQ_CLR_EOF (KEY_MAX + 39) /* clear to end of field */ -#define REQ_CLR_FIELD (KEY_MAX + 40) /* clear entire field */ -#define REQ_OVL_MODE (KEY_MAX + 41) /* begin overlay mode */ -#define REQ_INS_MODE (KEY_MAX + 42) /* begin insert mode */ -#define REQ_SCR_FLINE (KEY_MAX + 43) /* scroll field forward a line */ -#define REQ_SCR_BLINE (KEY_MAX + 44) /* scroll field backward a line */ -#define REQ_SCR_FPAGE (KEY_MAX + 45) /* scroll field forward a page */ -#define REQ_SCR_BPAGE (KEY_MAX + 46) /* scroll field backward a page */ -#define REQ_SCR_FHPAGE (KEY_MAX + 47) /* scroll field forward half page */ -#define REQ_SCR_BHPAGE (KEY_MAX + 48) /* scroll field backward half page */ -#define REQ_SCR_FCHAR (KEY_MAX + 49) /* horizontal scroll char */ -#define REQ_SCR_BCHAR (KEY_MAX + 50) /* horizontal scroll char */ -#define REQ_SCR_HFLINE (KEY_MAX + 51) /* horizontal scroll line */ -#define REQ_SCR_HBLINE (KEY_MAX + 52) /* horizontal scroll line */ -#define REQ_SCR_HFHALF (KEY_MAX + 53) /* horizontal scroll half line */ -#define REQ_SCR_HBHALF (KEY_MAX + 54) /* horizontal scroll half line */ - -#define REQ_VALIDATION (KEY_MAX + 55) /* validate field */ -#define REQ_NEXT_CHOICE (KEY_MAX + 56) /* display next field choice */ -#define REQ_PREV_CHOICE (KEY_MAX + 57) /* display prev field choice */ - -#define MIN_FORM_COMMAND (KEY_MAX + 1) /* used by form_driver */ -#define MAX_FORM_COMMAND (KEY_MAX + 57) /* used by form_driver */ - -#if defined(MAX_COMMAND) -# if (MAX_FORM_COMMAND > MAX_COMMAND) -# error Something is wrong -- MAX_FORM_COMMAND is greater than MAX_COMMAND -# elif (MAX_COMMAND != (KEY_MAX + 128)) -# error Something is wrong -- MAX_COMMAND is already inconsistently defined. -# endif -#else -# define MAX_COMMAND (KEY_MAX + 128) -#endif - - /************************* - * standard field types * - *************************/ -extern NCURSES_EXPORT_VAR(FIELDTYPE *) TYPE_ALPHA; -extern NCURSES_EXPORT_VAR(FIELDTYPE *) TYPE_ALNUM; -extern NCURSES_EXPORT_VAR(FIELDTYPE *) TYPE_ENUM; -extern NCURSES_EXPORT_VAR(FIELDTYPE *) TYPE_INTEGER; -extern NCURSES_EXPORT_VAR(FIELDTYPE *) TYPE_NUMERIC; -extern NCURSES_EXPORT_VAR(FIELDTYPE *) TYPE_REGEXP; - - /************************************ - * built-in additional field types * - * They are not defined in SVr4 * - ************************************/ -extern NCURSES_EXPORT_VAR(FIELDTYPE *) TYPE_IPV4; /* Internet IP Version 4 address */ - - /*********************** - * FIELDTYPE routines * - ***********************/ -extern NCURSES_EXPORT(FIELDTYPE *) new_fieldtype ( - bool (* const field_check)(FIELD *,const void *), - bool (* const char_check)(int,const void *)); -extern NCURSES_EXPORT(FIELDTYPE *) link_fieldtype( - FIELDTYPE *, FIELDTYPE *); - -extern NCURSES_EXPORT(int) free_fieldtype (FIELDTYPE *); -extern NCURSES_EXPORT(int) set_fieldtype_arg (FIELDTYPE *, - void * (* const make_arg)(va_list *), - void * (* const copy_arg)(const void *), - void (* const free_arg)(void *)); -extern NCURSES_EXPORT(int) set_fieldtype_choice (FIELDTYPE *, - bool (* const next_choice)(FIELD *,const void *), - bool (* const prev_choice)(FIELD *,const void *)); - - /******************* - * FIELD routines * - *******************/ -extern NCURSES_EXPORT(FIELD *) new_field (int,int,int,int,int,int); -extern NCURSES_EXPORT(FIELD *) dup_field (FIELD *,int,int); -extern NCURSES_EXPORT(FIELD *) link_field (FIELD *,int,int); - -extern NCURSES_EXPORT(int) free_field (FIELD *); -extern NCURSES_EXPORT(int) field_info (const FIELD *,int *,int *,int *,int *,int *,int *); -extern NCURSES_EXPORT(int) dynamic_field_info (const FIELD *,int *,int *,int *); -extern NCURSES_EXPORT(int) set_max_field ( FIELD *,int); -extern NCURSES_EXPORT(int) move_field (FIELD *,int,int); -extern NCURSES_EXPORT(int) set_field_type (FIELD *,FIELDTYPE *,...); -extern NCURSES_EXPORT(int) set_new_page (FIELD *,bool); -extern NCURSES_EXPORT(int) set_field_just (FIELD *,int); -extern NCURSES_EXPORT(int) field_just (const FIELD *); -extern NCURSES_EXPORT(int) set_field_fore (FIELD *,chtype); -extern NCURSES_EXPORT(int) set_field_back (FIELD *,chtype); -extern NCURSES_EXPORT(int) set_field_pad (FIELD *,int); -extern NCURSES_EXPORT(int) field_pad (const FIELD *); -extern NCURSES_EXPORT(int) set_field_buffer (FIELD *,int,const char *); -extern NCURSES_EXPORT(int) set_field_status (FIELD *,bool); -extern NCURSES_EXPORT(int) set_field_userptr (FIELD *, void *); -extern NCURSES_EXPORT(int) set_field_opts (FIELD *,Field_Options); -extern NCURSES_EXPORT(int) field_opts_on (FIELD *,Field_Options); -extern NCURSES_EXPORT(int) field_opts_off (FIELD *,Field_Options); - -extern NCURSES_EXPORT(chtype) field_fore (const FIELD *); -extern NCURSES_EXPORT(chtype) field_back (const FIELD *); - -extern NCURSES_EXPORT(bool) new_page (const FIELD *); -extern NCURSES_EXPORT(bool) field_status (const FIELD *); - -extern NCURSES_EXPORT(void *) field_arg (const FIELD *); - -extern NCURSES_EXPORT(void *) field_userptr (const FIELD *); - -extern NCURSES_EXPORT(FIELDTYPE *) field_type (const FIELD *); - -extern NCURSES_EXPORT(char *) field_buffer (const FIELD *,int); - -extern NCURSES_EXPORT(Field_Options) field_opts (const FIELD *); - - /****************** - * FORM routines * - ******************/ - -extern NCURSES_EXPORT(FORM *) new_form (FIELD **); - -extern NCURSES_EXPORT(FIELD **) form_fields (const FORM *); -extern NCURSES_EXPORT(FIELD *) current_field (const FORM *); - -extern NCURSES_EXPORT(WINDOW *) form_win (const FORM *); -extern NCURSES_EXPORT(WINDOW *) form_sub (const FORM *); - -extern NCURSES_EXPORT(Form_Hook) form_init (const FORM *); -extern NCURSES_EXPORT(Form_Hook) form_term (const FORM *); -extern NCURSES_EXPORT(Form_Hook) field_init (const FORM *); -extern NCURSES_EXPORT(Form_Hook) field_term (const FORM *); - -extern NCURSES_EXPORT(int) free_form (FORM *); -extern NCURSES_EXPORT(int) set_form_fields (FORM *,FIELD **); -extern NCURSES_EXPORT(int) field_count (const FORM *); -extern NCURSES_EXPORT(int) set_form_win (FORM *,WINDOW *); -extern NCURSES_EXPORT(int) set_form_sub (FORM *,WINDOW *); -extern NCURSES_EXPORT(int) set_current_field (FORM *,FIELD *); -extern NCURSES_EXPORT(int) field_index (const FIELD *); -extern NCURSES_EXPORT(int) set_form_page (FORM *,int); -extern NCURSES_EXPORT(int) form_page (const FORM *); -extern NCURSES_EXPORT(int) scale_form (const FORM *,int *,int *); -extern NCURSES_EXPORT(int) set_form_init (FORM *,Form_Hook); -extern NCURSES_EXPORT(int) set_form_term (FORM *,Form_Hook); -extern NCURSES_EXPORT(int) set_field_init (FORM *,Form_Hook); -extern NCURSES_EXPORT(int) set_field_term (FORM *,Form_Hook); -extern NCURSES_EXPORT(int) post_form (FORM *); -extern NCURSES_EXPORT(int) unpost_form (FORM *); -extern NCURSES_EXPORT(int) pos_form_cursor (FORM *); -extern NCURSES_EXPORT(int) form_driver (FORM *,int); -extern NCURSES_EXPORT(int) set_form_userptr (FORM *,void *); -extern NCURSES_EXPORT(int) set_form_opts (FORM *,Form_Options); -extern NCURSES_EXPORT(int) form_opts_on (FORM *,Form_Options); -extern NCURSES_EXPORT(int) form_opts_off (FORM *,Form_Options); -extern NCURSES_EXPORT(int) form_request_by_name (const char *); - -extern NCURSES_EXPORT(const char *) form_request_name (int); - -extern NCURSES_EXPORT(void *) form_userptr (const FORM *); - -extern NCURSES_EXPORT(Form_Options) form_opts (const FORM *); - -extern NCURSES_EXPORT(bool) data_ahead (const FORM *); -extern NCURSES_EXPORT(bool) data_behind (const FORM *); - -#if NCURSES_SP_FUNCS -extern NCURSES_EXPORT(FORM *) NCURSES_SP_NAME(new_form) (SCREEN*, FIELD **); -#endif - -#ifdef __cplusplus - } -#endif - -#endif /* FORM_H */ diff --git a/windows/ncurses/include/ncurses/menu.h b/windows/ncurses/include/ncurses/menu.h deleted file mode 100644 index 48eaa3f1d..000000000 --- a/windows/ncurses/include/ncurses/menu.h +++ /dev/null @@ -1,260 +0,0 @@ -/**************************************************************************** - * Copyright (c) 1998-2007,2009 Free Software Foundation, Inc. * - * * - * Permission is hereby granted, free of charge, to any person obtaining a * - * copy of this software and associated documentation files (the * - * "Software"), to deal in the Software without restriction, including * - * without limitation the rights to use, copy, modify, merge, publish, * - * distribute, distribute with modifications, sublicense, and/or sell * - * copies of the Software, and to permit persons to whom the Software is * - * furnished to do so, subject to the following conditions: * - * * - * The above copyright notice and this permission notice shall be included * - * in all copies or substantial portions of the Software. * - * * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * - * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * - * THE USE OR OTHER DEALINGS IN THE SOFTWARE. * - * * - * Except as contained in this notice, the name(s) of the above copyright * - * holders shall not be used in advertising or otherwise to promote the * - * sale, use or other dealings in this Software without prior written * - * authorization. * - ****************************************************************************/ - -/**************************************************************************** - * Author: Juergen Pfeifer, 1995,1997 * - ****************************************************************************/ - -/* $Id: menu.h,v 1.20 2009/04/05 00:28:07 tom Exp $ */ - -#ifndef ETI_MENU -#define ETI_MENU - -#ifdef AMIGA -#define TEXT TEXT_ncurses -#endif - -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -typedef int Menu_Options; -typedef int Item_Options; - -/* Menu options: */ -#define O_ONEVALUE (0x01) -#define O_SHOWDESC (0x02) -#define O_ROWMAJOR (0x04) -#define O_IGNORECASE (0x08) -#define O_SHOWMATCH (0x10) -#define O_NONCYCLIC (0x20) - -/* Item options: */ -#define O_SELECTABLE (0x01) - -typedef struct -{ - const char* str; - unsigned short length; -} TEXT; - -typedef struct tagITEM -{ - TEXT name; /* name of menu item */ - TEXT description; /* description of item, optional in display */ - struct tagMENU *imenu; /* Pointer to parent menu */ - void *userptr; /* Pointer to user defined per item data */ - Item_Options opt; /* Item options */ - short index; /* Item number if connected to a menu */ - short y; /* y and x location of item in menu */ - short x; - bool value; /* Selection value */ - - struct tagITEM *left; /* neighbor items */ - struct tagITEM *right; - struct tagITEM *up; - struct tagITEM *down; - -} ITEM; - -typedef void (*Menu_Hook)(struct tagMENU *); - -typedef struct tagMENU -{ - short height; /* Nr. of chars high */ - short width; /* Nr. of chars wide */ - short rows; /* Nr. of items high */ - short cols; /* Nr. of items wide */ - short frows; /* Nr. of formatted items high */ - short fcols; /* Nr. of formatted items wide */ - short arows; /* Nr. of items high (actual) */ - short namelen; /* Max. name length */ - short desclen; /* Max. description length */ - short marklen; /* Length of mark, if any */ - short itemlen; /* Length of one item */ - short spc_desc; /* Spacing for descriptor */ - short spc_cols; /* Spacing for columns */ - short spc_rows; /* Spacing for rows */ - char *pattern; /* Buffer to store match chars */ - short pindex; /* Index into pattern buffer */ - WINDOW *win; /* Window containing menu */ - WINDOW *sub; /* Subwindow for menu display */ - WINDOW *userwin; /* User's window */ - WINDOW *usersub; /* User's subwindow */ - ITEM **items; /* array of items */ - short nitems; /* Nr. of items in menu */ - ITEM *curitem; /* Current item */ - short toprow; /* Top row of menu */ - chtype fore; /* Selection attribute */ - chtype back; /* Nonselection attribute */ - chtype grey; /* Inactive attribute */ - unsigned char pad; /* Pad character */ - - Menu_Hook menuinit; /* User hooks */ - Menu_Hook menuterm; - Menu_Hook iteminit; - Menu_Hook itemterm; - - void *userptr; /* Pointer to menus user data */ - char *mark; /* Pointer to marker string */ - - Menu_Options opt; /* Menu options */ - unsigned short status; /* Internal state of menu */ - -} MENU; - - -/* Define keys */ - -#define REQ_LEFT_ITEM (KEY_MAX + 1) -#define REQ_RIGHT_ITEM (KEY_MAX + 2) -#define REQ_UP_ITEM (KEY_MAX + 3) -#define REQ_DOWN_ITEM (KEY_MAX + 4) -#define REQ_SCR_ULINE (KEY_MAX + 5) -#define REQ_SCR_DLINE (KEY_MAX + 6) -#define REQ_SCR_DPAGE (KEY_MAX + 7) -#define REQ_SCR_UPAGE (KEY_MAX + 8) -#define REQ_FIRST_ITEM (KEY_MAX + 9) -#define REQ_LAST_ITEM (KEY_MAX + 10) -#define REQ_NEXT_ITEM (KEY_MAX + 11) -#define REQ_PREV_ITEM (KEY_MAX + 12) -#define REQ_TOGGLE_ITEM (KEY_MAX + 13) -#define REQ_CLEAR_PATTERN (KEY_MAX + 14) -#define REQ_BACK_PATTERN (KEY_MAX + 15) -#define REQ_NEXT_MATCH (KEY_MAX + 16) -#define REQ_PREV_MATCH (KEY_MAX + 17) - -#define MIN_MENU_COMMAND (KEY_MAX + 1) -#define MAX_MENU_COMMAND (KEY_MAX + 17) - -/* - * Some AT&T code expects MAX_COMMAND to be out-of-band not - * just for menu commands but for forms ones as well. - */ -#if defined(MAX_COMMAND) -# if (MAX_MENU_COMMAND > MAX_COMMAND) -# error Something is wrong -- MAX_MENU_COMMAND is greater than MAX_COMMAND -# elif (MAX_COMMAND != (KEY_MAX + 128)) -# error Something is wrong -- MAX_COMMAND is already inconsistently defined. -# endif -#else -# define MAX_COMMAND (KEY_MAX + 128) -#endif - - -/* --------- prototypes for libmenu functions ----------------------------- */ - -extern NCURSES_EXPORT(ITEM **) menu_items (const MENU *); -extern NCURSES_EXPORT(ITEM *) current_item (const MENU *); -extern NCURSES_EXPORT(ITEM *) new_item (const char *,const char *); - -extern NCURSES_EXPORT(MENU *) new_menu (ITEM **); - -extern NCURSES_EXPORT(Item_Options) item_opts (const ITEM *); -extern NCURSES_EXPORT(Menu_Options) menu_opts (const MENU *); - -extern NCURSES_EXPORT(Menu_Hook) item_init (const MENU *); -extern NCURSES_EXPORT(Menu_Hook) item_term (const MENU *); -extern NCURSES_EXPORT(Menu_Hook) menu_init (const MENU *); -extern NCURSES_EXPORT(Menu_Hook) menu_term (const MENU *); - -extern NCURSES_EXPORT(WINDOW *) menu_sub (const MENU *); -extern NCURSES_EXPORT(WINDOW *) menu_win (const MENU *); - -extern NCURSES_EXPORT(const char *) item_description (const ITEM *); -extern NCURSES_EXPORT(const char *) item_name (const ITEM *); -extern NCURSES_EXPORT(const char *) menu_mark (const MENU *); -extern NCURSES_EXPORT(const char *) menu_request_name (int); - -extern NCURSES_EXPORT(char *) menu_pattern (const MENU *); - -extern NCURSES_EXPORT(void *) menu_userptr (const MENU *); -extern NCURSES_EXPORT(void *) item_userptr (const ITEM *); - -extern NCURSES_EXPORT(chtype) menu_back (const MENU *); -extern NCURSES_EXPORT(chtype) menu_fore (const MENU *); -extern NCURSES_EXPORT(chtype) menu_grey (const MENU *); - -extern NCURSES_EXPORT(int) free_item (ITEM *); -extern NCURSES_EXPORT(int) free_menu (MENU *); -extern NCURSES_EXPORT(int) item_count (const MENU *); -extern NCURSES_EXPORT(int) item_index (const ITEM *); -extern NCURSES_EXPORT(int) item_opts_off (ITEM *,Item_Options); -extern NCURSES_EXPORT(int) item_opts_on (ITEM *,Item_Options); -extern NCURSES_EXPORT(int) menu_driver (MENU *,int); -extern NCURSES_EXPORT(int) menu_opts_off (MENU *,Menu_Options); -extern NCURSES_EXPORT(int) menu_opts_on (MENU *,Menu_Options); -extern NCURSES_EXPORT(int) menu_pad (const MENU *); -extern NCURSES_EXPORT(int) pos_menu_cursor (const MENU *); -extern NCURSES_EXPORT(int) post_menu (MENU *); -extern NCURSES_EXPORT(int) scale_menu (const MENU *,int *,int *); -extern NCURSES_EXPORT(int) set_current_item (MENU *menu,ITEM *item); -extern NCURSES_EXPORT(int) set_item_init (MENU *, Menu_Hook); -extern NCURSES_EXPORT(int) set_item_opts (ITEM *,Item_Options); -extern NCURSES_EXPORT(int) set_item_term (MENU *, Menu_Hook); -extern NCURSES_EXPORT(int) set_item_userptr (ITEM *, void *); -extern NCURSES_EXPORT(int) set_item_value (ITEM *,bool); -extern NCURSES_EXPORT(int) set_menu_back (MENU *,chtype); -extern NCURSES_EXPORT(int) set_menu_fore (MENU *,chtype); -extern NCURSES_EXPORT(int) set_menu_format (MENU *,int,int); -extern NCURSES_EXPORT(int) set_menu_grey (MENU *,chtype); -extern NCURSES_EXPORT(int) set_menu_init (MENU *, Menu_Hook); -extern NCURSES_EXPORT(int) set_menu_items (MENU *,ITEM **); -extern NCURSES_EXPORT(int) set_menu_mark (MENU *, const char *); -extern NCURSES_EXPORT(int) set_menu_opts (MENU *,Menu_Options); -extern NCURSES_EXPORT(int) set_menu_pad (MENU *,int); -extern NCURSES_EXPORT(int) set_menu_pattern (MENU *,const char *); -extern NCURSES_EXPORT(int) set_menu_sub (MENU *,WINDOW *); -extern NCURSES_EXPORT(int) set_menu_term (MENU *, Menu_Hook); -extern NCURSES_EXPORT(int) set_menu_userptr (MENU *,void *); -extern NCURSES_EXPORT(int) set_menu_win (MENU *,WINDOW *); -extern NCURSES_EXPORT(int) set_top_row (MENU *,int); -extern NCURSES_EXPORT(int) top_row (const MENU *); -extern NCURSES_EXPORT(int) unpost_menu (MENU *); -extern NCURSES_EXPORT(int) menu_request_by_name (const char *); -extern NCURSES_EXPORT(int) set_menu_spacing (MENU *,int,int,int); -extern NCURSES_EXPORT(int) menu_spacing (const MENU *,int *,int *,int *); - - -extern NCURSES_EXPORT(bool) item_value (const ITEM *); -extern NCURSES_EXPORT(bool) item_visible (const ITEM *); - -extern NCURSES_EXPORT(void) menu_format (const MENU *,int *,int *); - -#if NCURSES_SP_FUNCS -extern NCURSES_EXPORT(MENU *) NCURSES_SP_NAME(new_menu) (SCREEN*, ITEM **); -#endif - -#ifdef __cplusplus - } -#endif - -#endif /* ETI_MENU */ diff --git a/windows/ncurses/include/ncurses/nc_tparm.h b/windows/ncurses/include/ncurses/nc_tparm.h deleted file mode 100644 index a8dbcacb1..000000000 --- a/windows/ncurses/include/ncurses/nc_tparm.h +++ /dev/null @@ -1,73 +0,0 @@ -/**************************************************************************** - * Copyright (c) 2006,2010 Free Software Foundation, Inc. * - * * - * Permission is hereby granted, free of charge, to any person obtaining a * - * copy of this software and associated documentation files (the * - * "Software"), to deal in the Software without restriction, including * - * without limitation the rights to use, copy, modify, merge, publish, * - * distribute, distribute with modifications, sublicense, and/or sell * - * copies of the Software, and to permit persons to whom the Software is * - * furnished to do so, subject to the following conditions: * - * * - * The above copyright notice and this permission notice shall be included * - * in all copies or substantial portions of the Software. * - * * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * - * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * - * THE USE OR OTHER DEALINGS IN THE SOFTWARE. * - * * - * Except as contained in this notice, the name(s) of the above copyright * - * holders shall not be used in advertising or otherwise to promote the * - * sale, use or other dealings in this Software without prior written * - * authorization. * - ****************************************************************************/ - -/**************************************************************************** - * Author: Thomas E. Dickey 2006 * - ****************************************************************************/ - -/* $Id: nc_tparm.h,v 1.5 2010/12/25 20:27:22 tom Exp $ */ - -#ifndef NC_TPARM_included -#define NC_TPARM_included 1 - -/* - * Cast parameters past the formatting-string for tparm() to match the - * assumption of the varargs code. - */ -#ifndef TPARM_ARG -#define TPARM_ARG long -#endif - -#define TPARM_N(n) (TPARM_ARG)(n) - -#define TPARM_9(a,b,c,d,e,f,g,h,i,j) tparm(a,TPARM_N(b),TPARM_N(c),TPARM_N(d),TPARM_N(e),TPARM_N(f),TPARM_N(g),TPARM_N(h),TPARM_N(i),TPARM_N(j)) - -#if NCURSES_TPARM_VARARGS -#define TPARM_8(a,b,c,d,e,f,g,h,i) tparm(a,TPARM_N(b),TPARM_N(c),TPARM_N(d),TPARM_N(e),TPARM_N(f),TPARM_N(g),TPARM_N(h),TPARM_N(i)) -#define TPARM_7(a,b,c,d,e,f,g,h) tparm(a,TPARM_N(b),TPARM_N(c),TPARM_N(d),TPARM_N(e),TPARM_N(f),TPARM_N(g),TPARM_N(h)) -#define TPARM_6(a,b,c,d,e,f,g) tparm(a,TPARM_N(b),TPARM_N(c),TPARM_N(d),TPARM_N(e),TPARM_N(f),TPARM_N(g)) -#define TPARM_5(a,b,c,d,e,f) tparm(a,TPARM_N(b),TPARM_N(c),TPARM_N(d),TPARM_N(e),TPARM_N(f)) -#define TPARM_4(a,b,c,d,e) tparm(a,TPARM_N(b),TPARM_N(c),TPARM_N(d),TPARM_N(e)) -#define TPARM_3(a,b,c,d) tparm(a,TPARM_N(b),TPARM_N(c),TPARM_N(d)) -#define TPARM_2(a,b,c) tparm(a,TPARM_N(b),TPARM_N(c)) -#define TPARM_1(a,b) tparm(a,TPARM_N(b)) -#define TPARM_0(a) tparm(a) -#else -#define TPARM_8(a,b,c,d,e,f,g,h,i) TPARM_9(a,b,c,d,e,f,g,h,i,0) -#define TPARM_7(a,b,c,d,e,f,g,h) TPARM_8(a,b,c,d,e,f,g,h,0) -#define TPARM_6(a,b,c,d,e,f,g) TPARM_7(a,b,c,d,e,f,g,0) -#define TPARM_5(a,b,c,d,e,f) TPARM_6(a,b,c,d,e,f,0) -#define TPARM_4(a,b,c,d,e) TPARM_5(a,b,c,d,e,0) -#define TPARM_3(a,b,c,d) TPARM_4(a,b,c,d,0) -#define TPARM_2(a,b,c) TPARM_3(a,b,c,0) -#define TPARM_1(a,b) TPARM_2(a,b,0) -#define TPARM_1(a,b) TPARM_2(a,b,0) -#define TPARM_0(a) TPARM_1(a,0) -#endif - -#endif /* NC_TPARM_included */ diff --git a/windows/ncurses/include/ncurses/ncurses.h b/windows/ncurses/include/ncurses/ncurses.h deleted file mode 100644 index ff375d525..000000000 --- a/windows/ncurses/include/ncurses/ncurses.h +++ /dev/null @@ -1,1675 +0,0 @@ -/**************************************************************************** - * Copyright (c) 1998-2010,2011 Free Software Foundation, Inc. * - * * - * Permission is hereby granted, free of charge, to any person obtaining a * - * copy of this software and associated documentation files (the * - * "Software"), to deal in the Software without restriction, including * - * without limitation the rights to use, copy, modify, merge, publish, * - * distribute, distribute with modifications, sublicense, and/or sell * - * copies of the Software, and to permit persons to whom the Software is * - * furnished to do so, subject to the following conditions: * - * * - * The above copyright notice and this permission notice shall be included * - * in all copies or substantial portions of the Software. * - * * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * - * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * - * THE USE OR OTHER DEALINGS IN THE SOFTWARE. * - * * - * Except as contained in this notice, the name(s) of the above copyright * - * holders shall not be used in advertising or otherwise to promote the * - * sale, use or other dealings in this Software without prior written * - * authorization. * - ****************************************************************************/ - -/**************************************************************************** - * Author: Zeyd M. Ben-Halim 1992,1995 * - * and: Eric S. Raymond * - * and: Thomas E. Dickey 1996-on * - ****************************************************************************/ - -/* $Id: curses.h.in,v 1.220 2011/01/22 19:47:20 tom Exp $ */ - -#ifndef __NCURSES_H -#define __NCURSES_H - -#define CURSES 1 -#define CURSES_H 1 - -/* These are defined only in curses.h, and are used for conditional compiles */ -#define NCURSES_VERSION_MAJOR 5 -#define NCURSES_VERSION_MINOR 9 -#define NCURSES_VERSION_PATCH 20110404 - -/* This is defined in more than one ncurses header, for identification */ -#undef NCURSES_VERSION -#define NCURSES_VERSION "5.9" - -/* - * Identify the mouse encoding version. - */ -#define NCURSES_MOUSE_VERSION 1 - -/* - * Definitions to facilitate DLL's. - */ -#include - -/* - * User-definable tweak to disable the include of . - */ -#ifndef NCURSES_ENABLE_STDBOOL_H -#define NCURSES_ENABLE_STDBOOL_H 1 -#endif - -/* - * NCURSES_ATTR_T is used to quiet compiler warnings when building ncurses - * configured using --disable-macros. - */ -#ifdef NCURSES_NOMACROS -#ifndef NCURSES_ATTR_T -#define NCURSES_ATTR_T attr_t -#endif -#endif /* NCURSES_NOMACROS */ - -#ifndef NCURSES_ATTR_T -#define NCURSES_ATTR_T int -#endif - -/* - * Expands to 'const' if ncurses is configured using --enable-const. Note that - * doing so makes it incompatible with other implementations of X/Open Curses. - */ -#undef NCURSES_CONST -#define NCURSES_CONST /*nothing*/ - -#undef NCURSES_INLINE -#define NCURSES_INLINE inline - -/* - * The internal type used for color values - */ -#undef NCURSES_COLOR_T -#define NCURSES_COLOR_T short - -/* - * Definition used to make WINDOW and similar structs opaque. - */ -#ifndef NCURSES_OPAQUE -#define NCURSES_OPAQUE 0 -#endif - -/* - * The reentrant code relies on the opaque setting, but adds features. - */ -#ifndef NCURSES_REENTRANT -#define NCURSES_REENTRANT 0 -#endif - -/* - * Control whether bindings for interop support are added. - */ -#undef NCURSES_INTEROP_FUNCS -#define NCURSES_INTEROP_FUNCS 0 - -/* - * The internal type used for window dimensions. - */ -#undef NCURSES_SIZE_T -#define NCURSES_SIZE_T short - -/* - * Control whether tparm() supports varargs or fixed-parameter list. - */ -#undef NCURSES_TPARM_VARARGS -#define NCURSES_TPARM_VARARGS 1 - -/* - * NCURSES_CH_T is used in building the library, but not used otherwise in - * this header file, since that would make the normal/wide-character versions - * of the header incompatible. - */ -#undef NCURSES_CH_T -#define NCURSES_CH_T chtype - -#if 0 && defined(_LP64) -typedef unsigned chtype; -typedef unsigned mmask_t; -#else -typedef unsigned long chtype; -typedef unsigned long mmask_t; -#endif - -/* - * We need FILE, etc. Include this before checking any feature symbols. - */ -#include - -/* - * With XPG4, you must define _XOPEN_SOURCE_EXTENDED, it is redundant (or - * conflicting) when _XOPEN_SOURCE is 500 or greater. - */ -#undef NCURSES_WIDECHAR -#if defined(_XOPEN_SOURCE_EXTENDED) || defined(_XPG5) -#define NCURSES_WIDECHAR -#endif - -#include /* we need va_list */ -#ifdef NCURSES_WIDECHAR -#include /* we want wchar_t */ -#endif - -/* X/Open and SVr4 specify that curses implements 'bool'. However, C++ may also - * implement it. If so, we must use the C++ compiler's type to avoid conflict - * with other interfaces. - * - * A further complication is that may declare 'bool' to be a - * different type, such as an enum which is not necessarily compatible with - * C++. If we have , make 'bool' a macro, so users may #undef it. - * Otherwise, let it remain a typedef to avoid conflicts with other #define's. - * In either case, make a typedef for NCURSES_BOOL which can be used if needed - * from either C or C++. - */ - -#undef TRUE -#define TRUE 1 - -#undef FALSE -#define FALSE 0 - -typedef unsigned char NCURSES_BOOL; - -#if defined(__cplusplus) /* __cplusplus, etc. */ - -/* use the C++ compiler's bool type */ -#define NCURSES_BOOL bool - -#else /* c89, c99, etc. */ - -#if NCURSES_ENABLE_STDBOOL_H -#include -/* use whatever the C compiler decides bool really is */ -#define NCURSES_BOOL bool -#else -/* there is no predefined bool - use our own */ -#undef bool -#define bool NCURSES_BOOL -#endif - -#endif /* !__cplusplus, etc. */ - -#ifdef __cplusplus -extern "C" { -#define NCURSES_CAST(type,value) static_cast(value) -#else -#define NCURSES_CAST(type,value) (type)(value) -#endif - -/* - * X/Open attributes. In the ncurses implementation, they are identical to the - * A_ attributes. - */ -#define WA_ATTRIBUTES A_ATTRIBUTES -#define WA_NORMAL A_NORMAL -#define WA_STANDOUT A_STANDOUT -#define WA_UNDERLINE A_UNDERLINE -#define WA_REVERSE A_REVERSE -#define WA_BLINK A_BLINK -#define WA_DIM A_DIM -#define WA_BOLD A_BOLD -#define WA_ALTCHARSET A_ALTCHARSET -#define WA_INVIS A_INVIS -#define WA_PROTECT A_PROTECT -#define WA_HORIZONTAL A_HORIZONTAL -#define WA_LEFT A_LEFT -#define WA_LOW A_LOW -#define WA_RIGHT A_RIGHT -#define WA_TOP A_TOP -#define WA_VERTICAL A_VERTICAL - -/* colors */ -#define COLOR_BLACK 0 -#define COLOR_RED 1 -#define COLOR_GREEN 2 -#define COLOR_YELLOW 3 -#define COLOR_BLUE 4 -#define COLOR_MAGENTA 5 -#define COLOR_CYAN 6 -#define COLOR_WHITE 7 - -/* line graphics */ - -#if 0 || NCURSES_REENTRANT -NCURSES_WRAPPED_VAR(chtype*, acs_map); -#define acs_map NCURSES_PUBLIC_VAR(acs_map()) -#else -extern NCURSES_EXPORT_VAR(chtype) acs_map[]; -#endif - -#define NCURSES_ACS(c) (acs_map[NCURSES_CAST(unsigned char,c)]) - -/* VT100 symbols begin here */ -#define ACS_ULCORNER NCURSES_ACS('l') /* upper left corner */ -#define ACS_LLCORNER NCURSES_ACS('m') /* lower left corner */ -#define ACS_URCORNER NCURSES_ACS('k') /* upper right corner */ -#define ACS_LRCORNER NCURSES_ACS('j') /* lower right corner */ -#define ACS_LTEE NCURSES_ACS('t') /* tee pointing right */ -#define ACS_RTEE NCURSES_ACS('u') /* tee pointing left */ -#define ACS_BTEE NCURSES_ACS('v') /* tee pointing up */ -#define ACS_TTEE NCURSES_ACS('w') /* tee pointing down */ -#define ACS_HLINE NCURSES_ACS('q') /* horizontal line */ -#define ACS_VLINE NCURSES_ACS('x') /* vertical line */ -#define ACS_PLUS NCURSES_ACS('n') /* large plus or crossover */ -#define ACS_S1 NCURSES_ACS('o') /* scan line 1 */ -#define ACS_S9 NCURSES_ACS('s') /* scan line 9 */ -#define ACS_DIAMOND NCURSES_ACS('`') /* diamond */ -#define ACS_CKBOARD NCURSES_ACS('a') /* checker board (stipple) */ -#define ACS_DEGREE NCURSES_ACS('f') /* degree symbol */ -#define ACS_PLMINUS NCURSES_ACS('g') /* plus/minus */ -#define ACS_BULLET NCURSES_ACS('~') /* bullet */ -/* Teletype 5410v1 symbols begin here */ -#define ACS_LARROW NCURSES_ACS(',') /* arrow pointing left */ -#define ACS_RARROW NCURSES_ACS('+') /* arrow pointing right */ -#define ACS_DARROW NCURSES_ACS('.') /* arrow pointing down */ -#define ACS_UARROW NCURSES_ACS('-') /* arrow pointing up */ -#define ACS_BOARD NCURSES_ACS('h') /* board of squares */ -#define ACS_LANTERN NCURSES_ACS('i') /* lantern symbol */ -#define ACS_BLOCK NCURSES_ACS('0') /* solid square block */ -/* - * These aren't documented, but a lot of System Vs have them anyway - * (you can spot pprryyzz{{||}} in a lot of AT&T terminfo strings). - * The ACS_names may not match AT&T's, our source didn't know them. - */ -#define ACS_S3 NCURSES_ACS('p') /* scan line 3 */ -#define ACS_S7 NCURSES_ACS('r') /* scan line 7 */ -#define ACS_LEQUAL NCURSES_ACS('y') /* less/equal */ -#define ACS_GEQUAL NCURSES_ACS('z') /* greater/equal */ -#define ACS_PI NCURSES_ACS('{') /* Pi */ -#define ACS_NEQUAL NCURSES_ACS('|') /* not equal */ -#define ACS_STERLING NCURSES_ACS('}') /* UK pound sign */ - -/* - * Line drawing ACS names are of the form ACS_trbl, where t is the top, r - * is the right, b is the bottom, and l is the left. t, r, b, and l might - * be B (blank), S (single), D (double), or T (thick). The subset defined - * here only uses B and S. - */ -#define ACS_BSSB ACS_ULCORNER -#define ACS_SSBB ACS_LLCORNER -#define ACS_BBSS ACS_URCORNER -#define ACS_SBBS ACS_LRCORNER -#define ACS_SBSS ACS_RTEE -#define ACS_SSSB ACS_LTEE -#define ACS_SSBS ACS_BTEE -#define ACS_BSSS ACS_TTEE -#define ACS_BSBS ACS_HLINE -#define ACS_SBSB ACS_VLINE -#define ACS_SSSS ACS_PLUS - -#undef ERR -#define ERR (-1) - -#undef OK -#define OK (0) - -/* values for the _flags member */ -#define _SUBWIN 0x01 /* is this a sub-window? */ -#define _ENDLINE 0x02 /* is the window flush right? */ -#define _FULLWIN 0x04 /* is the window full-screen? */ -#define _SCROLLWIN 0x08 /* bottom edge is at screen bottom? */ -#define _ISPAD 0x10 /* is this window a pad? */ -#define _HASMOVED 0x20 /* has cursor moved since last refresh? */ -#define _WRAPPED 0x40 /* cursor was just wrappped */ - -/* - * this value is used in the firstchar and lastchar fields to mark - * unchanged lines - */ -#define _NOCHANGE -1 - -/* - * this value is used in the oldindex field to mark lines created by insertions - * and scrolls. - */ -#define _NEWINDEX -1 - -typedef struct screen SCREEN; -typedef struct _win_st WINDOW; - -typedef chtype attr_t; /* ...must be at least as wide as chtype */ - -#ifdef NCURSES_WIDECHAR - -#if 0 -#ifdef mblen /* libutf8.h defines it w/o undefining first */ -#undef mblen -#endif -#include -#endif - -#if 0 -#include /* ...to get mbstate_t, etc. */ -#endif - -#if 0 -typedef unsigned short wchar_t; -#endif - -#if 0 -typedef unsigned int wint_t; -#endif - -/* - * cchar_t stores an array of CCHARW_MAX wide characters. The first is - * normally a spacing character. The others are non-spacing. If those - * (spacing and nonspacing) do not fill the array, a null L'\0' follows. - * Otherwise, a null is assumed to follow when extracting via getcchar(). - */ -#define CCHARW_MAX 5 -typedef struct -{ - attr_t attr; - wchar_t chars[CCHARW_MAX]; -#if 0 -#undef NCURSES_EXT_COLORS -#define NCURSES_EXT_COLORS 20110404 - int ext_color; /* color pair, must be more than 16-bits */ -#endif -} -cchar_t; - -#endif /* NCURSES_WIDECHAR */ - -#if !NCURSES_OPAQUE -struct ldat; - -struct _win_st -{ - NCURSES_SIZE_T _cury, _curx; /* current cursor position */ - - /* window location and size */ - NCURSES_SIZE_T _maxy, _maxx; /* maximums of x and y, NOT window size */ - NCURSES_SIZE_T _begy, _begx; /* screen coords of upper-left-hand corner */ - - short _flags; /* window state flags */ - - /* attribute tracking */ - attr_t _attrs; /* current attribute for non-space character */ - chtype _bkgd; /* current background char/attribute pair */ - - /* option values set by user */ - bool _notimeout; /* no time out on function-key entry? */ - bool _clear; /* consider all data in the window invalid? */ - bool _leaveok; /* OK to not reset cursor on exit? */ - bool _scroll; /* OK to scroll this window? */ - bool _idlok; /* OK to use insert/delete line? */ - bool _idcok; /* OK to use insert/delete char? */ - bool _immed; /* window in immed mode? (not yet used) */ - bool _sync; /* window in sync mode? */ - bool _use_keypad; /* process function keys into KEY_ symbols? */ - int _delay; /* 0 = nodelay, <0 = blocking, >0 = delay */ - - struct ldat *_line; /* the actual line data */ - - /* global screen state */ - NCURSES_SIZE_T _regtop; /* top line of scrolling region */ - NCURSES_SIZE_T _regbottom; /* bottom line of scrolling region */ - - /* these are used only if this is a sub-window */ - int _parx; /* x coordinate of this window in parent */ - int _pary; /* y coordinate of this window in parent */ - WINDOW *_parent; /* pointer to parent if a sub-window */ - - /* these are used only if this is a pad */ - struct pdat - { - NCURSES_SIZE_T _pad_y, _pad_x; - NCURSES_SIZE_T _pad_top, _pad_left; - NCURSES_SIZE_T _pad_bottom, _pad_right; - } _pad; - - NCURSES_SIZE_T _yoffset; /* real begy is _begy + _yoffset */ - -#ifdef NCURSES_WIDECHAR - cchar_t _bkgrnd; /* current background char/attribute pair */ -#if 0 - int _color; /* current color-pair for non-space character */ -#endif -#endif -}; -#endif /* NCURSES_OPAQUE */ - -/* - * This is an extension to support events... - */ -#if 1 -#ifdef NCURSES_WGETCH_EVENTS -#if !defined(__BEOS__) || defined(__HAIKU__) - /* Fix _nc_timed_wait() on BEOS... */ -# define NCURSES_EVENT_VERSION 1 -#endif /* !defined(__BEOS__) */ - -/* - * Bits to set in _nc_event.data.flags - */ -# define _NC_EVENT_TIMEOUT_MSEC 1 -# define _NC_EVENT_FILE 2 -# define _NC_EVENT_FILE_READABLE 2 -# if 0 /* Not supported yet... */ -# define _NC_EVENT_FILE_WRITABLE 4 -# define _NC_EVENT_FILE_EXCEPTION 8 -# endif - -typedef struct -{ - int type; - union - { - long timeout_msec; /* _NC_EVENT_TIMEOUT_MSEC */ - struct - { - unsigned int flags; - int fd; - unsigned int result; - } fev; /* _NC_EVENT_FILE */ - } data; -} _nc_event; - -typedef struct -{ - int count; - int result_flags; /* _NC_EVENT_TIMEOUT_MSEC or _NC_EVENT_FILE_READABLE */ - _nc_event *events[1]; -} _nc_eventlist; - -extern NCURSES_EXPORT(int) wgetch_events (WINDOW *, _nc_eventlist *); /* experimental */ -extern NCURSES_EXPORT(int) wgetnstr_events (WINDOW *,char *,int,_nc_eventlist *);/* experimental */ - -#endif /* NCURSES_WGETCH_EVENTS */ -#endif /* NCURSES_EXT_FUNCS */ - -/* - * GCC (and some other compilers) define '__attribute__'; we're using this - * macro to alert the compiler to flag inconsistencies in printf/scanf-like - * function calls. Just in case '__attribute__' isn't defined, make a dummy. - * Old versions of G++ do not accept it anyway, at least not consistently with - * GCC. - */ -#if !(defined(__GNUC__) || defined(__GNUG__) || defined(__attribute__)) -#define __attribute__(p) /* nothing */ -#endif - -/* - * We cannot define these in ncurses_cfg.h, since they require parameters to be - * passed (that is non-portable). If you happen to be using gcc with warnings - * enabled, define - * GCC_PRINTF - * GCC_SCANF - * to improve checking of calls to printw(), etc. - */ -#ifndef GCC_PRINTFLIKE -#if defined(GCC_PRINTF) && !defined(printf) -#define GCC_PRINTFLIKE(fmt,var) __attribute__((format(printf,fmt,var))) -#else -#define GCC_PRINTFLIKE(fmt,var) /*nothing*/ -#endif -#endif - -#ifndef GCC_SCANFLIKE -#if defined(GCC_SCANF) && !defined(scanf) -#define GCC_SCANFLIKE(fmt,var) __attribute__((format(scanf,fmt,var))) -#else -#define GCC_SCANFLIKE(fmt,var) /*nothing*/ -#endif -#endif - -#ifndef GCC_NORETURN -#define GCC_NORETURN /* nothing */ -#endif - -#ifndef GCC_UNUSED -#define GCC_UNUSED /* nothing */ -#endif - -/* - * Curses uses a helper function. Define our type for this to simplify - * extending it for the sp-funcs feature. - */ -typedef int (*NCURSES_OUTC)(int); - -/* - * Function prototypes. This is the complete X/Open Curses list of required - * functions. Those marked `generated' will have sources generated from the - * macro definitions later in this file, in order to satisfy XPG4.2 - * requirements. - */ - -extern NCURSES_EXPORT(int) addch (const chtype); /* generated */ -extern NCURSES_EXPORT(int) addchnstr (const chtype *, int); /* generated */ -extern NCURSES_EXPORT(int) addchstr (const chtype *); /* generated */ -extern NCURSES_EXPORT(int) addnstr (const char *, int); /* generated */ -extern NCURSES_EXPORT(int) addstr (const char *); /* generated */ -extern NCURSES_EXPORT(int) attroff (NCURSES_ATTR_T); /* generated */ -extern NCURSES_EXPORT(int) attron (NCURSES_ATTR_T); /* generated */ -extern NCURSES_EXPORT(int) attrset (NCURSES_ATTR_T); /* generated */ -extern NCURSES_EXPORT(int) attr_get (attr_t *, short *, void *); /* generated */ -extern NCURSES_EXPORT(int) attr_off (attr_t, void *); /* generated */ -extern NCURSES_EXPORT(int) attr_on (attr_t, void *); /* generated */ -extern NCURSES_EXPORT(int) attr_set (attr_t, short, void *); /* generated */ -extern NCURSES_EXPORT(int) baudrate (void); /* implemented */ -extern NCURSES_EXPORT(int) beep (void); /* implemented */ -extern NCURSES_EXPORT(int) bkgd (chtype); /* generated */ -extern NCURSES_EXPORT(void) bkgdset (chtype); /* generated */ -extern NCURSES_EXPORT(int) border (chtype,chtype,chtype,chtype,chtype,chtype,chtype,chtype); /* generated */ -extern NCURSES_EXPORT(int) box (WINDOW *, chtype, chtype); /* generated */ -extern NCURSES_EXPORT(bool) can_change_color (void); /* implemented */ -extern NCURSES_EXPORT(int) cbreak (void); /* implemented */ -extern NCURSES_EXPORT(int) chgat (int, attr_t, short, const void *); /* generated */ -extern NCURSES_EXPORT(int) clear (void); /* generated */ -extern NCURSES_EXPORT(int) clearok (WINDOW *,bool); /* implemented */ -extern NCURSES_EXPORT(int) clrtobot (void); /* generated */ -extern NCURSES_EXPORT(int) clrtoeol (void); /* generated */ -extern NCURSES_EXPORT(int) color_content (short,short*,short*,short*); /* implemented */ -extern NCURSES_EXPORT(int) color_set (short,void*); /* generated */ -extern NCURSES_EXPORT(int) COLOR_PAIR (int); /* generated */ -extern NCURSES_EXPORT(int) copywin (const WINDOW*,WINDOW*,int,int,int,int,int,int,int); /* implemented */ -extern NCURSES_EXPORT(int) curs_set (int); /* implemented */ -extern NCURSES_EXPORT(int) def_prog_mode (void); /* implemented */ -extern NCURSES_EXPORT(int) def_shell_mode (void); /* implemented */ -extern NCURSES_EXPORT(int) delay_output (int); /* implemented */ -extern NCURSES_EXPORT(int) delch (void); /* generated */ -extern NCURSES_EXPORT(void) delscreen (SCREEN *); /* implemented */ -extern NCURSES_EXPORT(int) delwin (WINDOW *); /* implemented */ -extern NCURSES_EXPORT(int) deleteln (void); /* generated */ -extern NCURSES_EXPORT(WINDOW *) derwin (WINDOW *,int,int,int,int); /* implemented */ -extern NCURSES_EXPORT(int) doupdate (void); /* implemented */ -extern NCURSES_EXPORT(WINDOW *) dupwin (WINDOW *); /* implemented */ -extern NCURSES_EXPORT(int) echo (void); /* implemented */ -extern NCURSES_EXPORT(int) echochar (const chtype); /* generated */ -extern NCURSES_EXPORT(int) erase (void); /* generated */ -extern NCURSES_EXPORT(int) endwin (void); /* implemented */ -extern NCURSES_EXPORT(char) erasechar (void); /* implemented */ -extern NCURSES_EXPORT(void) filter (void); /* implemented */ -extern NCURSES_EXPORT(int) flash (void); /* implemented */ -extern NCURSES_EXPORT(int) flushinp (void); /* implemented */ -extern NCURSES_EXPORT(chtype) getbkgd (WINDOW *); /* generated */ -extern NCURSES_EXPORT(int) getch (void); /* generated */ -extern NCURSES_EXPORT(int) getnstr (char *, int); /* generated */ -extern NCURSES_EXPORT(int) getstr (char *); /* generated */ -extern NCURSES_EXPORT(WINDOW *) getwin (FILE *); /* implemented */ -extern NCURSES_EXPORT(int) halfdelay (int); /* implemented */ -extern NCURSES_EXPORT(bool) has_colors (void); /* implemented */ -extern NCURSES_EXPORT(bool) has_ic (void); /* implemented */ -extern NCURSES_EXPORT(bool) has_il (void); /* implemented */ -extern NCURSES_EXPORT(int) hline (chtype, int); /* generated */ -extern NCURSES_EXPORT(void) idcok (WINDOW *, bool); /* implemented */ -extern NCURSES_EXPORT(int) idlok (WINDOW *, bool); /* implemented */ -extern NCURSES_EXPORT(void) immedok (WINDOW *, bool); /* implemented */ -extern NCURSES_EXPORT(chtype) inch (void); /* generated */ -extern NCURSES_EXPORT(int) inchnstr (chtype *, int); /* generated */ -extern NCURSES_EXPORT(int) inchstr (chtype *); /* generated */ -extern NCURSES_EXPORT(WINDOW *) initscr (void); /* implemented */ -extern NCURSES_EXPORT(int) init_color (short,short,short,short); /* implemented */ -extern NCURSES_EXPORT(int) init_pair (short,short,short); /* implemented */ -extern NCURSES_EXPORT(int) innstr (char *, int); /* generated */ -extern NCURSES_EXPORT(int) insch (chtype); /* generated */ -extern NCURSES_EXPORT(int) insdelln (int); /* generated */ -extern NCURSES_EXPORT(int) insertln (void); /* generated */ -extern NCURSES_EXPORT(int) insnstr (const char *, int); /* generated */ -extern NCURSES_EXPORT(int) insstr (const char *); /* generated */ -extern NCURSES_EXPORT(int) instr (char *); /* generated */ -extern NCURSES_EXPORT(int) intrflush (WINDOW *,bool); /* implemented */ -extern NCURSES_EXPORT(bool) isendwin (void); /* implemented */ -extern NCURSES_EXPORT(bool) is_linetouched (WINDOW *,int); /* implemented */ -extern NCURSES_EXPORT(bool) is_wintouched (WINDOW *); /* implemented */ -extern NCURSES_EXPORT(NCURSES_CONST char *) keyname (int); /* implemented */ -extern NCURSES_EXPORT(int) keypad (WINDOW *,bool); /* implemented */ -extern NCURSES_EXPORT(char) killchar (void); /* implemented */ -extern NCURSES_EXPORT(int) leaveok (WINDOW *,bool); /* implemented */ -extern NCURSES_EXPORT(char *) longname (void); /* implemented */ -extern NCURSES_EXPORT(int) meta (WINDOW *,bool); /* implemented */ -extern NCURSES_EXPORT(int) move (int, int); /* generated */ -extern NCURSES_EXPORT(int) mvaddch (int, int, const chtype); /* generated */ -extern NCURSES_EXPORT(int) mvaddchnstr (int, int, const chtype *, int); /* generated */ -extern NCURSES_EXPORT(int) mvaddchstr (int, int, const chtype *); /* generated */ -extern NCURSES_EXPORT(int) mvaddnstr (int, int, const char *, int); /* generated */ -extern NCURSES_EXPORT(int) mvaddstr (int, int, const char *); /* generated */ -extern NCURSES_EXPORT(int) mvchgat (int, int, int, attr_t, short, const void *); /* generated */ -extern NCURSES_EXPORT(int) mvcur (int,int,int,int); /* implemented */ -extern NCURSES_EXPORT(int) mvdelch (int, int); /* generated */ -extern NCURSES_EXPORT(int) mvderwin (WINDOW *, int, int); /* implemented */ -extern NCURSES_EXPORT(int) mvgetch (int, int); /* generated */ -extern NCURSES_EXPORT(int) mvgetnstr (int, int, char *, int); /* generated */ -extern NCURSES_EXPORT(int) mvgetstr (int, int, char *); /* generated */ -extern NCURSES_EXPORT(int) mvhline (int, int, chtype, int); /* generated */ -extern NCURSES_EXPORT(chtype) mvinch (int, int); /* generated */ -extern NCURSES_EXPORT(int) mvinchnstr (int, int, chtype *, int); /* generated */ -extern NCURSES_EXPORT(int) mvinchstr (int, int, chtype *); /* generated */ -extern NCURSES_EXPORT(int) mvinnstr (int, int, char *, int); /* generated */ -extern NCURSES_EXPORT(int) mvinsch (int, int, chtype); /* generated */ -extern NCURSES_EXPORT(int) mvinsnstr (int, int, const char *, int); /* generated */ -extern NCURSES_EXPORT(int) mvinsstr (int, int, const char *); /* generated */ -extern NCURSES_EXPORT(int) mvinstr (int, int, char *); /* generated */ -extern NCURSES_EXPORT(int) mvprintw (int,int, const char *,...) /* implemented */ - GCC_PRINTFLIKE(3,4); -extern NCURSES_EXPORT(int) mvscanw (int,int, NCURSES_CONST char *,...) /* implemented */ - GCC_SCANFLIKE(3,4); -extern NCURSES_EXPORT(int) mvvline (int, int, chtype, int); /* generated */ -extern NCURSES_EXPORT(int) mvwaddch (WINDOW *, int, int, const chtype); /* generated */ -extern NCURSES_EXPORT(int) mvwaddchnstr (WINDOW *, int, int, const chtype *, int);/* generated */ -extern NCURSES_EXPORT(int) mvwaddchstr (WINDOW *, int, int, const chtype *); /* generated */ -extern NCURSES_EXPORT(int) mvwaddnstr (WINDOW *, int, int, const char *, int); /* generated */ -extern NCURSES_EXPORT(int) mvwaddstr (WINDOW *, int, int, const char *); /* generated */ -extern NCURSES_EXPORT(int) mvwchgat (WINDOW *, int, int, int, attr_t, short, const void *);/* generated */ -extern NCURSES_EXPORT(int) mvwdelch (WINDOW *, int, int); /* generated */ -extern NCURSES_EXPORT(int) mvwgetch (WINDOW *, int, int); /* generated */ -extern NCURSES_EXPORT(int) mvwgetnstr (WINDOW *, int, int, char *, int); /* generated */ -extern NCURSES_EXPORT(int) mvwgetstr (WINDOW *, int, int, char *); /* generated */ -extern NCURSES_EXPORT(int) mvwhline (WINDOW *, int, int, chtype, int); /* generated */ -extern NCURSES_EXPORT(int) mvwin (WINDOW *,int,int); /* implemented */ -extern NCURSES_EXPORT(chtype) mvwinch (WINDOW *, int, int); /* generated */ -extern NCURSES_EXPORT(int) mvwinchnstr (WINDOW *, int, int, chtype *, int); /* generated */ -extern NCURSES_EXPORT(int) mvwinchstr (WINDOW *, int, int, chtype *); /* generated */ -extern NCURSES_EXPORT(int) mvwinnstr (WINDOW *, int, int, char *, int); /* generated */ -extern NCURSES_EXPORT(int) mvwinsch (WINDOW *, int, int, chtype); /* generated */ -extern NCURSES_EXPORT(int) mvwinsnstr (WINDOW *, int, int, const char *, int); /* generated */ -extern NCURSES_EXPORT(int) mvwinsstr (WINDOW *, int, int, const char *); /* generated */ -extern NCURSES_EXPORT(int) mvwinstr (WINDOW *, int, int, char *); /* generated */ -extern NCURSES_EXPORT(int) mvwprintw (WINDOW*,int,int, const char *,...) /* implemented */ - GCC_PRINTFLIKE(4,5); -extern NCURSES_EXPORT(int) mvwscanw (WINDOW *,int,int, NCURSES_CONST char *,...) /* implemented */ - GCC_SCANFLIKE(4,5); -extern NCURSES_EXPORT(int) mvwvline (WINDOW *,int, int, chtype, int); /* generated */ -extern NCURSES_EXPORT(int) napms (int); /* implemented */ -extern NCURSES_EXPORT(WINDOW *) newpad (int,int); /* implemented */ -extern NCURSES_EXPORT(SCREEN *) newterm (NCURSES_CONST char *,FILE *,FILE *); /* implemented */ -extern NCURSES_EXPORT(WINDOW *) newwin (int,int,int,int); /* implemented */ -extern NCURSES_EXPORT(int) nl (void); /* implemented */ -extern NCURSES_EXPORT(int) nocbreak (void); /* implemented */ -extern NCURSES_EXPORT(int) nodelay (WINDOW *,bool); /* implemented */ -extern NCURSES_EXPORT(int) noecho (void); /* implemented */ -extern NCURSES_EXPORT(int) nonl (void); /* implemented */ -extern NCURSES_EXPORT(void) noqiflush (void); /* implemented */ -extern NCURSES_EXPORT(int) noraw (void); /* implemented */ -extern NCURSES_EXPORT(int) notimeout (WINDOW *,bool); /* implemented */ -extern NCURSES_EXPORT(int) overlay (const WINDOW*,WINDOW *); /* implemented */ -extern NCURSES_EXPORT(int) overwrite (const WINDOW*,WINDOW *); /* implemented */ -extern NCURSES_EXPORT(int) pair_content (short,short*,short*); /* implemented */ -extern NCURSES_EXPORT(int) PAIR_NUMBER (int); /* generated */ -extern NCURSES_EXPORT(int) pechochar (WINDOW *, const chtype); /* implemented */ -extern NCURSES_EXPORT(int) pnoutrefresh (WINDOW*,int,int,int,int,int,int);/* implemented */ -extern NCURSES_EXPORT(int) prefresh (WINDOW *,int,int,int,int,int,int); /* implemented */ -extern NCURSES_EXPORT(int) printw (const char *,...) /* implemented */ - GCC_PRINTFLIKE(1,2); -extern NCURSES_EXPORT(int) putwin (WINDOW *, FILE *); /* implemented */ -extern NCURSES_EXPORT(void) qiflush (void); /* implemented */ -extern NCURSES_EXPORT(int) raw (void); /* implemented */ -extern NCURSES_EXPORT(int) redrawwin (WINDOW *); /* generated */ -extern NCURSES_EXPORT(int) refresh (void); /* generated */ -extern NCURSES_EXPORT(int) resetty (void); /* implemented */ -extern NCURSES_EXPORT(int) reset_prog_mode (void); /* implemented */ -extern NCURSES_EXPORT(int) reset_shell_mode (void); /* implemented */ -extern NCURSES_EXPORT(int) ripoffline (int, int (*)(WINDOW *, int)); /* implemented */ -extern NCURSES_EXPORT(int) savetty (void); /* implemented */ -extern NCURSES_EXPORT(int) scanw (NCURSES_CONST char *,...) /* implemented */ - GCC_SCANFLIKE(1,2); -extern NCURSES_EXPORT(int) scr_dump (const char *); /* implemented */ -extern NCURSES_EXPORT(int) scr_init (const char *); /* implemented */ -extern NCURSES_EXPORT(int) scrl (int); /* generated */ -extern NCURSES_EXPORT(int) scroll (WINDOW *); /* generated */ -extern NCURSES_EXPORT(int) scrollok (WINDOW *,bool); /* implemented */ -extern NCURSES_EXPORT(int) scr_restore (const char *); /* implemented */ -extern NCURSES_EXPORT(int) scr_set (const char *); /* implemented */ -extern NCURSES_EXPORT(int) setscrreg (int,int); /* generated */ -extern NCURSES_EXPORT(SCREEN *) set_term (SCREEN *); /* implemented */ -extern NCURSES_EXPORT(int) slk_attroff (const chtype); /* implemented */ -extern NCURSES_EXPORT(int) slk_attr_off (const attr_t, void *); /* generated:WIDEC */ -extern NCURSES_EXPORT(int) slk_attron (const chtype); /* implemented */ -extern NCURSES_EXPORT(int) slk_attr_on (attr_t,void*); /* generated:WIDEC */ -extern NCURSES_EXPORT(int) slk_attrset (const chtype); /* implemented */ -extern NCURSES_EXPORT(attr_t) slk_attr (void); /* implemented */ -extern NCURSES_EXPORT(int) slk_attr_set (const attr_t,short,void*); /* implemented */ -extern NCURSES_EXPORT(int) slk_clear (void); /* implemented */ -extern NCURSES_EXPORT(int) slk_color (short); /* implemented */ -extern NCURSES_EXPORT(int) slk_init (int); /* implemented */ -extern NCURSES_EXPORT(char *) slk_label (int); /* implemented */ -extern NCURSES_EXPORT(int) slk_noutrefresh (void); /* implemented */ -extern NCURSES_EXPORT(int) slk_refresh (void); /* implemented */ -extern NCURSES_EXPORT(int) slk_restore (void); /* implemented */ -extern NCURSES_EXPORT(int) slk_set (int,const char *,int); /* implemented */ -extern NCURSES_EXPORT(int) slk_touch (void); /* implemented */ -extern NCURSES_EXPORT(int) standout (void); /* generated */ -extern NCURSES_EXPORT(int) standend (void); /* generated */ -extern NCURSES_EXPORT(int) start_color (void); /* implemented */ -extern NCURSES_EXPORT(WINDOW *) subpad (WINDOW *, int, int, int, int); /* implemented */ -extern NCURSES_EXPORT(WINDOW *) subwin (WINDOW *, int, int, int, int); /* implemented */ -extern NCURSES_EXPORT(int) syncok (WINDOW *, bool); /* implemented */ -extern NCURSES_EXPORT(chtype) termattrs (void); /* implemented */ -extern NCURSES_EXPORT(char *) termname (void); /* implemented */ -extern NCURSES_EXPORT(void) timeout (int); /* generated */ -extern NCURSES_EXPORT(int) touchline (WINDOW *, int, int); /* generated */ -extern NCURSES_EXPORT(int) touchwin (WINDOW *); /* generated */ -extern NCURSES_EXPORT(int) typeahead (int); /* implemented */ -extern NCURSES_EXPORT(int) ungetch (int); /* implemented */ -extern NCURSES_EXPORT(int) untouchwin (WINDOW *); /* generated */ -extern NCURSES_EXPORT(void) use_env (bool); /* implemented */ -extern NCURSES_EXPORT(int) vidattr (chtype); /* implemented */ -extern NCURSES_EXPORT(int) vidputs (chtype, NCURSES_OUTC); /* implemented */ -extern NCURSES_EXPORT(int) vline (chtype, int); /* generated */ -extern NCURSES_EXPORT(int) vwprintw (WINDOW *, const char *,va_list); /* implemented */ -extern NCURSES_EXPORT(int) vw_printw (WINDOW *, const char *,va_list); /* generated */ -extern NCURSES_EXPORT(int) vwscanw (WINDOW *, NCURSES_CONST char *,va_list); /* implemented */ -extern NCURSES_EXPORT(int) vw_scanw (WINDOW *, NCURSES_CONST char *,va_list); /* generated */ -extern NCURSES_EXPORT(int) waddch (WINDOW *, const chtype); /* implemented */ -extern NCURSES_EXPORT(int) waddchnstr (WINDOW *,const chtype *,int); /* implemented */ -extern NCURSES_EXPORT(int) waddchstr (WINDOW *,const chtype *); /* generated */ -extern NCURSES_EXPORT(int) waddnstr (WINDOW *,const char *,int); /* implemented */ -extern NCURSES_EXPORT(int) waddstr (WINDOW *,const char *); /* generated */ -extern NCURSES_EXPORT(int) wattron (WINDOW *, int); /* generated */ -extern NCURSES_EXPORT(int) wattroff (WINDOW *, int); /* generated */ -extern NCURSES_EXPORT(int) wattrset (WINDOW *, int); /* generated */ -extern NCURSES_EXPORT(int) wattr_get (WINDOW *, attr_t *, short *, void *); /* generated */ -extern NCURSES_EXPORT(int) wattr_on (WINDOW *, attr_t, void *); /* implemented */ -extern NCURSES_EXPORT(int) wattr_off (WINDOW *, attr_t, void *); /* implemented */ -extern NCURSES_EXPORT(int) wattr_set (WINDOW *, attr_t, short, void *); /* generated */ -extern NCURSES_EXPORT(int) wbkgd (WINDOW *, chtype); /* implemented */ -extern NCURSES_EXPORT(void) wbkgdset (WINDOW *,chtype); /* implemented */ -extern NCURSES_EXPORT(int) wborder (WINDOW *,chtype,chtype,chtype,chtype,chtype,chtype,chtype,chtype); /* implemented */ -extern NCURSES_EXPORT(int) wchgat (WINDOW *, int, attr_t, short, const void *);/* implemented */ -extern NCURSES_EXPORT(int) wclear (WINDOW *); /* implemented */ -extern NCURSES_EXPORT(int) wclrtobot (WINDOW *); /* implemented */ -extern NCURSES_EXPORT(int) wclrtoeol (WINDOW *); /* implemented */ -extern NCURSES_EXPORT(int) wcolor_set (WINDOW*,short,void*); /* implemented */ -extern NCURSES_EXPORT(void) wcursyncup (WINDOW *); /* implemented */ -extern NCURSES_EXPORT(int) wdelch (WINDOW *); /* implemented */ -extern NCURSES_EXPORT(int) wdeleteln (WINDOW *); /* generated */ -extern NCURSES_EXPORT(int) wechochar (WINDOW *, const chtype); /* implemented */ -extern NCURSES_EXPORT(int) werase (WINDOW *); /* implemented */ -extern NCURSES_EXPORT(int) wgetch (WINDOW *); /* implemented */ -extern NCURSES_EXPORT(int) wgetnstr (WINDOW *,char *,int); /* implemented */ -extern NCURSES_EXPORT(int) wgetstr (WINDOW *, char *); /* generated */ -extern NCURSES_EXPORT(int) whline (WINDOW *, chtype, int); /* implemented */ -extern NCURSES_EXPORT(chtype) winch (WINDOW *); /* implemented */ -extern NCURSES_EXPORT(int) winchnstr (WINDOW *, chtype *, int); /* implemented */ -extern NCURSES_EXPORT(int) winchstr (WINDOW *, chtype *); /* generated */ -extern NCURSES_EXPORT(int) winnstr (WINDOW *, char *, int); /* implemented */ -extern NCURSES_EXPORT(int) winsch (WINDOW *, chtype); /* implemented */ -extern NCURSES_EXPORT(int) winsdelln (WINDOW *,int); /* implemented */ -extern NCURSES_EXPORT(int) winsertln (WINDOW *); /* generated */ -extern NCURSES_EXPORT(int) winsnstr (WINDOW *, const char *,int); /* implemented */ -extern NCURSES_EXPORT(int) winsstr (WINDOW *, const char *); /* generated */ -extern NCURSES_EXPORT(int) winstr (WINDOW *, char *); /* generated */ -extern NCURSES_EXPORT(int) wmove (WINDOW *,int,int); /* implemented */ -extern NCURSES_EXPORT(int) wnoutrefresh (WINDOW *); /* implemented */ -extern NCURSES_EXPORT(int) wprintw (WINDOW *, const char *,...) /* implemented */ - GCC_PRINTFLIKE(2,3); -extern NCURSES_EXPORT(int) wredrawln (WINDOW *,int,int); /* implemented */ -extern NCURSES_EXPORT(int) wrefresh (WINDOW *); /* implemented */ -extern NCURSES_EXPORT(int) wscanw (WINDOW *, NCURSES_CONST char *,...) /* implemented */ - GCC_SCANFLIKE(2,3); -extern NCURSES_EXPORT(int) wscrl (WINDOW *,int); /* implemented */ -extern NCURSES_EXPORT(int) wsetscrreg (WINDOW *,int,int); /* implemented */ -extern NCURSES_EXPORT(int) wstandout (WINDOW *); /* generated */ -extern NCURSES_EXPORT(int) wstandend (WINDOW *); /* generated */ -extern NCURSES_EXPORT(void) wsyncdown (WINDOW *); /* implemented */ -extern NCURSES_EXPORT(void) wsyncup (WINDOW *); /* implemented */ -extern NCURSES_EXPORT(void) wtimeout (WINDOW *,int); /* implemented */ -extern NCURSES_EXPORT(int) wtouchln (WINDOW *,int,int,int); /* implemented */ -extern NCURSES_EXPORT(int) wvline (WINDOW *,chtype,int); /* implemented */ - -/* - * These are also declared in : - */ -extern NCURSES_EXPORT(int) tigetflag (NCURSES_CONST char *); /* implemented */ -extern NCURSES_EXPORT(int) tigetnum (NCURSES_CONST char *); /* implemented */ -extern NCURSES_EXPORT(char *) tigetstr (NCURSES_CONST char *); /* implemented */ -extern NCURSES_EXPORT(int) putp (const char *); /* implemented */ - -#if NCURSES_TPARM_VARARGS -extern NCURSES_EXPORT(char *) tparm (NCURSES_CONST char *, ...); /* special */ -#else -extern NCURSES_EXPORT(char *) tparm (NCURSES_CONST char *, long,long,long,long,long,long,long,long,long); /* special */ -extern NCURSES_EXPORT(char *) tparm_varargs (NCURSES_CONST char *, ...); /* special */ -#endif - -extern NCURSES_EXPORT(char *) tiparm (const char *, ...); /* special */ - -/* - * These functions are not in X/Open, but we use them in macro definitions: - */ -extern NCURSES_EXPORT(int) getattrs (const WINDOW *); /* generated */ -extern NCURSES_EXPORT(int) getcurx (const WINDOW *); /* generated */ -extern NCURSES_EXPORT(int) getcury (const WINDOW *); /* generated */ -extern NCURSES_EXPORT(int) getbegx (const WINDOW *); /* generated */ -extern NCURSES_EXPORT(int) getbegy (const WINDOW *); /* generated */ -extern NCURSES_EXPORT(int) getmaxx (const WINDOW *); /* generated */ -extern NCURSES_EXPORT(int) getmaxy (const WINDOW *); /* generated */ -extern NCURSES_EXPORT(int) getparx (const WINDOW *); /* generated */ -extern NCURSES_EXPORT(int) getpary (const WINDOW *); /* generated */ - -/* - * vid_attr() was implemented originally based on a draft of X/Open curses. - */ -#ifndef NCURSES_WIDECHAR -#define vid_attr(a,pair,opts) vidattr(a) -#endif - -/* - * These functions are extensions - not in X/Open Curses. - */ -#if 1 -#undef NCURSES_EXT_FUNCS -#define NCURSES_EXT_FUNCS 20110404 -typedef int (*NCURSES_WINDOW_CB)(WINDOW *, void *); -typedef int (*NCURSES_SCREEN_CB)(SCREEN *, void *); -extern NCURSES_EXPORT(bool) is_term_resized (int, int); -extern NCURSES_EXPORT(char *) keybound (int, int); -extern NCURSES_EXPORT(const char *) curses_version (void); -extern NCURSES_EXPORT(int) assume_default_colors (int, int); -extern NCURSES_EXPORT(int) define_key (const char *, int); -extern NCURSES_EXPORT(int) get_escdelay (void); -extern NCURSES_EXPORT(int) key_defined (const char *); -extern NCURSES_EXPORT(int) keyok (int, bool); -extern NCURSES_EXPORT(int) resize_term (int, int); -extern NCURSES_EXPORT(int) resizeterm (int, int); -extern NCURSES_EXPORT(int) set_escdelay (int); -extern NCURSES_EXPORT(int) set_tabsize (int); -extern NCURSES_EXPORT(int) use_default_colors (void); -extern NCURSES_EXPORT(int) use_extended_names (bool); -extern NCURSES_EXPORT(int) use_legacy_coding (int); -extern NCURSES_EXPORT(int) use_screen (SCREEN *, NCURSES_SCREEN_CB, void *); -extern NCURSES_EXPORT(int) use_window (WINDOW *, NCURSES_WINDOW_CB, void *); -extern NCURSES_EXPORT(int) wresize (WINDOW *, int, int); -extern NCURSES_EXPORT(void) nofilter(void); - -/* - * These extensions provide access to information stored in the WINDOW even - * when NCURSES_OPAQUE is set: - */ -extern NCURSES_EXPORT(WINDOW *) wgetparent (const WINDOW *); /* generated */ -extern NCURSES_EXPORT(bool) is_cleared (const WINDOW *); /* generated */ -extern NCURSES_EXPORT(bool) is_idcok (const WINDOW *); /* generated */ -extern NCURSES_EXPORT(bool) is_idlok (const WINDOW *); /* generated */ -extern NCURSES_EXPORT(bool) is_immedok (const WINDOW *); /* generated */ -extern NCURSES_EXPORT(bool) is_keypad (const WINDOW *); /* generated */ -extern NCURSES_EXPORT(bool) is_leaveok (const WINDOW *); /* generated */ -extern NCURSES_EXPORT(bool) is_nodelay (const WINDOW *); /* generated */ -extern NCURSES_EXPORT(bool) is_notimeout (const WINDOW *); /* generated */ -extern NCURSES_EXPORT(bool) is_pad (const WINDOW *); /* generated */ -extern NCURSES_EXPORT(bool) is_scrollok (const WINDOW *); /* generated */ -extern NCURSES_EXPORT(bool) is_subwin (const WINDOW *); /* generated */ -extern NCURSES_EXPORT(bool) is_syncok (const WINDOW *); /* generated */ -extern NCURSES_EXPORT(int) wgetscrreg (const WINDOW *, int *, int *); /* generated */ - -#else -#define curses_version() NCURSES_VERSION -#endif - -/* - * Extra extension-functions, which pass a SCREEN pointer rather than using - * a global variable SP. - */ -#if 1 -#undef NCURSES_SP_FUNCS -#define NCURSES_SP_FUNCS 20110404 -#define NCURSES_SP_NAME(name) name##_sp - -/* Define the sp-funcs helper function */ -#define NCURSES_SP_OUTC NCURSES_SP_NAME(NCURSES_OUTC) -typedef int (*NCURSES_SP_OUTC)(SCREEN*, int); - -extern NCURSES_EXPORT(SCREEN *) new_prescr (void); /* implemented:SP_FUNC */ - -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(baudrate) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(beep) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(bool) NCURSES_SP_NAME(can_change_color) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(cbreak) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(curs_set) (SCREEN*, int); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(color_content) (SCREEN*, short, short*, short*, short*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(def_prog_mode) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(def_shell_mode) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(delay_output) (SCREEN*, int); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(doupdate) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(echo) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(endwin) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(char) NCURSES_SP_NAME(erasechar) (SCREEN*);/* implemented:SP_FUNC */ -extern NCURSES_EXPORT(void) NCURSES_SP_NAME(filter) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(flash) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(flushinp) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(WINDOW *) NCURSES_SP_NAME(getwin) (SCREEN*, FILE *); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(halfdelay) (SCREEN*, int); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(bool) NCURSES_SP_NAME(has_colors) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(bool) NCURSES_SP_NAME(has_ic) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(bool) NCURSES_SP_NAME(has_il) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(init_color) (SCREEN*, short, short, short, short); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(init_pair) (SCREEN*, short, short, short); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(intrflush) (SCREEN*, WINDOW*, bool); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(bool) NCURSES_SP_NAME(isendwin) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(NCURSES_CONST char *) NCURSES_SP_NAME(keyname) (SCREEN*, int); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(char) NCURSES_SP_NAME(killchar) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(char *) NCURSES_SP_NAME(longname) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(mvcur) (SCREEN*, int, int, int, int); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(napms) (SCREEN*, int); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(WINDOW *) NCURSES_SP_NAME(newpad) (SCREEN*, int, int); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(SCREEN *) NCURSES_SP_NAME(newterm) (SCREEN*, NCURSES_CONST char *, FILE *, FILE *); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(WINDOW *) NCURSES_SP_NAME(newwin) (SCREEN*, int, int, int, int); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(nl) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(nocbreak) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(noecho) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(nonl) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(void) NCURSES_SP_NAME(noqiflush) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(noraw) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(pair_content) (SCREEN*, short, short*, short*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(void) NCURSES_SP_NAME(qiflush) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(raw) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(reset_prog_mode) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(reset_shell_mode) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(resetty) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(ripoffline) (SCREEN*, int, int (*)(WINDOW *, int)); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(savetty) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(scr_init) (SCREEN*, const char *); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(scr_restore) (SCREEN*, const char *); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(scr_set) (SCREEN*, const char *); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(slk_attroff) (SCREEN*, const chtype); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(slk_attron) (SCREEN*, const chtype); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(slk_attrset) (SCREEN*, const chtype); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(attr_t) NCURSES_SP_NAME(slk_attr) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(slk_attr_set) (SCREEN*, const attr_t, short, void*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(slk_clear) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(slk_color) (SCREEN*, short); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(slk_init) (SCREEN*, int); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(char *) NCURSES_SP_NAME(slk_label) (SCREEN*, int); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(slk_noutrefresh) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(slk_refresh) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(slk_restore) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(slk_set) (SCREEN*, int, const char *, int); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(slk_touch) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(start_color) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(chtype) NCURSES_SP_NAME(termattrs) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(char *) NCURSES_SP_NAME(termname) (SCREEN*); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(typeahead) (SCREEN*, int); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(ungetch) (SCREEN*, int); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(void) NCURSES_SP_NAME(use_env) (SCREEN*, bool); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(vidattr) (SCREEN*, chtype); /* implemented:SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(vidputs) (SCREEN*, chtype, NCURSES_SP_OUTC); /* implemented:SP_FUNC */ -#if 1 -extern NCURSES_EXPORT(char *) NCURSES_SP_NAME(keybound) (SCREEN*, int, int); /* implemented:EXT_SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(assume_default_colors) (SCREEN*, int, int); /* implemented:EXT_SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(define_key) (SCREEN*, const char *, int); /* implemented:EXT_SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(get_escdelay) (SCREEN*); /* implemented:EXT_SP_FUNC */ -extern NCURSES_EXPORT(bool) NCURSES_SP_NAME(is_term_resized) (SCREEN*, int, int); /* implemented:EXT_SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(key_defined) (SCREEN*, const char *); /* implemented:EXT_SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(keyok) (SCREEN*, int, bool); /* implemented:EXT_SP_FUNC */ -extern NCURSES_EXPORT(void) NCURSES_SP_NAME(nofilter) (SCREEN*); /* implemented */ /* implemented:EXT_SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(resize_term) (SCREEN*, int, int); /* implemented:EXT_SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(resizeterm) (SCREEN*, int, int); /* implemented:EXT_SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(set_escdelay) (SCREEN*, int); /* implemented:EXT_SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(set_tabsize) (SCREEN*, int); /* implemented:EXT_SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(use_default_colors) (SCREEN*); /* implemented:EXT_SP_FUNC */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(use_legacy_coding) (SCREEN*, int); /* implemented:EXT_SP_FUNC */ -#endif -#else -#undef NCURSES_SP_FUNCS -#define NCURSES_SP_FUNCS 0 -#define NCURSES_SP_NAME(name) name -#define NCURSES_SP_OUTC NCURSES_OUTC -#endif - -/* attributes */ - -#define NCURSES_ATTR_SHIFT 8 -#define NCURSES_BITS(mask,shift) ((mask) << ((shift) + NCURSES_ATTR_SHIFT)) - -#define A_NORMAL (1UL - 1UL) -#define A_ATTRIBUTES NCURSES_BITS(~(1UL - 1UL),0) -#define A_CHARTEXT (NCURSES_BITS(1UL,0) - 1UL) -#define A_COLOR NCURSES_BITS(((1UL) << 8) - 1UL,0) -#define A_STANDOUT NCURSES_BITS(1UL,8) -#define A_UNDERLINE NCURSES_BITS(1UL,9) -#define A_REVERSE NCURSES_BITS(1UL,10) -#define A_BLINK NCURSES_BITS(1UL,11) -#define A_DIM NCURSES_BITS(1UL,12) -#define A_BOLD NCURSES_BITS(1UL,13) -#define A_ALTCHARSET NCURSES_BITS(1UL,14) -#define A_INVIS NCURSES_BITS(1UL,15) -#define A_PROTECT NCURSES_BITS(1UL,16) -#define A_HORIZONTAL NCURSES_BITS(1UL,17) -#define A_LEFT NCURSES_BITS(1UL,18) -#define A_LOW NCURSES_BITS(1UL,19) -#define A_RIGHT NCURSES_BITS(1UL,20) -#define A_TOP NCURSES_BITS(1UL,21) -#define A_VERTICAL NCURSES_BITS(1UL,22) - -/* - * Most of the pseudo functions are macros that either provide compatibility - * with older versions of curses, or provide inline functionality to improve - * performance. - */ - -/* - * These pseudo functions are always implemented as macros: - */ - -#define getyx(win,y,x) (y = getcury(win), x = getcurx(win)) -#define getbegyx(win,y,x) (y = getbegy(win), x = getbegx(win)) -#define getmaxyx(win,y,x) (y = getmaxy(win), x = getmaxx(win)) -#define getparyx(win,y,x) (y = getpary(win), x = getparx(win)) - -#define getsyx(y,x) do { if (newscr) { \ - if (is_leaveok(newscr)) \ - (y) = (x) = -1; \ - else \ - getyx(newscr,(y), (x)); \ - } \ - } while(0) - -#define setsyx(y,x) do { if (newscr) { \ - if ((y) == -1 && (x) == -1) \ - leaveok(newscr, TRUE); \ - else { \ - leaveok(newscr, FALSE); \ - wmove(newscr, (y), (x)); \ - } \ - } \ - } while(0) - -#ifndef NCURSES_NOMACROS - -/* - * These miscellaneous pseudo functions are provided for compatibility: - */ - -#define wgetstr(w, s) wgetnstr(w, s, -1) -#define getnstr(s, n) wgetnstr(stdscr, s, n) - -#define setterm(term) setupterm(term, 1, (int *)0) - -#define fixterm() reset_prog_mode() -#define resetterm() reset_shell_mode() -#define saveterm() def_prog_mode() -#define crmode() cbreak() -#define nocrmode() nocbreak() -#define gettmode() - -/* It seems older SYSV curses versions define these */ -#if !NCURSES_OPAQUE -#define getattrs(win) NCURSES_CAST(int, (win) ? (win)->_attrs : A_NORMAL) -#define getcurx(win) ((win) ? (win)->_curx : ERR) -#define getcury(win) ((win) ? (win)->_cury : ERR) -#define getbegx(win) ((win) ? (win)->_begx : ERR) -#define getbegy(win) ((win) ? (win)->_begy : ERR) -#define getmaxx(win) ((win) ? ((win)->_maxx + 1) : ERR) -#define getmaxy(win) ((win) ? ((win)->_maxy + 1) : ERR) -#define getparx(win) ((win) ? (win)->_parx : ERR) -#define getpary(win) ((win) ? (win)->_pary : ERR) -#endif /* NCURSES_OPAQUE */ - -#define wstandout(win) (wattrset(win,A_STANDOUT)) -#define wstandend(win) (wattrset(win,A_NORMAL)) - -#define wattron(win,at) wattr_on(win, NCURSES_CAST(attr_t, at), NULL) -#define wattroff(win,at) wattr_off(win, NCURSES_CAST(attr_t, at), NULL) - -#if !NCURSES_OPAQUE -#if defined(NCURSES_WIDECHAR) && 0 -#define wattrset(win,at) ((win) \ - ? ((win)->_color = PAIR_NUMBER(at), \ - (win)->_attrs = NCURSES_CAST(attr_t, at), \ - OK) \ - : ERR) -#else -#define wattrset(win,at) ((win) \ - ? ((win)->_attrs = NCURSES_CAST(attr_t, at), \ - OK) \ - : ERR) -#endif -#endif /* NCURSES_OPAQUE */ - -#define scroll(win) wscrl(win,1) - -#define touchwin(win) wtouchln((win), 0, getmaxy(win), 1) -#define touchline(win, s, c) wtouchln((win), s, c, 1) -#define untouchwin(win) wtouchln((win), 0, getmaxy(win), 0) - -#define box(win, v, h) wborder(win, v, v, h, h, 0, 0, 0, 0) -#define border(ls, rs, ts, bs, tl, tr, bl, br) wborder(stdscr, ls, rs, ts, bs, tl, tr, bl, br) -#define hline(ch, n) whline(stdscr, ch, n) -#define vline(ch, n) wvline(stdscr, ch, n) - -#define winstr(w, s) winnstr(w, s, -1) -#define winchstr(w, s) winchnstr(w, s, -1) -#define winsstr(w, s) winsnstr(w, s, -1) - -#if !NCURSES_OPAQUE -#define redrawwin(win) wredrawln(win, 0, (win)->_maxy+1) -#endif /* NCURSES_OPAQUE */ - -#define waddstr(win,str) waddnstr(win,str,-1) -#define waddchstr(win,str) waddchnstr(win,str,-1) - -/* - * These apply to the first 256 color pairs. - */ -#define COLOR_PAIR(n) NCURSES_BITS(n, 0) -#define PAIR_NUMBER(a) (NCURSES_CAST(int,((NCURSES_CAST(unsigned long,a) & A_COLOR) >> NCURSES_ATTR_SHIFT))) - -/* - * pseudo functions for standard screen - */ - -#define addch(ch) waddch(stdscr,ch) -#define addchnstr(str,n) waddchnstr(stdscr,str,n) -#define addchstr(str) waddchstr(stdscr,str) -#define addnstr(str,n) waddnstr(stdscr,str,n) -#define addstr(str) waddnstr(stdscr,str,-1) -#define attroff(at) wattroff(stdscr,at) -#define attron(at) wattron(stdscr,at) -#define attrset(at) wattrset(stdscr,at) -#define attr_get(ap,cp,o) wattr_get(stdscr,ap,cp,o) -#define attr_off(a,o) wattr_off(stdscr,a,o) -#define attr_on(a,o) wattr_on(stdscr,a,o) -#define attr_set(a,c,o) wattr_set(stdscr,a,c,o) -#define bkgd(ch) wbkgd(stdscr,ch) -#define bkgdset(ch) wbkgdset(stdscr,ch) -#define chgat(n,a,c,o) wchgat(stdscr,n,a,c,o) -#define clear() wclear(stdscr) -#define clrtobot() wclrtobot(stdscr) -#define clrtoeol() wclrtoeol(stdscr) -#define color_set(c,o) wcolor_set(stdscr,c,o) -#define delch() wdelch(stdscr) -#define deleteln() winsdelln(stdscr,-1) -#define echochar(c) wechochar(stdscr,c) -#define erase() werase(stdscr) -#define getch() wgetch(stdscr) -#define getstr(str) wgetstr(stdscr,str) -#define inch() winch(stdscr) -#define inchnstr(s,n) winchnstr(stdscr,s,n) -#define inchstr(s) winchstr(stdscr,s) -#define innstr(s,n) winnstr(stdscr,s,n) -#define insch(c) winsch(stdscr,c) -#define insdelln(n) winsdelln(stdscr,n) -#define insertln() winsdelln(stdscr,1) -#define insnstr(s,n) winsnstr(stdscr,s,n) -#define insstr(s) winsstr(stdscr,s) -#define instr(s) winstr(stdscr,s) -#define move(y,x) wmove(stdscr,y,x) -#define refresh() wrefresh(stdscr) -#define scrl(n) wscrl(stdscr,n) -#define setscrreg(t,b) wsetscrreg(stdscr,t,b) -#define standend() wstandend(stdscr) -#define standout() wstandout(stdscr) -#define timeout(delay) wtimeout(stdscr,delay) -#define wdeleteln(win) winsdelln(win,-1) -#define winsertln(win) winsdelln(win,1) - -/* - * mv functions - */ - -#define mvwaddch(win,y,x,ch) (wmove(win,y,x) == ERR ? ERR : waddch(win,ch)) -#define mvwaddchnstr(win,y,x,str,n) (wmove(win,y,x) == ERR ? ERR : waddchnstr(win,str,n)) -#define mvwaddchstr(win,y,x,str) (wmove(win,y,x) == ERR ? ERR : waddchnstr(win,str,-1)) -#define mvwaddnstr(win,y,x,str,n) (wmove(win,y,x) == ERR ? ERR : waddnstr(win,str,n)) -#define mvwaddstr(win,y,x,str) (wmove(win,y,x) == ERR ? ERR : waddnstr(win,str,-1)) -#define mvwdelch(win,y,x) (wmove(win,y,x) == ERR ? ERR : wdelch(win)) -#define mvwchgat(win,y,x,n,a,c,o) (wmove(win,y,x) == ERR ? ERR : wchgat(win,n,a,c,o)) -#define mvwgetch(win,y,x) (wmove(win,y,x) == ERR ? ERR : wgetch(win)) -#define mvwgetnstr(win,y,x,str,n) (wmove(win,y,x) == ERR ? ERR : wgetnstr(win,str,n)) -#define mvwgetstr(win,y,x,str) (wmove(win,y,x) == ERR ? ERR : wgetstr(win,str)) -#define mvwhline(win,y,x,c,n) (wmove(win,y,x) == ERR ? ERR : whline(win,c,n)) -#define mvwinch(win,y,x) (wmove(win,y,x) == ERR ? NCURSES_CAST(chtype, ERR) : winch(win)) -#define mvwinchnstr(win,y,x,s,n) (wmove(win,y,x) == ERR ? ERR : winchnstr(win,s,n)) -#define mvwinchstr(win,y,x,s) (wmove(win,y,x) == ERR ? ERR : winchstr(win,s)) -#define mvwinnstr(win,y,x,s,n) (wmove(win,y,x) == ERR ? ERR : winnstr(win,s,n)) -#define mvwinsch(win,y,x,c) (wmove(win,y,x) == ERR ? ERR : winsch(win,c)) -#define mvwinsnstr(win,y,x,s,n) (wmove(win,y,x) == ERR ? ERR : winsnstr(win,s,n)) -#define mvwinsstr(win,y,x,s) (wmove(win,y,x) == ERR ? ERR : winsstr(win,s)) -#define mvwinstr(win,y,x,s) (wmove(win,y,x) == ERR ? ERR : winstr(win,s)) -#define mvwvline(win,y,x,c,n) (wmove(win,y,x) == ERR ? ERR : wvline(win,c,n)) - -#define mvaddch(y,x,ch) mvwaddch(stdscr,y,x,ch) -#define mvaddchnstr(y,x,str,n) mvwaddchnstr(stdscr,y,x,str,n) -#define mvaddchstr(y,x,str) mvwaddchstr(stdscr,y,x,str) -#define mvaddnstr(y,x,str,n) mvwaddnstr(stdscr,y,x,str,n) -#define mvaddstr(y,x,str) mvwaddstr(stdscr,y,x,str) -#define mvchgat(y,x,n,a,c,o) mvwchgat(stdscr,y,x,n,a,c,o) -#define mvdelch(y,x) mvwdelch(stdscr,y,x) -#define mvgetch(y,x) mvwgetch(stdscr,y,x) -#define mvgetnstr(y,x,str,n) mvwgetnstr(stdscr,y,x,str,n) -#define mvgetstr(y,x,str) mvwgetstr(stdscr,y,x,str) -#define mvhline(y,x,c,n) mvwhline(stdscr,y,x,c,n) -#define mvinch(y,x) mvwinch(stdscr,y,x) -#define mvinchnstr(y,x,s,n) mvwinchnstr(stdscr,y,x,s,n) -#define mvinchstr(y,x,s) mvwinchstr(stdscr,y,x,s) -#define mvinnstr(y,x,s,n) mvwinnstr(stdscr,y,x,s,n) -#define mvinsch(y,x,c) mvwinsch(stdscr,y,x,c) -#define mvinsnstr(y,x,s,n) mvwinsnstr(stdscr,y,x,s,n) -#define mvinsstr(y,x,s) mvwinsstr(stdscr,y,x,s) -#define mvinstr(y,x,s) mvwinstr(stdscr,y,x,s) -#define mvvline(y,x,c,n) mvwvline(stdscr,y,x,c,n) - -/* - * Some wide-character functions can be implemented without the extensions. - */ -#if !NCURSES_OPAQUE -#define getbkgd(win) ((win)->_bkgd) -#endif /* NCURSES_OPAQUE */ - -#define slk_attr_off(a,v) ((v) ? ERR : slk_attroff(a)) -#define slk_attr_on(a,v) ((v) ? ERR : slk_attron(a)) - -#if !NCURSES_OPAQUE -#if defined(NCURSES_WIDECHAR) && 0 -#define wattr_set(win,a,p,opts) ((win)->_attrs = ((a) & ~A_COLOR), \ - (win)->_color = (p), \ - OK) -#define wattr_get(win,a,p,opts) ((void)((a) != (void *)0 && (*(a) = (win)->_attrs)), \ - (void)((p) != (void *)0 && (*(p) = (short)(win)->_color)), \ - OK) -#else -#define wattr_set(win,a,p,opts) ((win)->_attrs = (((a) & ~A_COLOR) | (attr_t)COLOR_PAIR(p)), OK) -#define wattr_get(win,a,p,opts) ((void)((a) != (void *)0 && (*(a) = (win)->_attrs)), \ - (void)((p) != (void *)0 && (*(p) = (short)PAIR_NUMBER((win)->_attrs))), \ - OK) -#endif -#endif /* NCURSES_OPAQUE */ - -/* - * X/Open curses deprecates SVr4 vwprintw/vwscanw, which are supposed to use - * varargs.h. It adds new calls vw_printw/vw_scanw, which are supposed to - * use POSIX stdarg.h. The ncurses versions of vwprintw/vwscanw already - * use stdarg.h, so... - */ -#define vw_printw vwprintw -#define vw_scanw vwscanw - -/* - * Export fallback function for use in C++ binding. - */ -#if !1 -#define vsscanf(a,b,c) _nc_vsscanf(a,b,c) -NCURSES_EXPORT(int) vsscanf(const char *, const char *, va_list); -#endif - -/* - * These macros are extensions - not in X/Open Curses. - */ -#if 1 -#if !NCURSES_OPAQUE -#define is_cleared(win) ((win) ? (win)->_clear : FALSE) -#define is_idcok(win) ((win) ? (win)->_idcok : FALSE) -#define is_idlok(win) ((win) ? (win)->_idlok : FALSE) -#define is_immedok(win) ((win) ? (win)->_immed : FALSE) -#define is_keypad(win) ((win) ? (win)->_use_keypad : FALSE) -#define is_leaveok(win) ((win) ? (win)->_leaveok : FALSE) -#define is_nodelay(win) ((win) ? ((win)->_delay == 0) : FALSE) -#define is_notimeout(win) ((win) ? (win)->_notimeout : FALSE) -#define is_pad(win) ((win) ? ((win)->_flags & _ISPAD) != 0 : FALSE) -#define is_scrollok(win) ((win) ? (win)->_scroll : FALSE) -#define is_subwin(win) ((win) ? ((win)->_flags & _SUBWIN) != 0 : FALSE) -#define is_syncok(win) ((win) ? (win)->_sync : FALSE) -#define wgetparent(win) ((win) ? (win)->_parent : 0) -#define wgetscrreg(win,t,b) ((win) ? (*(t) = (win)->_regtop, *(b) = (win)->_regbottom, OK) : ERR) -#endif -#endif - -#endif /* NCURSES_NOMACROS */ - -/* - * Public variables. - * - * Notes: - * a. ESCDELAY was an undocumented feature under AIX curses. - * It gives the ESC expire time in milliseconds. - * b. ttytype is needed for backward compatibility - */ -#if NCURSES_REENTRANT - -NCURSES_WRAPPED_VAR(WINDOW *, curscr); -NCURSES_WRAPPED_VAR(WINDOW *, newscr); -NCURSES_WRAPPED_VAR(WINDOW *, stdscr); -NCURSES_WRAPPED_VAR(char *, ttytype); -NCURSES_WRAPPED_VAR(int, COLORS); -NCURSES_WRAPPED_VAR(int, COLOR_PAIRS); -NCURSES_WRAPPED_VAR(int, COLS); -NCURSES_WRAPPED_VAR(int, ESCDELAY); -NCURSES_WRAPPED_VAR(int, LINES); -NCURSES_WRAPPED_VAR(int, TABSIZE); - -#define curscr NCURSES_PUBLIC_VAR(curscr()) -#define newscr NCURSES_PUBLIC_VAR(newscr()) -#define stdscr NCURSES_PUBLIC_VAR(stdscr()) -#define ttytype NCURSES_PUBLIC_VAR(ttytype()) -#define COLORS NCURSES_PUBLIC_VAR(COLORS()) -#define COLOR_PAIRS NCURSES_PUBLIC_VAR(COLOR_PAIRS()) -#define COLS NCURSES_PUBLIC_VAR(COLS()) -#define ESCDELAY NCURSES_PUBLIC_VAR(ESCDELAY()) -#define LINES NCURSES_PUBLIC_VAR(LINES()) -#define TABSIZE NCURSES_PUBLIC_VAR(TABSIZE()) - -#else - -extern NCURSES_EXPORT_VAR(WINDOW *) curscr; -extern NCURSES_EXPORT_VAR(WINDOW *) newscr; -extern NCURSES_EXPORT_VAR(WINDOW *) stdscr; -extern NCURSES_EXPORT_VAR(char) ttytype[]; -extern NCURSES_EXPORT_VAR(int) COLORS; -extern NCURSES_EXPORT_VAR(int) COLOR_PAIRS; -extern NCURSES_EXPORT_VAR(int) COLS; -extern NCURSES_EXPORT_VAR(int) ESCDELAY; -extern NCURSES_EXPORT_VAR(int) LINES; -extern NCURSES_EXPORT_VAR(int) TABSIZE; - -#endif - -/* - * Pseudo-character tokens outside ASCII range. The curses wgetch() function - * will return any given one of these only if the corresponding k- capability - * is defined in your terminal's terminfo entry. - * - * Some keys (KEY_A1, etc) are arranged like this: - * a1 up a3 - * left b2 right - * c1 down c3 - * - * A few key codes do not depend upon the terminfo entry. - */ -#define KEY_CODE_YES 0400 /* A wchar_t contains a key code */ -#define KEY_MIN 0401 /* Minimum curses key */ -#define KEY_BREAK 0401 /* Break key (unreliable) */ -#define KEY_SRESET 0530 /* Soft (partial) reset (unreliable) */ -#define KEY_RESET 0531 /* Reset or hard reset (unreliable) */ -/* - * These definitions were generated by ./MKkey_defs.sh ./Caps - */ -#define KEY_DOWN 0402 /* down-arrow key */ -#define KEY_UP 0403 /* up-arrow key */ -#define KEY_LEFT 0404 /* left-arrow key */ -#define KEY_RIGHT 0405 /* right-arrow key */ -#define KEY_HOME 0406 /* home key */ -#define KEY_BACKSPACE 0407 /* backspace key */ -#define KEY_F0 0410 /* Function keys. Space for 64 */ -#define KEY_F(n) (KEY_F0+(n)) /* Value of function key n */ -#define KEY_DL 0510 /* delete-line key */ -#define KEY_IL 0511 /* insert-line key */ -#define KEY_DC 0512 /* delete-character key */ -#define KEY_IC 0513 /* insert-character key */ -#define KEY_EIC 0514 /* sent by rmir or smir in insert mode */ -#define KEY_CLEAR 0515 /* clear-screen or erase key */ -#define KEY_EOS 0516 /* clear-to-end-of-screen key */ -#define KEY_EOL 0517 /* clear-to-end-of-line key */ -#define KEY_SF 0520 /* scroll-forward key */ -#define KEY_SR 0521 /* scroll-backward key */ -#define KEY_NPAGE 0522 /* next-page key */ -#define KEY_PPAGE 0523 /* previous-page key */ -#define KEY_STAB 0524 /* set-tab key */ -#define KEY_CTAB 0525 /* clear-tab key */ -#define KEY_CATAB 0526 /* clear-all-tabs key */ -#define KEY_ENTER 0527 /* enter/send key */ -#define KEY_PRINT 0532 /* print key */ -#define KEY_LL 0533 /* lower-left key (home down) */ -#define KEY_A1 0534 /* upper left of keypad */ -#define KEY_A3 0535 /* upper right of keypad */ -#define KEY_B2 0536 /* center of keypad */ -#define KEY_C1 0537 /* lower left of keypad */ -#define KEY_C3 0540 /* lower right of keypad */ -#define KEY_BTAB 0541 /* back-tab key */ -#define KEY_BEG 0542 /* begin key */ -#define KEY_CANCEL 0543 /* cancel key */ -#define KEY_CLOSE 0544 /* close key */ -#define KEY_COMMAND 0545 /* command key */ -#define KEY_COPY 0546 /* copy key */ -#define KEY_CREATE 0547 /* create key */ -#define KEY_END 0550 /* end key */ -#define KEY_EXIT 0551 /* exit key */ -#define KEY_FIND 0552 /* find key */ -#define KEY_HELP 0553 /* help key */ -#define KEY_MARK 0554 /* mark key */ -#define KEY_MESSAGE 0555 /* message key */ -#define KEY_MOVE 0556 /* move key */ -#define KEY_NEXT 0557 /* next key */ -#define KEY_OPEN 0560 /* open key */ -#define KEY_OPTIONS 0561 /* options key */ -#define KEY_PREVIOUS 0562 /* previous key */ -#define KEY_REDO 0563 /* redo key */ -#define KEY_REFERENCE 0564 /* reference key */ -#define KEY_REFRESH 0565 /* refresh key */ -#define KEY_REPLACE 0566 /* replace key */ -#define KEY_RESTART 0567 /* restart key */ -#define KEY_RESUME 0570 /* resume key */ -#define KEY_SAVE 0571 /* save key */ -#define KEY_SBEG 0572 /* shifted begin key */ -#define KEY_SCANCEL 0573 /* shifted cancel key */ -#define KEY_SCOMMAND 0574 /* shifted command key */ -#define KEY_SCOPY 0575 /* shifted copy key */ -#define KEY_SCREATE 0576 /* shifted create key */ -#define KEY_SDC 0577 /* shifted delete-character key */ -#define KEY_SDL 0600 /* shifted delete-line key */ -#define KEY_SELECT 0601 /* select key */ -#define KEY_SEND 0602 /* shifted end key */ -#define KEY_SEOL 0603 /* shifted clear-to-end-of-line key */ -#define KEY_SEXIT 0604 /* shifted exit key */ -#define KEY_SFIND 0605 /* shifted find key */ -#define KEY_SHELP 0606 /* shifted help key */ -#define KEY_SHOME 0607 /* shifted home key */ -#define KEY_SIC 0610 /* shifted insert-character key */ -#define KEY_SLEFT 0611 /* shifted left-arrow key */ -#define KEY_SMESSAGE 0612 /* shifted message key */ -#define KEY_SMOVE 0613 /* shifted move key */ -#define KEY_SNEXT 0614 /* shifted next key */ -#define KEY_SOPTIONS 0615 /* shifted options key */ -#define KEY_SPREVIOUS 0616 /* shifted previous key */ -#define KEY_SPRINT 0617 /* shifted print key */ -#define KEY_SREDO 0620 /* shifted redo key */ -#define KEY_SREPLACE 0621 /* shifted replace key */ -#define KEY_SRIGHT 0622 /* shifted right-arrow key */ -#define KEY_SRSUME 0623 /* shifted resume key */ -#define KEY_SSAVE 0624 /* shifted save key */ -#define KEY_SSUSPEND 0625 /* shifted suspend key */ -#define KEY_SUNDO 0626 /* shifted undo key */ -#define KEY_SUSPEND 0627 /* suspend key */ -#define KEY_UNDO 0630 /* undo key */ -#define KEY_MOUSE 0631 /* Mouse event has occurred */ -#define KEY_RESIZE 0632 /* Terminal resize event */ -#define KEY_EVENT 0633 /* We were interrupted by an event */ - -#define KEY_MAX 0777 /* Maximum key value is 0633 */ -/* $Id: curses.tail,v 1.20 2010/03/28 19:10:55 tom Exp $ */ -/* - * vile:cmode: - * This file is part of ncurses, designed to be appended after curses.h.in - * (see that file for the relevant copyright). - */ - -/* mouse interface */ - -#if NCURSES_MOUSE_VERSION > 1 -#define NCURSES_MOUSE_MASK(b,m) ((m) << (((b) - 1) * 5)) -#else -#define NCURSES_MOUSE_MASK(b,m) ((m) << (((b) - 1) * 6)) -#endif - -#define NCURSES_BUTTON_RELEASED 001L -#define NCURSES_BUTTON_PRESSED 002L -#define NCURSES_BUTTON_CLICKED 004L -#define NCURSES_DOUBLE_CLICKED 010L -#define NCURSES_TRIPLE_CLICKED 020L -#define NCURSES_RESERVED_EVENT 040L - -/* event masks */ -#define BUTTON1_RELEASED NCURSES_MOUSE_MASK(1, NCURSES_BUTTON_RELEASED) -#define BUTTON1_PRESSED NCURSES_MOUSE_MASK(1, NCURSES_BUTTON_PRESSED) -#define BUTTON1_CLICKED NCURSES_MOUSE_MASK(1, NCURSES_BUTTON_CLICKED) -#define BUTTON1_DOUBLE_CLICKED NCURSES_MOUSE_MASK(1, NCURSES_DOUBLE_CLICKED) -#define BUTTON1_TRIPLE_CLICKED NCURSES_MOUSE_MASK(1, NCURSES_TRIPLE_CLICKED) - -#define BUTTON2_RELEASED NCURSES_MOUSE_MASK(2, NCURSES_BUTTON_RELEASED) -#define BUTTON2_PRESSED NCURSES_MOUSE_MASK(2, NCURSES_BUTTON_PRESSED) -#define BUTTON2_CLICKED NCURSES_MOUSE_MASK(2, NCURSES_BUTTON_CLICKED) -#define BUTTON2_DOUBLE_CLICKED NCURSES_MOUSE_MASK(2, NCURSES_DOUBLE_CLICKED) -#define BUTTON2_TRIPLE_CLICKED NCURSES_MOUSE_MASK(2, NCURSES_TRIPLE_CLICKED) - -#define BUTTON3_RELEASED NCURSES_MOUSE_MASK(3, NCURSES_BUTTON_RELEASED) -#define BUTTON3_PRESSED NCURSES_MOUSE_MASK(3, NCURSES_BUTTON_PRESSED) -#define BUTTON3_CLICKED NCURSES_MOUSE_MASK(3, NCURSES_BUTTON_CLICKED) -#define BUTTON3_DOUBLE_CLICKED NCURSES_MOUSE_MASK(3, NCURSES_DOUBLE_CLICKED) -#define BUTTON3_TRIPLE_CLICKED NCURSES_MOUSE_MASK(3, NCURSES_TRIPLE_CLICKED) - -#define BUTTON4_RELEASED NCURSES_MOUSE_MASK(4, NCURSES_BUTTON_RELEASED) -#define BUTTON4_PRESSED NCURSES_MOUSE_MASK(4, NCURSES_BUTTON_PRESSED) -#define BUTTON4_CLICKED NCURSES_MOUSE_MASK(4, NCURSES_BUTTON_CLICKED) -#define BUTTON4_DOUBLE_CLICKED NCURSES_MOUSE_MASK(4, NCURSES_DOUBLE_CLICKED) -#define BUTTON4_TRIPLE_CLICKED NCURSES_MOUSE_MASK(4, NCURSES_TRIPLE_CLICKED) - -/* - * In 32 bits the version-1 scheme does not provide enough space for a 5th - * button, unless we choose to change the ABI by omitting the reserved-events. - */ -#if NCURSES_MOUSE_VERSION > 1 - -#define BUTTON5_RELEASED NCURSES_MOUSE_MASK(5, NCURSES_BUTTON_RELEASED) -#define BUTTON5_PRESSED NCURSES_MOUSE_MASK(5, NCURSES_BUTTON_PRESSED) -#define BUTTON5_CLICKED NCURSES_MOUSE_MASK(5, NCURSES_BUTTON_CLICKED) -#define BUTTON5_DOUBLE_CLICKED NCURSES_MOUSE_MASK(5, NCURSES_DOUBLE_CLICKED) -#define BUTTON5_TRIPLE_CLICKED NCURSES_MOUSE_MASK(5, NCURSES_TRIPLE_CLICKED) - -#define BUTTON_CTRL NCURSES_MOUSE_MASK(6, 0001L) -#define BUTTON_SHIFT NCURSES_MOUSE_MASK(6, 0002L) -#define BUTTON_ALT NCURSES_MOUSE_MASK(6, 0004L) -#define REPORT_MOUSE_POSITION NCURSES_MOUSE_MASK(6, 0010L) - -#else - -#define BUTTON1_RESERVED_EVENT NCURSES_MOUSE_MASK(1, NCURSES_RESERVED_EVENT) -#define BUTTON2_RESERVED_EVENT NCURSES_MOUSE_MASK(2, NCURSES_RESERVED_EVENT) -#define BUTTON3_RESERVED_EVENT NCURSES_MOUSE_MASK(3, NCURSES_RESERVED_EVENT) -#define BUTTON4_RESERVED_EVENT NCURSES_MOUSE_MASK(4, NCURSES_RESERVED_EVENT) - -#define BUTTON_CTRL NCURSES_MOUSE_MASK(5, 0001L) -#define BUTTON_SHIFT NCURSES_MOUSE_MASK(5, 0002L) -#define BUTTON_ALT NCURSES_MOUSE_MASK(5, 0004L) -#define REPORT_MOUSE_POSITION NCURSES_MOUSE_MASK(5, 0010L) - -#endif - -#define ALL_MOUSE_EVENTS (REPORT_MOUSE_POSITION - 1) - -/* macros to extract single event-bits from masks */ -#define BUTTON_RELEASE(e, x) ((e) & NCURSES_MOUSE_MASK(x, 001)) -#define BUTTON_PRESS(e, x) ((e) & NCURSES_MOUSE_MASK(x, 002)) -#define BUTTON_CLICK(e, x) ((e) & NCURSES_MOUSE_MASK(x, 004)) -#define BUTTON_DOUBLE_CLICK(e, x) ((e) & NCURSES_MOUSE_MASK(x, 010)) -#define BUTTON_TRIPLE_CLICK(e, x) ((e) & NCURSES_MOUSE_MASK(x, 020)) -#define BUTTON_RESERVED_EVENT(e, x) ((e) & NCURSES_MOUSE_MASK(x, 040)) - -typedef struct -{ - short id; /* ID to distinguish multiple devices */ - int x, y, z; /* event coordinates (character-cell) */ - mmask_t bstate; /* button state bits */ -} -MEVENT; - -extern NCURSES_EXPORT(bool) has_mouse(void); -extern NCURSES_EXPORT(int) getmouse (MEVENT *); -extern NCURSES_EXPORT(int) ungetmouse (MEVENT *); -extern NCURSES_EXPORT(mmask_t) mousemask (mmask_t, mmask_t *); -extern NCURSES_EXPORT(bool) wenclose (const WINDOW *, int, int); -extern NCURSES_EXPORT(int) mouseinterval (int); -extern NCURSES_EXPORT(bool) wmouse_trafo (const WINDOW*, int*, int*, bool); -extern NCURSES_EXPORT(bool) mouse_trafo (int*, int*, bool); /* generated */ - -#if NCURSES_SP_FUNCS -extern NCURSES_EXPORT(bool) NCURSES_SP_NAME(has_mouse) (SCREEN*); -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(getmouse) (SCREEN*, MEVENT *); -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(ungetmouse) (SCREEN*,MEVENT *); -extern NCURSES_EXPORT(mmask_t) NCURSES_SP_NAME(mousemask) (SCREEN*, mmask_t, mmask_t *); -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(mouseinterval) (SCREEN*, int); -#endif - -#define mouse_trafo(y,x,to_screen) wmouse_trafo(stdscr,y,x,to_screen) - -/* other non-XSI functions */ - -extern NCURSES_EXPORT(int) mcprint (char *, int); /* direct data to printer */ -extern NCURSES_EXPORT(int) has_key (int); /* do we have given key? */ - -#if NCURSES_SP_FUNCS -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(has_key) (SCREEN*, int); /* do we have given key? */ -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(mcprint) (SCREEN*, char *, int); /* direct data to printer */ -#endif - -/* Debugging : use with libncurses_g.a */ - -extern NCURSES_EXPORT(void) _tracef (const char *, ...) GCC_PRINTFLIKE(1,2); -extern NCURSES_EXPORT(void) _tracedump (const char *, WINDOW *); -extern NCURSES_EXPORT(char *) _traceattr (attr_t); -extern NCURSES_EXPORT(char *) _traceattr2 (int, chtype); -extern NCURSES_EXPORT(char *) _nc_tracebits (void); -extern NCURSES_EXPORT(char *) _tracechar (int); -extern NCURSES_EXPORT(char *) _tracechtype (chtype); -extern NCURSES_EXPORT(char *) _tracechtype2 (int, chtype); -#ifdef NCURSES_WIDECHAR -#define _tracech_t _tracecchar_t -extern NCURSES_EXPORT(char *) _tracecchar_t (const cchar_t *); -#define _tracech_t2 _tracecchar_t2 -extern NCURSES_EXPORT(char *) _tracecchar_t2 (int, const cchar_t *); -#else -#define _tracech_t _tracechtype -#define _tracech_t2 _tracechtype2 -#endif -extern NCURSES_EXPORT(char *) _tracemouse (const MEVENT *); -extern NCURSES_EXPORT(void) trace (const unsigned int); - -/* trace masks */ -#define TRACE_DISABLE 0x0000 /* turn off tracing */ -#define TRACE_TIMES 0x0001 /* trace user and system times of updates */ -#define TRACE_TPUTS 0x0002 /* trace tputs calls */ -#define TRACE_UPDATE 0x0004 /* trace update actions, old & new screens */ -#define TRACE_MOVE 0x0008 /* trace cursor moves and scrolls */ -#define TRACE_CHARPUT 0x0010 /* trace all character outputs */ -#define TRACE_ORDINARY 0x001F /* trace all update actions */ -#define TRACE_CALLS 0x0020 /* trace all curses calls */ -#define TRACE_VIRTPUT 0x0040 /* trace virtual character puts */ -#define TRACE_IEVENT 0x0080 /* trace low-level input processing */ -#define TRACE_BITS 0x0100 /* trace state of TTY control bits */ -#define TRACE_ICALLS 0x0200 /* trace internal/nested calls */ -#define TRACE_CCALLS 0x0400 /* trace per-character calls */ -#define TRACE_DATABASE 0x0800 /* trace read/write of terminfo/termcap data */ -#define TRACE_ATTRS 0x1000 /* trace attribute updates */ - -#define TRACE_SHIFT 13 /* number of bits in the trace masks */ -#define TRACE_MAXIMUM ((1 << TRACE_SHIFT) - 1) /* maximum trace level */ - -#if defined(TRACE) || defined(NCURSES_TEST) -extern NCURSES_EXPORT_VAR(int) _nc_optimize_enable; /* enable optimizations */ -extern NCURSES_EXPORT(const char *) _nc_visbuf (const char *); -#define OPTIMIZE_MVCUR 0x01 /* cursor movement optimization */ -#define OPTIMIZE_HASHMAP 0x02 /* diff hashing to detect scrolls */ -#define OPTIMIZE_SCROLL 0x04 /* scroll optimization */ -#define OPTIMIZE_ALL 0xff /* enable all optimizations (dflt) */ -#endif - -#include - -#ifdef __cplusplus - -#ifndef NCURSES_NOMACROS - -/* these names conflict with STL */ -#undef box -#undef clear -#undef erase -#undef move -#undef refresh - -#endif /* NCURSES_NOMACROS */ - -} -#endif - -#endif /* __NCURSES_H */ diff --git a/windows/ncurses/include/ncurses/ncurses_dll.h b/windows/ncurses/include/ncurses/ncurses_dll.h deleted file mode 100644 index 6974fcba0..000000000 --- a/windows/ncurses/include/ncurses/ncurses_dll.h +++ /dev/null @@ -1,86 +0,0 @@ -/**************************************************************************** - * Copyright (c) 1998-2007,2009 Free Software Foundation, Inc. * - * * - * Permission is hereby granted, free of charge, to any person obtaining a * - * copy of this software and associated documentation files (the * - * "Software"), to deal in the Software without restriction, including * - * without limitation the rights to use, copy, modify, merge, publish, * - * distribute, distribute with modifications, sublicense, and/or sell * - * copies of the Software, and to permit persons to whom the Software is * - * furnished to do so, subject to the following conditions: * - * * - * The above copyright notice and this permission notice shall be included * - * in all copies or substantial portions of the Software. * - * * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * - * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * - * THE USE OR OTHER DEALINGS IN THE SOFTWARE. * - * * - * Except as contained in this notice, the name(s) of the above copyright * - * holders shall not be used in advertising or otherwise to promote the * - * sale, use or other dealings in this Software without prior written * - * authorization. * - ****************************************************************************/ -/* $Id: ncurses_dll.h.in,v 1.8 2009/04/04 22:26:27 tom Exp $ */ - -#ifndef NCURSES_DLL_H_incl -#define NCURSES_DLL_H_incl 1 - -/* - * For reentrant code, we map the various global variables into SCREEN by - * using functions to access them. - */ -#define NCURSES_PUBLIC_VAR(name) _nc_##name -#define NCURSES_WRAPPED_VAR(type,name) extern type NCURSES_PUBLIC_VAR(name)(void) - -/* no longer needed on cygwin or mingw, thanks to auto-import */ -/* but this structure may be useful at some point for an MSVC build */ -/* so, for now unconditionally define the important flags */ -/* "the right way" for proper static and dll+auto-import behavior */ -#undef NCURSES_DLL -#define NCURSES_STATIC - -#if defined(__CYGWIN__) || defined(__MINGW32__) -# if defined(NCURSES_DLL) -# if defined(NCURSES_STATIC) -# undef NCURSES_STATIC -# endif -# endif -# undef NCURSES_IMPEXP -# undef NCURSES_API -# undef NCURSES_EXPORT -# undef NCURSES_EXPORT_VAR -# if defined(NCURSES_DLL) -/* building a DLL */ -# define NCURSES_IMPEXP __declspec(dllexport) -# elif defined(NCURSES_STATIC) -/* building or linking to a static library */ -# define NCURSES_IMPEXP /* nothing */ -# else -/* linking to the DLL */ -# define NCURSES_IMPEXP __declspec(dllimport) -# endif -# define NCURSES_API __cdecl -# define NCURSES_EXPORT(type) NCURSES_IMPEXP type NCURSES_API -# define NCURSES_EXPORT_VAR(type) NCURSES_IMPEXP type -#endif - -/* Take care of non-cygwin platforms */ -#if !defined(NCURSES_IMPEXP) -# define NCURSES_IMPEXP /* nothing */ -#endif -#if !defined(NCURSES_API) -# define NCURSES_API /* nothing */ -#endif -#if !defined(NCURSES_EXPORT) -# define NCURSES_EXPORT(type) NCURSES_IMPEXP type NCURSES_API -#endif -#if !defined(NCURSES_EXPORT_VAR) -# define NCURSES_EXPORT_VAR(type) __declspec(dllimport) type -#endif - -#endif /* NCURSES_DLL_H_incl */ diff --git a/windows/ncurses/include/ncurses/panel.h b/windows/ncurses/include/ncurses/panel.h deleted file mode 100644 index 4d5aca279..000000000 --- a/windows/ncurses/include/ncurses/panel.h +++ /dev/null @@ -1,85 +0,0 @@ -/**************************************************************************** - * Copyright (c) 1998-2006,2009 Free Software Foundation, Inc. * - * * - * Permission is hereby granted, free of charge, to any person obtaining a * - * copy of this software and associated documentation files (the * - * "Software"), to deal in the Software without restriction, including * - * without limitation the rights to use, copy, modify, merge, publish, * - * distribute, distribute with modifications, sublicense, and/or sell * - * copies of the Software, and to permit persons to whom the Software is * - * furnished to do so, subject to the following conditions: * - * * - * The above copyright notice and this permission notice shall be included * - * in all copies or substantial portions of the Software. * - * * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * - * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * - * THE USE OR OTHER DEALINGS IN THE SOFTWARE. * - * * - * Except as contained in this notice, the name(s) of the above copyright * - * holders shall not be used in advertising or otherwise to promote the * - * sale, use or other dealings in this Software without prior written * - * authorization. * - ****************************************************************************/ - -/**************************************************************************** - * Author: Zeyd M. Ben-Halim 1995 * - * and: Eric S. Raymond * - * and: Juergen Pfeifer 1996-1999,2008 * - ****************************************************************************/ - -/* $Id: panel.h,v 1.11 2009/04/11 19:50:40 tom Exp $ */ - -/* panel.h -- interface file for panels library */ - -#ifndef NCURSES_PANEL_H_incl -#define NCURSES_PANEL_H_incl 1 - -#include - -typedef struct panel -{ - WINDOW *win; - struct panel *below; - struct panel *above; - NCURSES_CONST void *user; -} PANEL; - -#if defined(__cplusplus) -extern "C" { -#endif - -extern NCURSES_EXPORT(WINDOW*) panel_window (const PANEL *); -extern NCURSES_EXPORT(void) update_panels (void); -extern NCURSES_EXPORT(int) hide_panel (PANEL *); -extern NCURSES_EXPORT(int) show_panel (PANEL *); -extern NCURSES_EXPORT(int) del_panel (PANEL *); -extern NCURSES_EXPORT(int) top_panel (PANEL *); -extern NCURSES_EXPORT(int) bottom_panel (PANEL *); -extern NCURSES_EXPORT(PANEL*) new_panel (WINDOW *); -extern NCURSES_EXPORT(PANEL*) panel_above (const PANEL *); -extern NCURSES_EXPORT(PANEL*) panel_below (const PANEL *); -extern NCURSES_EXPORT(int) set_panel_userptr (PANEL *, NCURSES_CONST void *); -extern NCURSES_EXPORT(NCURSES_CONST void*) panel_userptr (const PANEL *); -extern NCURSES_EXPORT(int) move_panel (PANEL *, int, int); -extern NCURSES_EXPORT(int) replace_panel (PANEL *,WINDOW *); -extern NCURSES_EXPORT(int) panel_hidden (const PANEL *); - -#if NCURSES_SP_FUNCS -extern NCURSES_EXPORT(PANEL *) ground_panel(SCREEN *); -extern NCURSES_EXPORT(PANEL *) ceiling_panel(SCREEN *); - -extern NCURSES_EXPORT(void) NCURSES_SP_NAME(update_panels) (SCREEN*); -#endif - -#if defined(__cplusplus) -} -#endif - -#endif /* NCURSES_PANEL_H_incl */ - -/* end of panel.h */ diff --git a/windows/ncurses/include/ncurses/term.h b/windows/ncurses/include/ncurses/term.h deleted file mode 100644 index 543a18df8..000000000 --- a/windows/ncurses/include/ncurses/term.h +++ /dev/null @@ -1,834 +0,0 @@ -/**************************************************************************** - * Copyright (c) 1998-2009,2010 Free Software Foundation, Inc. * - * * - * Permission is hereby granted, free of charge, to any person obtaining a * - * copy of this software and associated documentation files (the * - * "Software"), to deal in the Software without restriction, including * - * without limitation the rights to use, copy, modify, merge, publish, * - * distribute, distribute with modifications, sublicense, and/or sell * - * copies of the Software, and to permit persons to whom the Software is * - * furnished to do so, subject to the following conditions: * - * * - * The above copyright notice and this permission notice shall be included * - * in all copies or substantial portions of the Software. * - * * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * - * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * - * THE USE OR OTHER DEALINGS IN THE SOFTWARE. * - * * - * Except as contained in this notice, the name(s) of the above copyright * - * holders shall not be used in advertising or otherwise to promote the * - * sale, use or other dealings in this Software without prior written * - * authorization. * - ****************************************************************************/ - -/****************************************************************************/ -/* Author: Zeyd M. Ben-Halim 1992,1995 */ -/* and: Eric S. Raymond */ -/* and: Thomas E. Dickey 1995-on */ -/****************************************************************************/ - -/* $Id: MKterm.h.awk.in,v 1.58 2010/01/09 19:53:26 tom Exp $ */ - -/* -** term.h -- Definition of struct term -*/ - -#ifndef NCURSES_TERM_H_incl -#define NCURSES_TERM_H_incl 1 - -#undef NCURSES_VERSION -#define NCURSES_VERSION "5.9" - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/* Make this file self-contained by providing defaults for the HAVE_TERMIO[S]_H - * definition (based on the system for which this was configured). - */ - -#undef NCURSES_CONST -#define NCURSES_CONST /*nothing*/ - -#undef NCURSES_SBOOL -#define NCURSES_SBOOL char - -#undef NCURSES_XNAMES -#define NCURSES_XNAMES 1 - -/* We will use these symbols to hide differences between - * termios/termio/sgttyb interfaces. - */ -#undef TTY -#undef SET_TTY -#undef GET_TTY - -/* Assume POSIX termio if we have the header and function */ -/* #if HAVE_TERMIOS_H && HAVE_TCGETATTR */ -#if 0 && 0 - -#undef TERMIOS -#define TERMIOS 1 - -#include -#define TTY struct termios - -#else /* !HAVE_TERMIOS_H */ - -/* #if HAVE_TERMIO_H */ -#if 0 - -#undef TERMIOS -#define TERMIOS 1 - -#include -#define TTY struct termio - -/* Add definitions to make termio look like termios. - * But ifdef it, since there are some implementations - * that try to do this for us in a fake . - */ -#ifndef TCSANOW -#define TCSANOW TCSETA -#endif -#ifndef TCSADRAIN -#define TCSADRAIN TCSETAW -#endif -#ifndef TCSAFLUSH -#define TCSAFLUSH TCSETAF -#endif -#ifndef tcsetattr -#define tcsetattr(fd, cmd, arg) ioctl(fd, cmd, arg) -#endif -#ifndef tcgetattr -#define tcgetattr(fd, arg) ioctl(fd, TCGETA, arg) -#endif -#ifndef cfgetospeed -#define cfgetospeed(t) ((t)->c_cflag & CBAUD) -#endif -#ifndef TCIFLUSH -#define TCIFLUSH 0 -#endif -#ifndef TCOFLUSH -#define TCOFLUSH 1 -#endif -#ifndef TCIOFLUSH -#define TCIOFLUSH 2 -#endif -#ifndef tcflush -#define tcflush(fd, arg) ioctl(fd, TCFLSH, arg) -#endif - -#else /* !HAVE_TERMIO_H */ - -#if __MINGW32__ -# include -# define TTY struct termios -#else -#undef TERMIOS -#include -#include -#define TTY struct sgttyb -#endif /* MINGW32 */ -#endif /* HAVE_TERMIO_H */ - -#endif /* HAVE_TERMIOS_H */ - -#ifdef TERMIOS -#define GET_TTY(fd, buf) tcgetattr(fd, buf) -#define SET_TTY(fd, buf) tcsetattr(fd, TCSADRAIN, buf) -#else -#define GET_TTY(fd, buf) gtty(fd, buf) -#define SET_TTY(fd, buf) stty(fd, buf) -#endif - -#define NAMESIZE 256 - -#define CUR cur_term->type. - -#define auto_left_margin CUR Booleans[0] -#define auto_right_margin CUR Booleans[1] -#define no_esc_ctlc CUR Booleans[2] -#define ceol_standout_glitch CUR Booleans[3] -#define eat_newline_glitch CUR Booleans[4] -#define erase_overstrike CUR Booleans[5] -#define generic_type CUR Booleans[6] -#define hard_copy CUR Booleans[7] -#define has_meta_key CUR Booleans[8] -#define has_status_line CUR Booleans[9] -#define insert_null_glitch CUR Booleans[10] -#define memory_above CUR Booleans[11] -#define memory_below CUR Booleans[12] -#define move_insert_mode CUR Booleans[13] -#define move_standout_mode CUR Booleans[14] -#define over_strike CUR Booleans[15] -#define status_line_esc_ok CUR Booleans[16] -#define dest_tabs_magic_smso CUR Booleans[17] -#define tilde_glitch CUR Booleans[18] -#define transparent_underline CUR Booleans[19] -#define xon_xoff CUR Booleans[20] -#define needs_xon_xoff CUR Booleans[21] -#define prtr_silent CUR Booleans[22] -#define hard_cursor CUR Booleans[23] -#define non_rev_rmcup CUR Booleans[24] -#define no_pad_char CUR Booleans[25] -#define non_dest_scroll_region CUR Booleans[26] -#define can_change CUR Booleans[27] -#define back_color_erase CUR Booleans[28] -#define hue_lightness_saturation CUR Booleans[29] -#define col_addr_glitch CUR Booleans[30] -#define cr_cancels_micro_mode CUR Booleans[31] -#define has_print_wheel CUR Booleans[32] -#define row_addr_glitch CUR Booleans[33] -#define semi_auto_right_margin CUR Booleans[34] -#define cpi_changes_res CUR Booleans[35] -#define lpi_changes_res CUR Booleans[36] -#define columns CUR Numbers[0] -#define init_tabs CUR Numbers[1] -#define lines CUR Numbers[2] -#define lines_of_memory CUR Numbers[3] -#define magic_cookie_glitch CUR Numbers[4] -#define padding_baud_rate CUR Numbers[5] -#define virtual_terminal CUR Numbers[6] -#define width_status_line CUR Numbers[7] -#define num_labels CUR Numbers[8] -#define label_height CUR Numbers[9] -#define label_width CUR Numbers[10] -#define max_attributes CUR Numbers[11] -#define maximum_windows CUR Numbers[12] -#define max_colors CUR Numbers[13] -#define max_pairs CUR Numbers[14] -#define no_color_video CUR Numbers[15] -#define buffer_capacity CUR Numbers[16] -#define dot_vert_spacing CUR Numbers[17] -#define dot_horz_spacing CUR Numbers[18] -#define max_micro_address CUR Numbers[19] -#define max_micro_jump CUR Numbers[20] -#define micro_col_size CUR Numbers[21] -#define micro_line_size CUR Numbers[22] -#define number_of_pins CUR Numbers[23] -#define output_res_char CUR Numbers[24] -#define output_res_line CUR Numbers[25] -#define output_res_horz_inch CUR Numbers[26] -#define output_res_vert_inch CUR Numbers[27] -#define print_rate CUR Numbers[28] -#define wide_char_size CUR Numbers[29] -#define buttons CUR Numbers[30] -#define bit_image_entwining CUR Numbers[31] -#define bit_image_type CUR Numbers[32] -#define back_tab CUR Strings[0] -#define bell CUR Strings[1] -#define carriage_return CUR Strings[2] -#define change_scroll_region CUR Strings[3] -#define clear_all_tabs CUR Strings[4] -#define clear_screen CUR Strings[5] -#define clr_eol CUR Strings[6] -#define clr_eos CUR Strings[7] -#define column_address CUR Strings[8] -#define command_character CUR Strings[9] -#define cursor_address CUR Strings[10] -#define cursor_down CUR Strings[11] -#define cursor_home CUR Strings[12] -#define cursor_invisible CUR Strings[13] -#define cursor_left CUR Strings[14] -#define cursor_mem_address CUR Strings[15] -#define cursor_normal CUR Strings[16] -#define cursor_right CUR Strings[17] -#define cursor_to_ll CUR Strings[18] -#define cursor_up CUR Strings[19] -#define cursor_visible CUR Strings[20] -#define delete_character CUR Strings[21] -#define delete_line CUR Strings[22] -#define dis_status_line CUR Strings[23] -#define down_half_line CUR Strings[24] -#define enter_alt_charset_mode CUR Strings[25] -#define enter_blink_mode CUR Strings[26] -#define enter_bold_mode CUR Strings[27] -#define enter_ca_mode CUR Strings[28] -#define enter_delete_mode CUR Strings[29] -#define enter_dim_mode CUR Strings[30] -#define enter_insert_mode CUR Strings[31] -#define enter_secure_mode CUR Strings[32] -#define enter_protected_mode CUR Strings[33] -#define enter_reverse_mode CUR Strings[34] -#define enter_standout_mode CUR Strings[35] -#define enter_underline_mode CUR Strings[36] -#define erase_chars CUR Strings[37] -#define exit_alt_charset_mode CUR Strings[38] -#define exit_attribute_mode CUR Strings[39] -#define exit_ca_mode CUR Strings[40] -#define exit_delete_mode CUR Strings[41] -#define exit_insert_mode CUR Strings[42] -#define exit_standout_mode CUR Strings[43] -#define exit_underline_mode CUR Strings[44] -#define flash_screen CUR Strings[45] -#define form_feed CUR Strings[46] -#define from_status_line CUR Strings[47] -#define init_1string CUR Strings[48] -#define init_2string CUR Strings[49] -#define init_3string CUR Strings[50] -#define init_file CUR Strings[51] -#define insert_character CUR Strings[52] -#define insert_line CUR Strings[53] -#define insert_padding CUR Strings[54] -#define key_backspace CUR Strings[55] -#define key_catab CUR Strings[56] -#define key_clear CUR Strings[57] -#define key_ctab CUR Strings[58] -#define key_dc CUR Strings[59] -#define key_dl CUR Strings[60] -#define key_down CUR Strings[61] -#define key_eic CUR Strings[62] -#define key_eol CUR Strings[63] -#define key_eos CUR Strings[64] -#define key_f0 CUR Strings[65] -#define key_f1 CUR Strings[66] -#define key_f10 CUR Strings[67] -#define key_f2 CUR Strings[68] -#define key_f3 CUR Strings[69] -#define key_f4 CUR Strings[70] -#define key_f5 CUR Strings[71] -#define key_f6 CUR Strings[72] -#define key_f7 CUR Strings[73] -#define key_f8 CUR Strings[74] -#define key_f9 CUR Strings[75] -#define key_home CUR Strings[76] -#define key_ic CUR Strings[77] -#define key_il CUR Strings[78] -#define key_left CUR Strings[79] -#define key_ll CUR Strings[80] -#define key_npage CUR Strings[81] -#define key_ppage CUR Strings[82] -#define key_right CUR Strings[83] -#define key_sf CUR Strings[84] -#define key_sr CUR Strings[85] -#define key_stab CUR Strings[86] -#define key_up CUR Strings[87] -#define keypad_local CUR Strings[88] -#define keypad_xmit CUR Strings[89] -#define lab_f0 CUR Strings[90] -#define lab_f1 CUR Strings[91] -#define lab_f10 CUR Strings[92] -#define lab_f2 CUR Strings[93] -#define lab_f3 CUR Strings[94] -#define lab_f4 CUR Strings[95] -#define lab_f5 CUR Strings[96] -#define lab_f6 CUR Strings[97] -#define lab_f7 CUR Strings[98] -#define lab_f8 CUR Strings[99] -#define lab_f9 CUR Strings[100] -#define meta_off CUR Strings[101] -#define meta_on CUR Strings[102] -#define newline CUR Strings[103] -#define pad_char CUR Strings[104] -#define parm_dch CUR Strings[105] -#define parm_delete_line CUR Strings[106] -#define parm_down_cursor CUR Strings[107] -#define parm_ich CUR Strings[108] -#define parm_index CUR Strings[109] -#define parm_insert_line CUR Strings[110] -#define parm_left_cursor CUR Strings[111] -#define parm_right_cursor CUR Strings[112] -#define parm_rindex CUR Strings[113] -#define parm_up_cursor CUR Strings[114] -#define pkey_key CUR Strings[115] -#define pkey_local CUR Strings[116] -#define pkey_xmit CUR Strings[117] -#define print_screen CUR Strings[118] -#define prtr_off CUR Strings[119] -#define prtr_on CUR Strings[120] -#define repeat_char CUR Strings[121] -#define reset_1string CUR Strings[122] -#define reset_2string CUR Strings[123] -#define reset_3string CUR Strings[124] -#define reset_file CUR Strings[125] -#define restore_cursor CUR Strings[126] -#define row_address CUR Strings[127] -#define save_cursor CUR Strings[128] -#define scroll_forward CUR Strings[129] -#define scroll_reverse CUR Strings[130] -#define set_attributes CUR Strings[131] -#define set_tab CUR Strings[132] -#define set_window CUR Strings[133] -#define tab CUR Strings[134] -#define to_status_line CUR Strings[135] -#define underline_char CUR Strings[136] -#define up_half_line CUR Strings[137] -#define init_prog CUR Strings[138] -#define key_a1 CUR Strings[139] -#define key_a3 CUR Strings[140] -#define key_b2 CUR Strings[141] -#define key_c1 CUR Strings[142] -#define key_c3 CUR Strings[143] -#define prtr_non CUR Strings[144] -#define char_padding CUR Strings[145] -#define acs_chars CUR Strings[146] -#define plab_norm CUR Strings[147] -#define key_btab CUR Strings[148] -#define enter_xon_mode CUR Strings[149] -#define exit_xon_mode CUR Strings[150] -#define enter_am_mode CUR Strings[151] -#define exit_am_mode CUR Strings[152] -#define xon_character CUR Strings[153] -#define xoff_character CUR Strings[154] -#define ena_acs CUR Strings[155] -#define label_on CUR Strings[156] -#define label_off CUR Strings[157] -#define key_beg CUR Strings[158] -#define key_cancel CUR Strings[159] -#define key_close CUR Strings[160] -#define key_command CUR Strings[161] -#define key_copy CUR Strings[162] -#define key_create CUR Strings[163] -#define key_end CUR Strings[164] -#define key_enter CUR Strings[165] -#define key_exit CUR Strings[166] -#define key_find CUR Strings[167] -#define key_help CUR Strings[168] -#define key_mark CUR Strings[169] -#define key_message CUR Strings[170] -#define key_move CUR Strings[171] -#define key_next CUR Strings[172] -#define key_open CUR Strings[173] -#define key_options CUR Strings[174] -#define key_previous CUR Strings[175] -#define key_print CUR Strings[176] -#define key_redo CUR Strings[177] -#define key_reference CUR Strings[178] -#define key_refresh CUR Strings[179] -#define key_replace CUR Strings[180] -#define key_restart CUR Strings[181] -#define key_resume CUR Strings[182] -#define key_save CUR Strings[183] -#define key_suspend CUR Strings[184] -#define key_undo CUR Strings[185] -#define key_sbeg CUR Strings[186] -#define key_scancel CUR Strings[187] -#define key_scommand CUR Strings[188] -#define key_scopy CUR Strings[189] -#define key_screate CUR Strings[190] -#define key_sdc CUR Strings[191] -#define key_sdl CUR Strings[192] -#define key_select CUR Strings[193] -#define key_send CUR Strings[194] -#define key_seol CUR Strings[195] -#define key_sexit CUR Strings[196] -#define key_sfind CUR Strings[197] -#define key_shelp CUR Strings[198] -#define key_shome CUR Strings[199] -#define key_sic CUR Strings[200] -#define key_sleft CUR Strings[201] -#define key_smessage CUR Strings[202] -#define key_smove CUR Strings[203] -#define key_snext CUR Strings[204] -#define key_soptions CUR Strings[205] -#define key_sprevious CUR Strings[206] -#define key_sprint CUR Strings[207] -#define key_sredo CUR Strings[208] -#define key_sreplace CUR Strings[209] -#define key_sright CUR Strings[210] -#define key_srsume CUR Strings[211] -#define key_ssave CUR Strings[212] -#define key_ssuspend CUR Strings[213] -#define key_sundo CUR Strings[214] -#define req_for_input CUR Strings[215] -#define key_f11 CUR Strings[216] -#define key_f12 CUR Strings[217] -#define key_f13 CUR Strings[218] -#define key_f14 CUR Strings[219] -#define key_f15 CUR Strings[220] -#define key_f16 CUR Strings[221] -#define key_f17 CUR Strings[222] -#define key_f18 CUR Strings[223] -#define key_f19 CUR Strings[224] -#define key_f20 CUR Strings[225] -#define key_f21 CUR Strings[226] -#define key_f22 CUR Strings[227] -#define key_f23 CUR Strings[228] -#define key_f24 CUR Strings[229] -#define key_f25 CUR Strings[230] -#define key_f26 CUR Strings[231] -#define key_f27 CUR Strings[232] -#define key_f28 CUR Strings[233] -#define key_f29 CUR Strings[234] -#define key_f30 CUR Strings[235] -#define key_f31 CUR Strings[236] -#define key_f32 CUR Strings[237] -#define key_f33 CUR Strings[238] -#define key_f34 CUR Strings[239] -#define key_f35 CUR Strings[240] -#define key_f36 CUR Strings[241] -#define key_f37 CUR Strings[242] -#define key_f38 CUR Strings[243] -#define key_f39 CUR Strings[244] -#define key_f40 CUR Strings[245] -#define key_f41 CUR Strings[246] -#define key_f42 CUR Strings[247] -#define key_f43 CUR Strings[248] -#define key_f44 CUR Strings[249] -#define key_f45 CUR Strings[250] -#define key_f46 CUR Strings[251] -#define key_f47 CUR Strings[252] -#define key_f48 CUR Strings[253] -#define key_f49 CUR Strings[254] -#define key_f50 CUR Strings[255] -#define key_f51 CUR Strings[256] -#define key_f52 CUR Strings[257] -#define key_f53 CUR Strings[258] -#define key_f54 CUR Strings[259] -#define key_f55 CUR Strings[260] -#define key_f56 CUR Strings[261] -#define key_f57 CUR Strings[262] -#define key_f58 CUR Strings[263] -#define key_f59 CUR Strings[264] -#define key_f60 CUR Strings[265] -#define key_f61 CUR Strings[266] -#define key_f62 CUR Strings[267] -#define key_f63 CUR Strings[268] -#define clr_bol CUR Strings[269] -#define clear_margins CUR Strings[270] -#define set_left_margin CUR Strings[271] -#define set_right_margin CUR Strings[272] -#define label_format CUR Strings[273] -#define set_clock CUR Strings[274] -#define display_clock CUR Strings[275] -#define remove_clock CUR Strings[276] -#define create_window CUR Strings[277] -#define goto_window CUR Strings[278] -#define hangup CUR Strings[279] -#define dial_phone CUR Strings[280] -#define quick_dial CUR Strings[281] -#define tone CUR Strings[282] -#define pulse CUR Strings[283] -#define flash_hook CUR Strings[284] -#define fixed_pause CUR Strings[285] -#define wait_tone CUR Strings[286] -#define user0 CUR Strings[287] -#define user1 CUR Strings[288] -#define user2 CUR Strings[289] -#define user3 CUR Strings[290] -#define user4 CUR Strings[291] -#define user5 CUR Strings[292] -#define user6 CUR Strings[293] -#define user7 CUR Strings[294] -#define user8 CUR Strings[295] -#define user9 CUR Strings[296] -#define orig_pair CUR Strings[297] -#define orig_colors CUR Strings[298] -#define initialize_color CUR Strings[299] -#define initialize_pair CUR Strings[300] -#define set_color_pair CUR Strings[301] -#define set_foreground CUR Strings[302] -#define set_background CUR Strings[303] -#define change_char_pitch CUR Strings[304] -#define change_line_pitch CUR Strings[305] -#define change_res_horz CUR Strings[306] -#define change_res_vert CUR Strings[307] -#define define_char CUR Strings[308] -#define enter_doublewide_mode CUR Strings[309] -#define enter_draft_quality CUR Strings[310] -#define enter_italics_mode CUR Strings[311] -#define enter_leftward_mode CUR Strings[312] -#define enter_micro_mode CUR Strings[313] -#define enter_near_letter_quality CUR Strings[314] -#define enter_normal_quality CUR Strings[315] -#define enter_shadow_mode CUR Strings[316] -#define enter_subscript_mode CUR Strings[317] -#define enter_superscript_mode CUR Strings[318] -#define enter_upward_mode CUR Strings[319] -#define exit_doublewide_mode CUR Strings[320] -#define exit_italics_mode CUR Strings[321] -#define exit_leftward_mode CUR Strings[322] -#define exit_micro_mode CUR Strings[323] -#define exit_shadow_mode CUR Strings[324] -#define exit_subscript_mode CUR Strings[325] -#define exit_superscript_mode CUR Strings[326] -#define exit_upward_mode CUR Strings[327] -#define micro_column_address CUR Strings[328] -#define micro_down CUR Strings[329] -#define micro_left CUR Strings[330] -#define micro_right CUR Strings[331] -#define micro_row_address CUR Strings[332] -#define micro_up CUR Strings[333] -#define order_of_pins CUR Strings[334] -#define parm_down_micro CUR Strings[335] -#define parm_left_micro CUR Strings[336] -#define parm_right_micro CUR Strings[337] -#define parm_up_micro CUR Strings[338] -#define select_char_set CUR Strings[339] -#define set_bottom_margin CUR Strings[340] -#define set_bottom_margin_parm CUR Strings[341] -#define set_left_margin_parm CUR Strings[342] -#define set_right_margin_parm CUR Strings[343] -#define set_top_margin CUR Strings[344] -#define set_top_margin_parm CUR Strings[345] -#define start_bit_image CUR Strings[346] -#define start_char_set_def CUR Strings[347] -#define stop_bit_image CUR Strings[348] -#define stop_char_set_def CUR Strings[349] -#define subscript_characters CUR Strings[350] -#define superscript_characters CUR Strings[351] -#define these_cause_cr CUR Strings[352] -#define zero_motion CUR Strings[353] -#define char_set_names CUR Strings[354] -#define key_mouse CUR Strings[355] -#define mouse_info CUR Strings[356] -#define req_mouse_pos CUR Strings[357] -#define get_mouse CUR Strings[358] -#define set_a_foreground CUR Strings[359] -#define set_a_background CUR Strings[360] -#define pkey_plab CUR Strings[361] -#define device_type CUR Strings[362] -#define code_set_init CUR Strings[363] -#define set0_des_seq CUR Strings[364] -#define set1_des_seq CUR Strings[365] -#define set2_des_seq CUR Strings[366] -#define set3_des_seq CUR Strings[367] -#define set_lr_margin CUR Strings[368] -#define set_tb_margin CUR Strings[369] -#define bit_image_repeat CUR Strings[370] -#define bit_image_newline CUR Strings[371] -#define bit_image_carriage_return CUR Strings[372] -#define color_names CUR Strings[373] -#define define_bit_image_region CUR Strings[374] -#define end_bit_image_region CUR Strings[375] -#define set_color_band CUR Strings[376] -#define set_page_length CUR Strings[377] -#define display_pc_char CUR Strings[378] -#define enter_pc_charset_mode CUR Strings[379] -#define exit_pc_charset_mode CUR Strings[380] -#define enter_scancode_mode CUR Strings[381] -#define exit_scancode_mode CUR Strings[382] -#define pc_term_options CUR Strings[383] -#define scancode_escape CUR Strings[384] -#define alt_scancode_esc CUR Strings[385] -#define enter_horizontal_hl_mode CUR Strings[386] -#define enter_left_hl_mode CUR Strings[387] -#define enter_low_hl_mode CUR Strings[388] -#define enter_right_hl_mode CUR Strings[389] -#define enter_top_hl_mode CUR Strings[390] -#define enter_vertical_hl_mode CUR Strings[391] -#define set_a_attributes CUR Strings[392] -#define set_pglen_inch CUR Strings[393] - -#define BOOLWRITE 37 -#define NUMWRITE 33 -#define STRWRITE 394 - -/* older synonyms for some capabilities */ -#define beehive_glitch no_esc_ctlc -#define teleray_glitch dest_tabs_magic_smso -#define micro_char_size micro_col_size - -#ifdef __INTERNAL_CAPS_VISIBLE -#define termcap_init2 CUR Strings[394] -#define termcap_reset CUR Strings[395] -#define magic_cookie_glitch_ul CUR Numbers[33] -#define backspaces_with_bs CUR Booleans[37] -#define crt_no_scrolling CUR Booleans[38] -#define no_correctly_working_cr CUR Booleans[39] -#define carriage_return_delay CUR Numbers[34] -#define new_line_delay CUR Numbers[35] -#define linefeed_if_not_lf CUR Strings[396] -#define backspace_if_not_bs CUR Strings[397] -#define gnu_has_meta_key CUR Booleans[40] -#define linefeed_is_newline CUR Booleans[41] -#define backspace_delay CUR Numbers[36] -#define horizontal_tab_delay CUR Numbers[37] -#define number_of_function_keys CUR Numbers[38] -#define other_non_function_keys CUR Strings[398] -#define arrow_key_map CUR Strings[399] -#define has_hardware_tabs CUR Booleans[42] -#define return_does_clr_eol CUR Booleans[43] -#define acs_ulcorner CUR Strings[400] -#define acs_llcorner CUR Strings[401] -#define acs_urcorner CUR Strings[402] -#define acs_lrcorner CUR Strings[403] -#define acs_ltee CUR Strings[404] -#define acs_rtee CUR Strings[405] -#define acs_btee CUR Strings[406] -#define acs_ttee CUR Strings[407] -#define acs_hline CUR Strings[408] -#define acs_vline CUR Strings[409] -#define acs_plus CUR Strings[410] -#define memory_lock CUR Strings[411] -#define memory_unlock CUR Strings[412] -#define box_chars_1 CUR Strings[413] -#endif /* __INTERNAL_CAPS_VISIBLE */ - - -/* - * Predefined terminfo array sizes - */ -#define BOOLCOUNT 44 -#define NUMCOUNT 39 -#define STRCOUNT 414 - -/* used by code for comparing entries */ -#define acs_chars_index 146 - -typedef struct termtype { /* in-core form of terminfo data */ - char *term_names; /* str_table offset of term names */ - char *str_table; /* pointer to string table */ - NCURSES_SBOOL *Booleans; /* array of boolean values */ - short *Numbers; /* array of integer values */ - char **Strings; /* array of string offsets */ - -#if NCURSES_XNAMES - char *ext_str_table; /* pointer to extended string table */ - char **ext_Names; /* corresponding names */ - - unsigned short num_Booleans;/* count total Booleans */ - unsigned short num_Numbers; /* count total Numbers */ - unsigned short num_Strings; /* count total Strings */ - - unsigned short ext_Booleans;/* count extensions to Booleans */ - unsigned short ext_Numbers; /* count extensions to Numbers */ - unsigned short ext_Strings; /* count extensions to Strings */ -#endif /* NCURSES_XNAMES */ - -} TERMTYPE; - -typedef struct term { /* describe an actual terminal */ - TERMTYPE type; /* terminal type description */ - short Filedes; /* file description being written to */ - TTY Ottyb, /* original state of the terminal */ - Nttyb; /* current state of the terminal */ - int _baudrate; /* used to compute padding */ - char * _termname; /* used for termname() */ -} TERMINAL; - -#if 0 && !0 -extern NCURSES_EXPORT_VAR(TERMINAL *) cur_term; -#elif 0 -NCURSES_WRAPPED_VAR(TERMINAL *, cur_term); -#define cur_term NCURSES_PUBLIC_VAR(cur_term()) -#else -extern NCURSES_EXPORT_VAR(TERMINAL *) cur_term; -#endif - -#if 0 || 0 -NCURSES_WRAPPED_VAR(NCURSES_CONST char * const *, boolnames); -NCURSES_WRAPPED_VAR(NCURSES_CONST char * const *, boolcodes); -NCURSES_WRAPPED_VAR(NCURSES_CONST char * const *, boolfnames); -NCURSES_WRAPPED_VAR(NCURSES_CONST char * const *, numnames); -NCURSES_WRAPPED_VAR(NCURSES_CONST char * const *, numcodes); -NCURSES_WRAPPED_VAR(NCURSES_CONST char * const *, numfnames); -NCURSES_WRAPPED_VAR(NCURSES_CONST char * const *, strnames); -NCURSES_WRAPPED_VAR(NCURSES_CONST char * const *, strcodes); -NCURSES_WRAPPED_VAR(NCURSES_CONST char * const *, strfnames); - -#define boolnames NCURSES_PUBLIC_VAR(boolnames()) -#define boolcodes NCURSES_PUBLIC_VAR(boolcodes()) -#define boolfnames NCURSES_PUBLIC_VAR(boolfnames()) -#define numnames NCURSES_PUBLIC_VAR(numnames()) -#define numcodes NCURSES_PUBLIC_VAR(numcodes()) -#define numfnames NCURSES_PUBLIC_VAR(numfnames()) -#define strnames NCURSES_PUBLIC_VAR(strnames()) -#define strcodes NCURSES_PUBLIC_VAR(strcodes()) -#define strfnames NCURSES_PUBLIC_VAR(strfnames()) - -#else - -extern NCURSES_EXPORT_VAR(NCURSES_CONST char * const ) boolnames[]; -extern NCURSES_EXPORT_VAR(NCURSES_CONST char * const ) boolcodes[]; -extern NCURSES_EXPORT_VAR(NCURSES_CONST char * const ) boolfnames[]; -extern NCURSES_EXPORT_VAR(NCURSES_CONST char * const ) numnames[]; -extern NCURSES_EXPORT_VAR(NCURSES_CONST char * const ) numcodes[]; -extern NCURSES_EXPORT_VAR(NCURSES_CONST char * const ) numfnames[]; -extern NCURSES_EXPORT_VAR(NCURSES_CONST char * const ) strnames[]; -extern NCURSES_EXPORT_VAR(NCURSES_CONST char * const ) strcodes[]; -extern NCURSES_EXPORT_VAR(NCURSES_CONST char * const ) strfnames[]; - -#endif - -/* internals */ -extern NCURSES_EXPORT(int) _nc_set_tty_mode (TTY *buf); -extern NCURSES_EXPORT(int) _nc_get_tty_mode (TTY *buf); -extern NCURSES_EXPORT(int) _nc_read_entry (const char * const, char * const, TERMTYPE *const); -extern NCURSES_EXPORT(int) _nc_read_file_entry (const char *const, TERMTYPE *); -extern NCURSES_EXPORT(int) _nc_read_termtype (TERMTYPE *, char *, int); -extern NCURSES_EXPORT(char *) _nc_first_name (const char *const); -extern NCURSES_EXPORT(int) _nc_name_match (const char *const, const char *const, const char *const); -extern NCURSES_EXPORT(const TERMTYPE *) _nc_fallback (const char *); - -/* entry points */ -extern NCURSES_EXPORT(TERMINAL *) set_curterm (TERMINAL *); -extern NCURSES_EXPORT(int) del_curterm (TERMINAL *); - -/* miscellaneous entry points */ -extern NCURSES_EXPORT(int) restartterm (NCURSES_CONST char *, int, int *); -extern NCURSES_EXPORT(int) setupterm (NCURSES_CONST char *,int,int *); - -/* terminfo entry points, also declared in curses.h */ -#if !defined(__NCURSES_H) -extern NCURSES_EXPORT(char *) tigetstr (NCURSES_CONST char *); -extern NCURSES_EXPORT_VAR(char) ttytype[]; -extern NCURSES_EXPORT(int) putp (const char *); -extern NCURSES_EXPORT(int) tigetflag (NCURSES_CONST char *); -extern NCURSES_EXPORT(int) tigetnum (NCURSES_CONST char *); - -#if 1 /* NCURSES_TPARM_VARARGS */ -extern NCURSES_EXPORT(char *) tparm (NCURSES_CONST char *, ...); /* special */ -#else -extern NCURSES_EXPORT(char *) tparm (NCURSES_CONST char *, long,long,long,long,long,long,long,long,long); /* special */ -extern NCURSES_EXPORT(char *) tparm_varargs (NCURSES_CONST char *, ...); /* special */ -#endif - -extern NCURSES_EXPORT(char *) tiparm (const char *, ...); /* special */ - -#endif /* __NCURSES_H */ - -/* termcap database emulation (XPG4 uses const only for 2nd param of tgetent) */ -#if !defined(NCURSES_TERMCAP_H_incl) -extern NCURSES_EXPORT(char *) tgetstr (NCURSES_CONST char *, char **); -extern NCURSES_EXPORT(char *) tgoto (const char *, int, int); -extern NCURSES_EXPORT(int) tgetent (char *, const char *); -extern NCURSES_EXPORT(int) tgetflag (NCURSES_CONST char *); -extern NCURSES_EXPORT(int) tgetnum (NCURSES_CONST char *); -extern NCURSES_EXPORT(int) tputs (const char *, int, int (*)(int)); -#endif /* NCURSES_TERMCAP_H_incl */ - -/* - * Include curses.h before term.h to enable these extensions. - */ -#if defined(NCURSES_SP_FUNCS) && (NCURSES_SP_FUNCS != 0) - -extern NCURSES_EXPORT(char *) NCURSES_SP_NAME(tigetstr) (SCREEN*, NCURSES_CONST char *); -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(putp) (SCREEN*, const char *); -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(tigetflag) (SCREEN*, NCURSES_CONST char *); -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(tigetnum) (SCREEN*, NCURSES_CONST char *); - -#if 1 /* NCURSES_TPARM_VARARGS */ -extern NCURSES_EXPORT(char *) NCURSES_SP_NAME(tparm) (SCREEN*, NCURSES_CONST char *, ...); /* special */ -#else -extern NCURSES_EXPORT(char *) NCURSES_SP_NAME(tparm) (SCREEN*, NCURSES_CONST char *, long,long,long,long,long,long,long,long,long); /* special */ -extern NCURSES_EXPORT(char *) NCURSES_SP_NAME(tparm_varargs) (SCREEN*, NCURSES_CONST char *, ...); /* special */ -#endif - -/* termcap database emulation (XPG4 uses const only for 2nd param of tgetent) */ -extern NCURSES_EXPORT(char *) NCURSES_SP_NAME(tgetstr) (SCREEN*, NCURSES_CONST char *, char **); -extern NCURSES_EXPORT(char *) NCURSES_SP_NAME(tgoto) (SCREEN*, const char *, int, int); -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(tgetent) (SCREEN*, char *, const char *); -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(tgetflag) (SCREEN*, NCURSES_CONST char *); -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(tgetnum) (SCREEN*, NCURSES_CONST char *); -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(tputs) (SCREEN*, const char *, int, NCURSES_SP_OUTC); - -extern NCURSES_EXPORT(TERMINAL *) NCURSES_SP_NAME(set_curterm) (SCREEN*, TERMINAL *); -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(del_curterm) (SCREEN*, TERMINAL *); - -extern NCURSES_EXPORT(int) NCURSES_SP_NAME(restartterm) (SCREEN*, NCURSES_CONST char *, int, int *); -#endif /* NCURSES_SP_FUNCS */ - -#ifdef __cplusplus -} -#endif - -#endif /* NCURSES_TERM_H_incl */ diff --git a/windows/ncurses/include/ncurses/term_entry.h b/windows/ncurses/include/ncurses/term_entry.h deleted file mode 100644 index 1610438e3..000000000 --- a/windows/ncurses/include/ncurses/term_entry.h +++ /dev/null @@ -1,174 +0,0 @@ -/**************************************************************************** - * Copyright (c) 1998-2008,2009 Free Software Foundation, Inc. * - * * - * Permission is hereby granted, free of charge, to any person obtaining a * - * copy of this software and associated documentation files (the * - * "Software"), to deal in the Software without restriction, including * - * without limitation the rights to use, copy, modify, merge, publish, * - * distribute, distribute with modifications, sublicense, and/or sell * - * copies of the Software, and to permit persons to whom the Software is * - * furnished to do so, subject to the following conditions: * - * * - * The above copyright notice and this permission notice shall be included * - * in all copies or substantial portions of the Software. * - * * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * - * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * - * THE USE OR OTHER DEALINGS IN THE SOFTWARE. * - * * - * Except as contained in this notice, the name(s) of the above copyright * - * holders shall not be used in advertising or otherwise to promote the * - * sale, use or other dealings in this Software without prior written * - * authorization. * - ****************************************************************************/ - -/**************************************************************************** - * Author: Zeyd M. Ben-Halim 1992,1995 * - * and: Eric S. Raymond * - * and: Thomas E. Dickey 1998-on * - ****************************************************************************/ - -/* $Id: term_entry.h,v 1.37 2009/07/11 16:52:29 tom Exp $ */ - -/* - * term_entry.h -- interface to entry-manipulation code - */ - -#ifndef NCURSES_TERM_ENTRY_H_incl -#define NCURSES_TERM_ENTRY_H_incl 1 - -#ifdef __cplusplus -extern "C" { -#endif - -#include - -#define MAX_USES 32 -#define MAX_CROSSLINKS 16 - -typedef struct entry { - TERMTYPE tterm; - unsigned nuses; - struct - { - char *name; - struct entry *link; - long line; - } - uses[MAX_USES]; - int ncrosslinks; - struct entry *crosslinks[MAX_CROSSLINKS]; - long cstart, cend; - long startline; - struct entry *next; - struct entry *last; -} -ENTRY; - -#if NCURSES_XNAMES -#define NUM_BOOLEANS(tp) (tp)->num_Booleans -#define NUM_NUMBERS(tp) (tp)->num_Numbers -#define NUM_STRINGS(tp) (tp)->num_Strings -#define EXT_NAMES(tp,i,limit,index,table) (i >= limit) ? tp->ext_Names[index] : table[i] -#else -#define NUM_BOOLEANS(tp) BOOLCOUNT -#define NUM_NUMBERS(tp) NUMCOUNT -#define NUM_STRINGS(tp) STRCOUNT -#define EXT_NAMES(tp,i,limit,index,table) table[i] -#endif - -#define NUM_EXT_NAMES(tp) (unsigned) ((tp)->ext_Booleans + (tp)->ext_Numbers + (tp)->ext_Strings) - -#define for_each_boolean(n,tp) for(n = 0; n < NUM_BOOLEANS(tp); n++) -#define for_each_number(n,tp) for(n = 0; n < NUM_NUMBERS(tp); n++) -#define for_each_string(n,tp) for(n = 0; n < NUM_STRINGS(tp); n++) - -#if NCURSES_XNAMES -#define for_each_ext_boolean(n,tp) for(n = BOOLCOUNT; n < NUM_BOOLEANS(tp); n++) -#define for_each_ext_number(n,tp) for(n = NUMCOUNT; n < NUM_NUMBERS(tp); n++) -#define for_each_ext_string(n,tp) for(n = STRCOUNT; n < NUM_STRINGS(tp); n++) -#endif - -#define ExtBoolname(tp,i,names) EXT_NAMES(tp, i, BOOLCOUNT, (i - (tp->num_Booleans - tp->ext_Booleans)), names) -#define ExtNumname(tp,i,names) EXT_NAMES(tp, i, NUMCOUNT, (i - (tp->num_Numbers - tp->ext_Numbers)) + tp->ext_Booleans, names) -#define ExtStrname(tp,i,names) EXT_NAMES(tp, i, STRCOUNT, (i - (tp->num_Strings - tp->ext_Strings)) + (tp->ext_Numbers + tp->ext_Booleans), names) - -extern NCURSES_EXPORT_VAR(ENTRY *) _nc_head; -extern NCURSES_EXPORT_VAR(ENTRY *) _nc_tail; -#define for_entry_list(qp) for (qp = _nc_head; qp; qp = qp->next) - -#define MAX_LINE 132 - -#define NULLHOOK (bool(*)(ENTRY *))0 - -/* - * Note that WANTED and PRESENT are not simple inverses! If a capability - * has been explicitly cancelled, it's not considered WANTED. - */ -#define WANTED(s) ((s) == ABSENT_STRING) -#define PRESENT(s) (((s) != ABSENT_STRING) && ((s) != CANCELLED_STRING)) - -#define ANDMISSING(p,q) \ - {if (PRESENT(p) && !PRESENT(q)) _nc_warning(#p " but no " #q);} - -#define PAIRED(p,q) \ - { \ - if (PRESENT(q) && !PRESENT(p)) \ - _nc_warning(#q " but no " #p); \ - if (PRESENT(p) && !PRESENT(q)) \ - _nc_warning(#p " but no " #q); \ - } - -/* alloc_entry.c: elementary allocation code */ -extern NCURSES_EXPORT(ENTRY *) _nc_copy_entry (ENTRY *oldp); -extern NCURSES_EXPORT(char *) _nc_save_str (const char *const); -extern NCURSES_EXPORT(void) _nc_init_entry (TERMTYPE *const); -extern NCURSES_EXPORT(void) _nc_merge_entry (TERMTYPE *const, TERMTYPE *const); -extern NCURSES_EXPORT(void) _nc_wrap_entry (ENTRY *const, bool); - -/* alloc_ttype.c: elementary allocation code */ -extern NCURSES_EXPORT(void) _nc_align_termtype (TERMTYPE *, TERMTYPE *); -extern NCURSES_EXPORT(void) _nc_copy_termtype (TERMTYPE *, TERMTYPE *); - -/* free_ttype.c: elementary allocation code */ -extern NCURSES_EXPORT(void) _nc_free_termtype (TERMTYPE *); - -/* lib_acs.c */ -extern NCURSES_EXPORT(void) _nc_init_acs (void); /* corresponds to traditional 'init_acs()' */ - -/* lib_termcap.c: trim sgr0 string for termcap users */ -extern NCURSES_EXPORT(char *) _nc_trim_sgr0 (TERMTYPE *); - -/* parse_entry.c: entry-parsing code */ -#if NCURSES_XNAMES -extern NCURSES_EXPORT_VAR(bool) _nc_user_definable; -extern NCURSES_EXPORT_VAR(bool) _nc_disable_period; -#endif -extern NCURSES_EXPORT(int) _nc_parse_entry (ENTRY *, int, bool); -extern NCURSES_EXPORT(int) _nc_capcmp (const char *, const char *); - -/* write_entry.c: writing an entry to the file system */ -extern NCURSES_EXPORT(void) _nc_set_writedir (char *); -extern NCURSES_EXPORT(void) _nc_write_entry (TERMTYPE *const); - -/* comp_parse.c: entry list handling */ -extern NCURSES_EXPORT(void) _nc_read_entry_source (FILE*, char*, int, bool, bool (*)(ENTRY*)); -extern NCURSES_EXPORT(bool) _nc_entry_match (char *, char *); -extern NCURSES_EXPORT(int) _nc_resolve_uses (bool); /* obs 20040705 */ -extern NCURSES_EXPORT(int) _nc_resolve_uses2 (bool, bool); -extern NCURSES_EXPORT(void) _nc_free_entries (ENTRY *); -extern NCURSES_IMPEXP void NCURSES_API (*_nc_check_termtype)(TERMTYPE *); /* obs 20040705 */ -extern NCURSES_IMPEXP void NCURSES_API (*_nc_check_termtype2)(TERMTYPE *, bool); - -/* trace_xnames.c */ -extern NCURSES_EXPORT(void) _nc_trace_xnames (TERMTYPE *); - -#ifdef __cplusplus -} -#endif - -#endif /* NCURSES_TERM_ENTRY_H_incl */ diff --git a/windows/ncurses/include/ncurses/termcap.h b/windows/ncurses/include/ncurses/termcap.h deleted file mode 100644 index a1d81a154..000000000 --- a/windows/ncurses/include/ncurses/termcap.h +++ /dev/null @@ -1,75 +0,0 @@ -/**************************************************************************** - * Copyright (c) 1998,2000 Free Software Foundation, Inc. * - * * - * Permission is hereby granted, free of charge, to any person obtaining a * - * copy of this software and associated documentation files (the * - * "Software"), to deal in the Software without restriction, including * - * without limitation the rights to use, copy, modify, merge, publish, * - * distribute, distribute with modifications, sublicense, and/or sell * - * copies of the Software, and to permit persons to whom the Software is * - * furnished to do so, subject to the following conditions: * - * * - * The above copyright notice and this permission notice shall be included * - * in all copies or substantial portions of the Software. * - * * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * - * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * - * THE USE OR OTHER DEALINGS IN THE SOFTWARE. * - * * - * Except as contained in this notice, the name(s) of the above copyright * - * holders shall not be used in advertising or otherwise to promote the * - * sale, use or other dealings in this Software without prior written * - * authorization. * - ****************************************************************************/ - -/**************************************************************************** - * Author: Zeyd M. Ben-Halim 1992,1995 * - * and: Eric S. Raymond * - ****************************************************************************/ - -/* $Id: termcap.h.in,v 1.16 2001/03/24 21:53:27 tom Exp $ */ - -#ifndef NCURSES_TERMCAP_H_incl -#define NCURSES_TERMCAP_H_incl 1 - -#undef NCURSES_VERSION -#define NCURSES_VERSION "5.9" - -#include - -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#include - -#undef NCURSES_CONST -#define NCURSES_CONST /*nothing*/ - -#undef NCURSES_OSPEED -#define NCURSES_OSPEED short - -extern NCURSES_EXPORT_VAR(char) PC; -extern NCURSES_EXPORT_VAR(char *) UP; -extern NCURSES_EXPORT_VAR(char *) BC; -extern NCURSES_EXPORT_VAR(NCURSES_OSPEED) ospeed; - -#if !defined(NCURSES_TERM_H_incl) -extern NCURSES_EXPORT(char *) tgetstr (NCURSES_CONST char *, char **); -extern NCURSES_EXPORT(char *) tgoto (const char *, int, int); -extern NCURSES_EXPORT(int) tgetent (char *, const char *); -extern NCURSES_EXPORT(int) tgetflag (NCURSES_CONST char *); -extern NCURSES_EXPORT(int) tgetnum (NCURSES_CONST char *); -extern NCURSES_EXPORT(int) tputs (const char *, int, int (*)(int)); -#endif - -#ifdef __cplusplus -} -#endif - -#endif /* NCURSES_TERMCAP_H_incl */ diff --git a/windows/ncurses/include/ncurses/tic.h b/windows/ncurses/include/ncurses/tic.h deleted file mode 100644 index 28ee3882e..000000000 --- a/windows/ncurses/include/ncurses/tic.h +++ /dev/null @@ -1,346 +0,0 @@ -/**************************************************************************** - * Copyright (c) 1998-2007,2009 Free Software Foundation, Inc. * - * * - * Permission is hereby granted, free of charge, to any person obtaining a * - * copy of this software and associated documentation files (the * - * "Software"), to deal in the Software without restriction, including * - * without limitation the rights to use, copy, modify, merge, publish, * - * distribute, distribute with modifications, sublicense, and/or sell * - * copies of the Software, and to permit persons to whom the Software is * - * furnished to do so, subject to the following conditions: * - * * - * The above copyright notice and this permission notice shall be included * - * in all copies or substantial portions of the Software. * - * * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * - * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * - * THE USE OR OTHER DEALINGS IN THE SOFTWARE. * - * * - * Except as contained in this notice, the name(s) of the above copyright * - * holders shall not be used in advertising or otherwise to promote the * - * sale, use or other dealings in this Software without prior written * - * authorization. * - ****************************************************************************/ - -/**************************************************************************** - * Author: Zeyd M. Ben-Halim 1992,1995 * - * and: Eric S. Raymond * - * and: Thomas E. Dickey 1996 on * - ****************************************************************************/ - -/* - * $Id: tic.h,v 1.65 2009/08/08 17:52:46 tom Exp $ - * tic.h - Global variables and structures for the terminfo - * compiler. - */ - -#ifndef __TIC_H -#define __TIC_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include /* for the _tracef() prototype, ERR/OK, bool defs */ - -/* -** The format of compiled terminfo files is as follows: -** -** Header (12 bytes), containing information given below -** Names Section, containing the names of the terminal -** Boolean Section, containing the values of all of the -** boolean capabilities -** A null byte may be inserted here to make -** sure that the Number Section begins on an -** even word boundary. -** Number Section, containing the values of all of the numeric -** capabilities, each as a short integer -** String Section, containing short integer offsets into the -** String Table, one per string capability -** String Table, containing the actual characters of the string -** capabilities. -** -** NOTE that all short integers in the file are stored using VAX/PDP-style -** byte-order, i.e., least-significant byte first. -** -** There is no structure definition here because it would only confuse -** matters. Terminfo format is a raw byte layout, not a structure -** dump. If you happen to be on a little-endian machine with 16-bit -** shorts that requires no padding between short members in a struct, -** then there is a natural C structure that captures the header, but -** not very helpfully. -*/ - -#define MAGIC 0432 /* first two bytes of a compiled entry */ - -#undef BYTE -#define BYTE(p,n) (unsigned char)((p)[n]) - -#define IS_NEG1(p) ((BYTE(p,0) == 0377) && (BYTE(p,1) == 0377)) -#define IS_NEG2(p) ((BYTE(p,0) == 0376) && (BYTE(p,1) == 0377)) -#define LOW_MSB(p) (BYTE(p,0) + 256*BYTE(p,1)) - -#define IS_TIC_MAGIC(p) (LOW_MSB(p) == MAGIC) - -/* - * The "maximum" here is misleading; XSI guarantees minimum values, which a - * given implementation may exceed. - */ -#define MAX_NAME_SIZE 512 /* maximum legal name field size (XSI:127) */ -#define MAX_ENTRY_SIZE 4096 /* maximum legal entry size */ - -/* - * The maximum size of individual name or alias is guaranteed in XSI to be at - * least 14, since that corresponds to the older filename lengths. Newer - * systems allow longer aliases, though not many terminal descriptions are - * written to use them. The MAX_ALIAS symbol is used for warnings. - */ -#if HAVE_LONG_FILE_NAMES -#define MAX_ALIAS 32 /* smaller than POSIX minimum for PATH_MAX */ -#else -#define MAX_ALIAS 14 /* SVr3 filename length */ -#endif - -/* location of user's personal info directory */ -#define PRIVATE_INFO "%s/.terminfo" /* plug getenv("HOME") into %s */ - -/* - * Some traces are designed to be used via tic's verbose option (and similar in - * infocmp and toe) rather than the 'trace()' function. So we use the bits - * above the normal trace() parameter as a debug-level. - */ - -#define MAX_DEBUG_LEVEL 15 -#define DEBUG_LEVEL(n) ((n) << TRACE_SHIFT) - -#define set_trace_level(n) \ - _nc_tracing &= DEBUG_LEVEL(MAX_DEBUG_LEVEL), \ - _nc_tracing |= DEBUG_LEVEL(n) - -#ifdef TRACE -#define DEBUG(n, a) if (_nc_tracing >= DEBUG_LEVEL(n)) _tracef a -#else -#define DEBUG(n, a) /*nothing*/ -#endif - -extern NCURSES_EXPORT_VAR(unsigned) _nc_tracing; -extern NCURSES_EXPORT(void) _nc_tracef (char *, ...) GCC_PRINTFLIKE(1,2); -extern NCURSES_EXPORT(const char *) _nc_visbuf (const char *); -extern NCURSES_EXPORT(const char *) _nc_visbuf2 (int, const char *); - -/* - * These are the types of tokens returned by the scanner. The first - * three are also used in the hash table of capability names. The scanner - * returns one of these values after loading the specifics into the global - * structure curr_token. - */ - -#define BOOLEAN 0 /* Boolean capability */ -#define NUMBER 1 /* Numeric capability */ -#define STRING 2 /* String-valued capability */ -#define CANCEL 3 /* Capability to be cancelled in following tc's */ -#define NAMES 4 /* The names for a terminal type */ -#define UNDEF 5 /* Undefined */ - -#define NO_PUSHBACK -1 /* used in pushtype to indicate no pushback */ - - /* - * The global structure in which the specific parts of a - * scanned token are returned. - * - */ - -struct token -{ - char *tk_name; /* name of capability */ - int tk_valnumber; /* value of capability (if a number) */ - char *tk_valstring; /* value of capability (if a string) */ -}; - -extern NCURSES_EXPORT_VAR(struct token) _nc_curr_token; - - /* - * Offsets to string capabilities, with the corresponding functionkey - * codes. - */ -struct tinfo_fkeys { - unsigned offset; - chtype code; - }; - -#if BROKEN_LINKER - -#define _nc_tinfo_fkeys _nc_tinfo_fkeysf() -extern NCURSES_EXPORT(const struct tinfo_fkeys *) _nc_tinfo_fkeysf (void); - -#else - -extern NCURSES_EXPORT_VAR(const struct tinfo_fkeys) _nc_tinfo_fkeys[]; - -#endif - -typedef short HashValue; - - /* - * The file comp_captab.c contains an array of these structures, one - * per possible capability. These are indexed by a hash table array of - * pointers to the same structures for use by the parser. - */ - -struct name_table_entry -{ - const char *nte_name; /* name to hash on */ - int nte_type; /* BOOLEAN, NUMBER or STRING */ - HashValue nte_index; /* index of associated variable in its array */ - HashValue nte_link; /* index in table of next hash, or -1 */ -}; - - /* - * Use this structure to hide differences between terminfo and termcap - * tables. - */ -typedef struct { - unsigned table_size; - const HashValue *table_data; - HashValue (*hash_of)(const char *); - int (*compare_names)(const char *, const char *); -} HashData; - -struct alias -{ - const char *from; - const char *to; - const char *source; -}; - -extern NCURSES_EXPORT(const struct name_table_entry *) _nc_get_table (bool); -extern NCURSES_EXPORT(const HashData *) _nc_get_hash_info (bool); -extern NCURSES_EXPORT(const HashValue *) _nc_get_hash_table (bool); -extern NCURSES_EXPORT(const struct alias *) _nc_get_alias_table (bool); - -#define NOTFOUND ((struct name_table_entry *) 0) - -/* out-of-band values for representing absent capabilities */ -#define ABSENT_BOOLEAN ((signed char)-1) /* 255 */ -#define ABSENT_NUMERIC (-1) -#define ABSENT_STRING (char *)0 - -/* out-of-band values for representing cancels */ -#define CANCELLED_BOOLEAN ((signed char)-2) /* 254 */ -#define CANCELLED_NUMERIC (-2) -#define CANCELLED_STRING (char *)(-1) - -#define VALID_BOOLEAN(s) ((unsigned char)(s) <= 1) /* reject "-1" */ -#define VALID_NUMERIC(s) ((s) >= 0) -#define VALID_STRING(s) ((s) != CANCELLED_STRING && (s) != ABSENT_STRING) - -/* termcap entries longer than this may break old binaries */ -#define MAX_TERMCAP_LENGTH 1023 - -/* this is a documented limitation of terminfo */ -#define MAX_TERMINFO_LENGTH 4096 - -#ifndef TERMINFO -#define TERMINFO "/usr/share/terminfo" -#endif - -/* access.c */ -extern NCURSES_EXPORT(unsigned) _nc_pathlast (const char *); -extern NCURSES_EXPORT(bool) _nc_is_abs_path (const char *); -extern NCURSES_EXPORT(bool) _nc_is_dir_path (const char *); -extern NCURSES_EXPORT(bool) _nc_is_file_path (const char *); -extern NCURSES_EXPORT(char *) _nc_basename (char *); -extern NCURSES_EXPORT(char *) _nc_rootname (char *); - -/* comp_hash.c: name lookup */ -extern NCURSES_EXPORT(struct name_table_entry const *) _nc_find_entry - (const char *, const HashValue *); -extern NCURSES_EXPORT(struct name_table_entry const *) _nc_find_type_entry - (const char *, int, bool); - -/* comp_scan.c: lexical analysis */ -extern NCURSES_EXPORT(int) _nc_get_token (bool); -extern NCURSES_EXPORT(void) _nc_panic_mode (char); -extern NCURSES_EXPORT(void) _nc_push_token (int); -extern NCURSES_EXPORT(void) _nc_reset_input (FILE *, char *); -extern NCURSES_EXPORT_VAR(int) _nc_curr_col; -extern NCURSES_EXPORT_VAR(int) _nc_curr_line; -extern NCURSES_EXPORT_VAR(int) _nc_syntax; -extern NCURSES_EXPORT_VAR(long) _nc_comment_end; -extern NCURSES_EXPORT_VAR(long) _nc_comment_start; -extern NCURSES_EXPORT_VAR(long) _nc_curr_file_pos; -extern NCURSES_EXPORT_VAR(long) _nc_start_line; -#define SYN_TERMINFO 0 -#define SYN_TERMCAP 1 - -/* comp_error.c: warning & abort messages */ -extern NCURSES_EXPORT(const char *) _nc_get_source (void); -extern NCURSES_EXPORT(void) _nc_err_abort (const char *const,...) GCC_PRINTFLIKE(1,2) GCC_NORETURN; -extern NCURSES_EXPORT(void) _nc_get_type (char *name); -extern NCURSES_EXPORT(void) _nc_set_source (const char *const); -extern NCURSES_EXPORT(void) _nc_set_type (const char *const); -extern NCURSES_EXPORT(void) _nc_syserr_abort (const char *const,...) GCC_PRINTFLIKE(1,2) GCC_NORETURN; -extern NCURSES_EXPORT(void) _nc_warning (const char *const,...) GCC_PRINTFLIKE(1,2); -extern NCURSES_EXPORT_VAR(bool) _nc_suppress_warnings; - -/* comp_expand.c: expand string into readable form */ -extern NCURSES_EXPORT(char *) _nc_tic_expand (const char *, bool, int); - -/* comp_scan.c: decode string from readable form */ -extern NCURSES_EXPORT(int) _nc_trans_string (char *, char *); - -/* captoinfo.c: capability conversion */ -extern NCURSES_EXPORT(char *) _nc_captoinfo (const char *, const char *, int const); -extern NCURSES_EXPORT(char *) _nc_infotocap (const char *, const char *, int const); - -/* home_terminfo.c */ -extern NCURSES_EXPORT(char *) _nc_home_terminfo (void); - -/* lib_tparm.c */ -#define NUM_PARM 9 - -extern NCURSES_EXPORT_VAR(int) _nc_tparm_err; - -extern NCURSES_EXPORT(int) _nc_tparm_analyze(const char *, char **, int *); - -/* lib_tputs.c */ -extern NCURSES_EXPORT_VAR(int) _nc_nulls_sent; /* Add one for every null sent */ - -/* comp_main.c: compiler main */ -extern const char * _nc_progname; - -/* db_iterator.c */ -typedef enum { - dbdTIC = 0, -#if USE_DATABASE - dbdEnvOnce, - dbdHome, - dbdEnvList, - dbdCfgList, - dbdCfgOnce, -#endif -#if USE_TERMCAP - dbdEnvOnce2, - dbdEnvList2, - dbdCfgList2, -#endif - dbdLAST -} DBDIRS; - -extern NCURSES_EXPORT(const char *) _nc_next_db(DBDIRS *, int *); -extern NCURSES_EXPORT(const char *) _nc_tic_dir (const char *); -extern NCURSES_EXPORT(void) _nc_first_db(DBDIRS *, int *); -extern NCURSES_EXPORT(void) _nc_last_db(void); - -/* write_entry.c */ -extern NCURSES_EXPORT(int) _nc_tic_written (void); - -#ifdef __cplusplus -} -#endif - -#endif /* __TIC_H */ diff --git a/windows/ncurses/include/ncurses/unctrl.h b/windows/ncurses/include/ncurses/unctrl.h deleted file mode 100644 index 318de7b57..000000000 --- a/windows/ncurses/include/ncurses/unctrl.h +++ /dev/null @@ -1,67 +0,0 @@ -/**************************************************************************** - * Copyright (c) 1998-2008,2009 Free Software Foundation, Inc. * - * * - * Permission is hereby granted, free of charge, to any person obtaining a * - * copy of this software and associated documentation files (the * - * "Software"), to deal in the Software without restriction, including * - * without limitation the rights to use, copy, modify, merge, publish, * - * distribute, distribute with modifications, sublicense, and/or sell * - * copies of the Software, and to permit persons to whom the Software is * - * furnished to do so, subject to the following conditions: * - * * - * The above copyright notice and this permission notice shall be included * - * in all copies or substantial portions of the Software. * - * * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * - * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * - * THE USE OR OTHER DEALINGS IN THE SOFTWARE. * - * * - * Except as contained in this notice, the name(s) of the above copyright * - * holders shall not be used in advertising or otherwise to promote the * - * sale, use or other dealings in this Software without prior written * - * authorization. * - ****************************************************************************/ - -/**************************************************************************** - * Author: Zeyd M. Ben-Halim 1992,1995 * - * and: Eric S. Raymond * - ****************************************************************************/ - -/* - * unctrl.h - * - * Display a printable version of a control character. - * Control characters are displayed in caret notation (^x), DELETE is displayed - * as ^?. Printable characters are displayed as is. - */ - -/* $Id: unctrl.h.in,v 1.11 2009/04/18 21:00:52 tom Exp $ */ - -#ifndef NCURSES_UNCTRL_H_incl -#define NCURSES_UNCTRL_H_incl 1 - -#undef NCURSES_VERSION -#define NCURSES_VERSION "5.9" - -#ifdef __cplusplus -extern "C" { -#endif - -#include - -#undef unctrl -NCURSES_EXPORT(NCURSES_CONST char *) unctrl (chtype); - -#if 1 -NCURSES_EXPORT(NCURSES_CONST char *) NCURSES_SP_NAME(unctrl) (SCREEN*, chtype); -#endif - -#ifdef __cplusplus -} -#endif - -#endif /* NCURSES_UNCTRL_H_incl */ diff --git a/windows/ncurses/lib/Win32/libgcc_s_sjlj-1.dll b/windows/ncurses/lib/Win32/libgcc_s_sjlj-1.dll deleted file mode 100644 index 2f0a309f2..000000000 Binary files a/windows/ncurses/lib/Win32/libgcc_s_sjlj-1.dll and /dev/null differ diff --git a/windows/ncurses/lib/Win32/wform.dll b/windows/ncurses/lib/Win32/wform.dll deleted file mode 100644 index a2b5bb0eb..000000000 Binary files a/windows/ncurses/lib/Win32/wform.dll and /dev/null differ diff --git a/windows/ncurses/lib/Win32/wform.lib b/windows/ncurses/lib/Win32/wform.lib deleted file mode 100644 index 8e36351eb..000000000 Binary files a/windows/ncurses/lib/Win32/wform.lib and /dev/null differ diff --git a/windows/ncurses/lib/Win32/wmenu.dll b/windows/ncurses/lib/Win32/wmenu.dll deleted file mode 100644 index 96853d26e..000000000 Binary files a/windows/ncurses/lib/Win32/wmenu.dll and /dev/null differ diff --git a/windows/ncurses/lib/Win32/wmenu.lib b/windows/ncurses/lib/Win32/wmenu.lib deleted file mode 100644 index 1b129ce63..000000000 Binary files a/windows/ncurses/lib/Win32/wmenu.lib and /dev/null differ diff --git a/windows/ncurses/lib/Win32/wncurses.dll b/windows/ncurses/lib/Win32/wncurses.dll deleted file mode 100644 index f252bd228..000000000 Binary files a/windows/ncurses/lib/Win32/wncurses.dll and /dev/null differ diff --git a/windows/ncurses/lib/Win32/wncurses.lib b/windows/ncurses/lib/Win32/wncurses.lib deleted file mode 100644 index b0ce657a3..000000000 Binary files a/windows/ncurses/lib/Win32/wncurses.lib and /dev/null differ diff --git a/windows/ncurses/lib/Win32/wpanel.dll b/windows/ncurses/lib/Win32/wpanel.dll deleted file mode 100644 index d1c5bbdf7..000000000 Binary files a/windows/ncurses/lib/Win32/wpanel.dll and /dev/null differ diff --git a/windows/ncurses/lib/Win32/wpanel.lib b/windows/ncurses/lib/Win32/wpanel.lib deleted file mode 100644 index 5fcdfb607..000000000 Binary files a/windows/ncurses/lib/Win32/wpanel.lib and /dev/null differ diff --git a/windows/ncurses/lib/x64/wform.dll b/windows/ncurses/lib/x64/wform.dll deleted file mode 100644 index c735974f7..000000000 Binary files a/windows/ncurses/lib/x64/wform.dll and /dev/null differ diff --git a/windows/ncurses/lib/x64/wform.lib b/windows/ncurses/lib/x64/wform.lib deleted file mode 100644 index 1c5fc5600..000000000 Binary files a/windows/ncurses/lib/x64/wform.lib and /dev/null differ diff --git a/windows/ncurses/lib/x64/wmenu.dll b/windows/ncurses/lib/x64/wmenu.dll deleted file mode 100644 index bf11c2978..000000000 Binary files a/windows/ncurses/lib/x64/wmenu.dll and /dev/null differ diff --git a/windows/ncurses/lib/x64/wmenu.lib b/windows/ncurses/lib/x64/wmenu.lib deleted file mode 100644 index a0eb2711b..000000000 Binary files a/windows/ncurses/lib/x64/wmenu.lib and /dev/null differ diff --git a/windows/ncurses/lib/x64/wncurses.dll b/windows/ncurses/lib/x64/wncurses.dll deleted file mode 100644 index ae0d66a4c..000000000 Binary files a/windows/ncurses/lib/x64/wncurses.dll and /dev/null differ diff --git a/windows/ncurses/lib/x64/wncurses.lib b/windows/ncurses/lib/x64/wncurses.lib deleted file mode 100644 index 1d6f182ff..000000000 Binary files a/windows/ncurses/lib/x64/wncurses.lib and /dev/null differ diff --git a/windows/ncurses/lib/x64/wpanel.dll b/windows/ncurses/lib/x64/wpanel.dll deleted file mode 100644 index 42c0ff752..000000000 Binary files a/windows/ncurses/lib/x64/wpanel.dll and /dev/null differ diff --git a/windows/ncurses/lib/x64/wpanel.lib b/windows/ncurses/lib/x64/wpanel.lib deleted file mode 100644 index ff689e449..000000000 Binary files a/windows/ncurses/lib/x64/wpanel.lib and /dev/null differ diff --git a/windows/patches/icu/0001-Upgrade-projects-to-VS2013.patch b/windows/patches/icu/0001-Upgrade-projects-to-VS2013.patch deleted file mode 100644 index 53ab005f5..000000000 --- a/windows/patches/icu/0001-Upgrade-projects-to-VS2013.patch +++ /dev/null @@ -1,2279 +0,0 @@ -From f0d00332540713c5d3e3981a5a29dc0ae226d999 Mon Sep 17 00:00:00 2001 -From: Tim Hughes -Date: Mon, 21 Apr 2014 12:54:15 +0100 -Subject: [PATCH 1/3] Upgrade projects to VS2013 . - -Signed-off-by: Tim Hughes ---- - source/common/common.vcxproj | 42 ++- - source/extra/uconv/uconv.vcxproj | 8 +- - source/i18n/i18n.vcxproj | 48 +-- - source/i18n/i18n.vcxproj.filters | 3 +- - source/io/io.vcxproj | 8 +- - source/layout/layout.vcxproj | 8 +- - source/layoutex/layoutex.vcxproj | 8 +- - source/samples/cal/cal.vcxproj | 528 +++++++++++++++++---------------- - source/samples/date/date.vcxproj | 8 +- - source/stubdata/stubdata.vcxproj | 42 ++- - source/test/cintltst/cintltst.vcxproj | 8 +- - source/test/intltest/intltest.vcxproj | 38 +-- - source/test/iotest/iotest.vcxproj | 8 +- - source/test/letest/letest.vcxproj | 8 +- - source/tools/ctestfw/ctestfw.vcxproj | 8 +- - source/tools/genbrk/genbrk.vcxproj | 8 +- - source/tools/genccode/genccode.vcxproj | 8 +- - source/tools/gencfu/gencfu.vcxproj | 8 +- - source/tools/gencmn/gencmn.vcxproj | 8 +- - source/tools/gencnval/gencnval.vcxproj | 8 +- - source/tools/gendict/gendict.vcxproj | 8 +- - source/tools/gennorm2/gennorm2.vcxproj | 8 +- - source/tools/genrb/derb.vcxproj | 8 +- - source/tools/genrb/genrb.vcxproj | 8 +- - source/tools/gensprep/gensprep.vcxproj | 8 +- - source/tools/gentest/gentest.vcxproj | 8 +- - source/tools/icuinfo/icuinfo.vcxproj | 8 +- - source/tools/icuinfo/testplug.vcxproj | 8 +- - source/tools/icupkg/icupkg.vcxproj | 8 +- - source/tools/makeconv/makeconv.vcxproj | 8 +- - source/tools/pkgdata/pkgdata.vcxproj | 8 +- - source/tools/toolutil/toolutil.vcxproj | 10 +- - 32 files changed, 531 insertions(+), 380 deletions(-) - -diff --git a/source/common/common.vcxproj b/source/common/common.vcxproj -index ef0dfc1..0b1eab3 100644 ---- a/source/common/common.vcxproj -+++ b/source/common/common.vcxproj -@@ -1,5 +1,5 @@ -  -- -+ - - - Debug -@@ -26,21 +26,25 @@ - DynamicLibrary - false - MultiByte -+ v120 - - - DynamicLibrary - false - MultiByte -+ v120 - - - DynamicLibrary - false - MultiByte -+ v120 - - - DynamicLibrary - false - MultiByte -+ v120 - - - -@@ -65,17 +69,33 @@ - - <_ProjectFileVersion>10.0.30319.1 - .\..\..\lib\ -- .\x86\Release\ -+ x86\$(Configuration) - false - .\..\..\lib\ -- .\x86\Debug\ -- true -+ x86\$(Configuration) -+ false - .\x64\Release\ -- .\x64\Release\ -+ x64\$(Configuration) - false - .\x64\Debug\ -- .\x64\Debug\ -- true -+ x64\$(Configuration) -+ false -+ -+ -+ icuuc52d -+ ..\..\bin -+ -+ -+ icuuc52 -+ ..\..\bin -+ -+ -+ icuuc52d -+ ..\..\bin64 -+ -+ -+ icuuc52 -+ ..\..\bin64 - - - -@@ -104,7 +124,6 @@ - 0x0409 - - -- ..\..\bin\icuuc52.dll - true - .\..\..\lib\icuuc.pdb - true -@@ -135,7 +154,6 @@ - .\x86\Debug/ - .\x86\Debug/ - .\x86\Debug/ -- true - Level3 - true - EditAndContinue -@@ -145,7 +163,6 @@ - 0x0409 - - -- ..\..\bin\icuuc52d.dll - true - true - .\..\..\lib\icuucd.pdb -@@ -183,7 +200,6 @@ - 0x0409 - - -- ..\..\bin64\icuuc52.dll - true - .\..\..\lib64\icuuc.pdb - true -@@ -212,7 +228,6 @@ - .\x64\Debug/ - .\x64\Debug/ - .\x64\Debug/ -- true - Level3 - true - ProgramDatabase -@@ -222,7 +237,6 @@ - 0x0409 - - -- ..\..\bin64\icuuc52d.dll - true - true - .\..\..\lib64\icuucd.pdb -@@ -1751,4 +1765,4 @@ - - - -- -+ -\ No newline at end of file -diff --git a/source/extra/uconv/uconv.vcxproj b/source/extra/uconv/uconv.vcxproj -index 3ff795c..1e9829f 100644 ---- a/source/extra/uconv/uconv.vcxproj -+++ b/source/extra/uconv/uconv.vcxproj -@@ -1,5 +1,5 @@ -  -- -+ - - - Debug -@@ -26,21 +26,25 @@ - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - -@@ -292,4 +296,4 @@ - - - -- -+ -\ No newline at end of file -diff --git a/source/i18n/i18n.vcxproj b/source/i18n/i18n.vcxproj -index 3c1eebb..3f216cc 100644 ---- a/source/i18n/i18n.vcxproj -+++ b/source/i18n/i18n.vcxproj -@@ -1,5 +1,5 @@ -- -- -+ -+ - - - Debug -@@ -26,21 +26,25 @@ - DynamicLibrary - false - MultiByte -+ v120 - - - DynamicLibrary - false - MultiByte -+ v120 - - - DynamicLibrary - false - MultiByte -+ v120 - - - DynamicLibrary - false - MultiByte -+ v120 - - - -@@ -64,18 +68,30 @@ - - - <_ProjectFileVersion>10.0.30319.1 -- .\..\..\lib\ -- .\x86\Release\ -+ ..\..\bin -+ x86\$(Configuration) - false -- .\..\..\lib\ -- .\x86\Debug\ -- true -- .\x64\Release\ -- .\x64\Release\ -+ ..\..\bin -+ x86\$(Configuration) -+ false -+ ..\..\bin64 -+ x64\$(Configuration) - false -- .\x64\Debug\ -- .\x64\Debug\ -- true -+ ..\..\bin64 -+ x64\$(Configuration) -+ false -+ -+ -+ icuin52d -+ -+ -+ icuin52 -+ -+ -+ icuin52d -+ -+ -+ icuin52 - - - -@@ -107,7 +123,6 @@ - ../common;%(AdditionalIncludeDirectories) - - -- ..\..\bin\icuin52.dll - true - .\..\..\lib\icuin.pdb - true -@@ -139,7 +154,6 @@ - .\x86\Debug/ - .\x86\Debug/ - .\x86\Debug/ -- true - Level3 - true - EditAndContinue -@@ -151,7 +165,6 @@ - ../common;%(AdditionalIncludeDirectories) - - -- ..\..\bin\icuin52d.dll - true - true - .\..\..\lib\icuind.pdb -@@ -192,7 +205,6 @@ - ../common;%(AdditionalIncludeDirectories) - - -- ..\..\bin64\icuin52.dll - true - .\..\..\lib64\icuin.pdb - true -@@ -222,7 +234,6 @@ - .\x64\Debug/ - .\x64\Debug/ - .\x64\Debug/ -- true - Level3 - true - ProgramDatabase -@@ -234,7 +245,6 @@ - ../common;%(AdditionalIncludeDirectories) - - -- ..\..\bin64\icuin52d.dll - true - true - .\..\..\lib64\icuind.pdb -@@ -1625,4 +1635,4 @@ - - - -- -+ -\ No newline at end of file -diff --git a/source/i18n/i18n.vcxproj.filters b/source/i18n/i18n.vcxproj.filters -index da3b9aa..554a235 100644 ---- a/source/i18n/i18n.vcxproj.filters -+++ b/source/i18n/i18n.vcxproj.filters -@@ -1050,5 +1050,6 @@ - - misc - -+ - -- -+ -\ No newline at end of file -diff --git a/source/io/io.vcxproj b/source/io/io.vcxproj -index 8944e2a..7b5e178 100644 ---- a/source/io/io.vcxproj -+++ b/source/io/io.vcxproj -@@ -1,5 +1,5 @@ -  -- -+ - - - Debug -@@ -26,21 +26,25 @@ - DynamicLibrary - false - MultiByte -+ v120 - - - DynamicLibrary - false - MultiByte -+ v120 - - - DynamicLibrary - false - MultiByte -+ v120 - - - DynamicLibrary - false - MultiByte -+ v120 - - - -@@ -319,4 +323,4 @@ - - - -- -+ -\ No newline at end of file -diff --git a/source/layout/layout.vcxproj b/source/layout/layout.vcxproj -index d80eb54..90a5e42 100644 ---- a/source/layout/layout.vcxproj -+++ b/source/layout/layout.vcxproj -@@ -1,5 +1,5 @@ -  -- -+ - - - Debug -@@ -26,21 +26,25 @@ - DynamicLibrary - false - MultiByte -+ v120 - - - DynamicLibrary - false - MultiByte -+ v120 - - - DynamicLibrary - false - MultiByte -+ v120 - - - DynamicLibrary - false - MultiByte -+ v120 - - - -@@ -576,4 +580,4 @@ - - - -- -+ -\ No newline at end of file -diff --git a/source/layoutex/layoutex.vcxproj b/source/layoutex/layoutex.vcxproj -index dac4cfe..f2c8dd8 100644 ---- a/source/layoutex/layoutex.vcxproj -+++ b/source/layoutex/layoutex.vcxproj -@@ -1,5 +1,5 @@ -  -- -+ - - - Debug -@@ -27,21 +27,25 @@ - DynamicLibrary - false - MultiByte -+ v120 - - - DynamicLibrary - false - MultiByte -+ v120 - - - DynamicLibrary - false - MultiByte -+ v120 - - - DynamicLibrary - false - MultiByte -+ v120 - - - -@@ -327,4 +331,4 @@ - - - -- -+ -\ No newline at end of file -diff --git a/source/samples/cal/cal.vcxproj b/source/samples/cal/cal.vcxproj -index 13dae70..947e173 100644 ---- a/source/samples/cal/cal.vcxproj -+++ b/source/samples/cal/cal.vcxproj -@@ -1,264 +1,268 @@ -- -- -- -- -- Debug -- Win32 -- -- -- Debug -- x64 -- -- -- Release -- Win32 -- -- -- Release -- x64 -- -- -- -- {F7659D77-09CF-4FE9-ACEE-927287AA9509} -- -- -- -- Application -- false -- MultiByte -- -- -- Application -- false -- MultiByte -- -- -- Application -- false -- MultiByte -- -- -- Application -- false -- MultiByte -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- <_ProjectFileVersion>10.0.30319.1 -- .\x86\Release\ -- .\x86\Release\ -- false -- .\x64\Release\ -- .\x64\Release\ -- false -- .\x86\Debug\ -- .\x86\Debug\ -- true -- .\x64\Debug\ -- .\x64\Debug\ -- true -- -- -- -- .\x86\Release/cal.tlb -- -- -- OnlyExplicitInline -- ..\..\..\include;%(AdditionalIncludeDirectories) -- WIN32;NDEBUG;_CRT_SECURE_NO_DEPRECATE;%(PreprocessorDefinitions) -- true -- MultiThreadedDLL -- true -- true -- -- -- .\x86\Release/cal.pch -- .\x86\Release/ -- .\x86\Release/ -- .\x86\Release/ -- Level3 -- true -- Default -- -- -- NDEBUG;%(PreprocessorDefinitions) -- 0x0409 -- -- -- icuuc.lib;icuin.lib;%(AdditionalDependencies) -- .\x86\Release/cal.exe -- true -- ../../../lib;%(AdditionalLibraryDirectories) -- .\x86\Release/cal.pdb -- Console -- false -- -- -- -- -- -- -- X64 -- .\x64\Release/cal.tlb -- -- -- OnlyExplicitInline -- ..\..\..\include;%(AdditionalIncludeDirectories) -- WIN64;WIN32;NDEBUG;_CRT_SECURE_NO_DEPRECATE;%(PreprocessorDefinitions) -- true -- MultiThreadedDLL -- true -- true -- -- -- .\x64\Release/cal.pch -- .\x64\Release/ -- .\x64\Release/ -- .\x64\Release/ -- Level3 -- true -- Default -- -- -- NDEBUG;%(PreprocessorDefinitions) -- 0x0409 -- -- -- icuuc.lib;icuin.lib;%(AdditionalDependencies) -- .\x64\Release/cal.exe -- true -- ../../../lib64;%(AdditionalLibraryDirectories) -- .\x64\Release/cal.pdb -- Console -- false -- -- -- MachineX64 -- -- -- -- -- .\x86\Debug/cal.tlb -- -- -- Disabled -- ..\..\..\include;%(AdditionalIncludeDirectories) -- WIN32;_DEBUG;_CRT_SECURE_NO_DEPRECATE;%(PreprocessorDefinitions) -- EnableFastChecks -- MultiThreadedDebugDLL -- true -- -- -- .\x86\Debug/cal.pch -- .\x86\Debug/ -- .\x86\Debug/ -- .\x86\Debug/ -- true -- Level3 -- true -- EditAndContinue -- Default -- -- -- _DEBUG;%(PreprocessorDefinitions) -- 0x0409 -- -- -- icuucd.lib;icuind.lib;%(AdditionalDependencies) -- .\x86\Debug/cal.exe -- true -- ../../../lib;%(AdditionalLibraryDirectories) -- true -- .\x86\Debug/cal.pdb -- Console -- false -- -- -- -- -- -- -- X64 -- .\x64\Debug/cal.tlb -- -- -- Disabled -- ..\..\..\include;%(AdditionalIncludeDirectories) -- WIN64;WIN32;_DEBUG;_CRT_SECURE_NO_DEPRECATE;%(PreprocessorDefinitions) -- EnableFastChecks -- MultiThreadedDebugDLL -- true -- -- -- .\x64\Debug/cal.pch -- .\x64\Debug/ -- .\x64\Debug/ -- .\x64\Debug/ -- true -- Level3 -- true -- ProgramDatabase -- Default -- -- -- _DEBUG;%(PreprocessorDefinitions) -- 0x0409 -- -- -- icuucd.lib;icuind.lib;%(AdditionalDependencies) -- .\x64\Debug/cal.exe -- true -- ../../../lib64;%(AdditionalLibraryDirectories) -- true -- .\x64\Debug/cal.pdb -- Console -- false -- -- -- MachineX64 -- -- -- -+ -+ -+ -+ -+ Debug -+ Win32 -+ -+ -+ Debug -+ x64 -+ -+ -+ Release -+ Win32 -+ -+ -+ Release -+ x64 -+ -+ -+ -+ {F7659D77-09CF-4FE9-ACEE-927287AA9509} -+ -+ -+ -+ Application -+ false -+ MultiByte -+ v120 -+ -+ -+ Application -+ false -+ MultiByte -+ v120 -+ -+ -+ Application -+ false -+ MultiByte -+ v120 -+ -+ -+ Application -+ false -+ MultiByte -+ v120 -+ -+ -+ -+ -+ -+ -+ -+ -+ -+ -+ -+ -+ -+ -+ -+ -+ -+ -+ -+ -+ -+ -+ <_ProjectFileVersion>10.0.30319.1 -+ .\x86\Release\ -+ .\x86\Release\ -+ false -+ .\x64\Release\ -+ .\x64\Release\ -+ false -+ .\x86\Debug\ -+ .\x86\Debug\ -+ true -+ .\x64\Debug\ -+ .\x64\Debug\ -+ true -+ -+ -+ -+ .\x86\Release/cal.tlb -+ -+ -+ OnlyExplicitInline -+ ..\..\..\include;%(AdditionalIncludeDirectories) -+ WIN32;NDEBUG;_CRT_SECURE_NO_DEPRECATE;%(PreprocessorDefinitions) -+ true -+ MultiThreadedDLL -+ true -+ true -+ -+ -+ .\x86\Release/cal.pch -+ .\x86\Release/ -+ .\x86\Release/ -+ .\x86\Release/ -+ Level3 -+ true -+ Default -+ -+ -+ NDEBUG;%(PreprocessorDefinitions) -+ 0x0409 -+ -+ -+ icuuc.lib;icuin.lib;%(AdditionalDependencies) -+ .\x86\Release/cal.exe -+ true -+ ../../../lib;%(AdditionalLibraryDirectories) -+ .\x86\Release/cal.pdb -+ Console -+ false -+ -+ -+ -+ -+ -+ -+ X64 -+ .\x64\Release/cal.tlb -+ -+ -+ OnlyExplicitInline -+ ..\..\..\include;%(AdditionalIncludeDirectories) -+ WIN64;WIN32;NDEBUG;_CRT_SECURE_NO_DEPRECATE;%(PreprocessorDefinitions) -+ true -+ MultiThreadedDLL -+ true -+ true -+ -+ -+ .\x64\Release/cal.pch -+ .\x64\Release/ -+ .\x64\Release/ -+ .\x64\Release/ -+ Level3 -+ true -+ Default -+ -+ -+ NDEBUG;%(PreprocessorDefinitions) -+ 0x0409 -+ -+ -+ icuuc.lib;icuin.lib;%(AdditionalDependencies) -+ .\x64\Release/cal.exe -+ true -+ ../../../lib64;%(AdditionalLibraryDirectories) -+ .\x64\Release/cal.pdb -+ Console -+ false -+ -+ -+ MachineX64 -+ -+ -+ -+ -+ .\x86\Debug/cal.tlb -+ -+ -+ Disabled -+ ..\..\..\include;%(AdditionalIncludeDirectories) -+ WIN32;_DEBUG;_CRT_SECURE_NO_DEPRECATE;%(PreprocessorDefinitions) -+ EnableFastChecks -+ MultiThreadedDebugDLL -+ true -+ -+ -+ .\x86\Debug/cal.pch -+ .\x86\Debug/ -+ .\x86\Debug/ -+ .\x86\Debug/ -+ true -+ Level3 -+ true -+ EditAndContinue -+ Default -+ -+ -+ _DEBUG;%(PreprocessorDefinitions) -+ 0x0409 -+ -+ -+ icuucd.lib;icuind.lib;%(AdditionalDependencies) -+ .\x86\Debug/cal.exe -+ true -+ ../../../lib;%(AdditionalLibraryDirectories) -+ true -+ .\x86\Debug/cal.pdb -+ Console -+ false -+ -+ -+ -+ -+ -+ -+ X64 -+ .\x64\Debug/cal.tlb -+ -+ -+ Disabled -+ ..\..\..\include;%(AdditionalIncludeDirectories) -+ WIN64;WIN32;_DEBUG;_CRT_SECURE_NO_DEPRECATE;%(PreprocessorDefinitions) -+ EnableFastChecks -+ MultiThreadedDebugDLL -+ true -+ -+ -+ .\x64\Debug/cal.pch -+ .\x64\Debug/ -+ .\x64\Debug/ -+ .\x64\Debug/ -+ true -+ Level3 -+ true -+ ProgramDatabase -+ Default -+ -+ -+ _DEBUG;%(PreprocessorDefinitions) -+ 0x0409 -+ -+ -+ icuucd.lib;icuind.lib;%(AdditionalDependencies) -+ .\x64\Debug/cal.exe -+ true -+ ../../../lib64;%(AdditionalLibraryDirectories) -+ true -+ .\x64\Debug/cal.pdb -+ Console -+ false -+ -+ -+ MachineX64 -+ -+ -+ - -- false -- -+ false -+ - -- false -- -- -- -- -- -- -- -- {73c0a65b-d1f2-4de1-b3a6-15dad2c23f3d} -- false -- -- -- {0178b127-6269-407d-b112-93877bb62776} -- false -- -- -- -- -- -- -+ false -+ -+ -+ -+ -+ -+ -+ -+ {73c0a65b-d1f2-4de1-b3a6-15dad2c23f3d} -+ false -+ -+ -+ {0178b127-6269-407d-b112-93877bb62776} -+ false -+ -+ -+ -+ -+ -+ -\ No newline at end of file -diff --git a/source/samples/date/date.vcxproj b/source/samples/date/date.vcxproj -index 0632b3f..38d70a9 100644 ---- a/source/samples/date/date.vcxproj -+++ b/source/samples/date/date.vcxproj -@@ -1,5 +1,5 @@ -  -- -+ - - - Debug -@@ -26,21 +26,25 @@ - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - -@@ -255,4 +259,4 @@ - - - -- -+ -\ No newline at end of file -diff --git a/source/stubdata/stubdata.vcxproj b/source/stubdata/stubdata.vcxproj -index ed4ca6b..541f19f 100644 ---- a/source/stubdata/stubdata.vcxproj -+++ b/source/stubdata/stubdata.vcxproj -@@ -1,5 +1,5 @@ -  -- -+ - - - Debug -@@ -26,21 +26,25 @@ - DynamicLibrary - false - MultiByte -+ v120 - - - DynamicLibrary - false - MultiByte -+ v120 - - - DynamicLibrary - false - MultiByte -+ v120 - - - DynamicLibrary - false - MultiByte -+ v120 - - - -@@ -64,21 +68,35 @@ - - - <_ProjectFileVersion>10.0.30319.1 -- .\x86\Release\ -- .\x86\Release\ -+ ..\..\bin - false - false -- .\x86\Debug\ -- .\x86\Debug\ -+ ..\..\bin - false -- .\x64\Release\ -- .\x64\Release\ -+ ..\..\bin64 - false - false -- .\x64\Debug\ -- .\x64\Debug\ -+ ..\..\bin64 - false - -+ -+ icudt52d -+ x86\$(Configuration) -+ false -+ -+ -+ icudt52d -+ x64\$(Configuration) -+ false -+ -+ -+ icudt52 -+ x86\$(Configuration) -+ -+ -+ icudt52 -+ x64\$(Configuration) -+ - - - NDEBUG;%(PreprocessorDefinitions) -@@ -113,7 +131,6 @@ - echo "File with stubdata build time, used as a dependency to trigger fresh data build, since stubdata dll will overwrite the real one." > "$(ProjectDir)stubdatabuilt.txt" - - -- ..\..\bin\icudt52.dll - true - true - .\x86\Release\icudt.pdb -@@ -160,7 +177,6 @@ - echo "File with stubdata build time, used as a dependency to trigger fresh data build, since stubdata dll will overwrite the real one." > "$(ProjectDir)stubdatabuilt.txt" - - -- ..\..\bin\icudt52.dll - true - .\x86\Debug/icudt.pdb - true -@@ -207,7 +223,6 @@ - echo "File with stubdata build time, used as a dependency to trigger fresh data build, since stubdata dll will overwrite the real one." > "$(ProjectDir)stubdatabuilt.txt" - - -- ..\..\bin64\icudt52.dll - true - true - .\x64\Release\icudt.pdb -@@ -252,7 +267,6 @@ - echo "File with stubdata build time, used as a dependency to trigger fresh data build, since stubdata dll will overwrite the real one." > "$(ProjectDir)stubdatabuilt.txt" - - -- ..\..\bin64\icudt52.dll - true - .\x64\Debug/icudt.pdb - true -@@ -277,4 +291,4 @@ - - - -- -+ -\ No newline at end of file -diff --git a/source/test/cintltst/cintltst.vcxproj b/source/test/cintltst/cintltst.vcxproj -index 17529b6..f04da0c 100644 ---- a/source/test/cintltst/cintltst.vcxproj -+++ b/source/test/cintltst/cintltst.vcxproj -@@ -1,5 +1,5 @@ -  -- -+ - - - Debug -@@ -26,21 +26,25 @@ - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - -@@ -373,4 +377,4 @@ - - - -- -+ -\ No newline at end of file -diff --git a/source/test/intltest/intltest.vcxproj b/source/test/intltest/intltest.vcxproj -index 8a6698e..9ee9bc7 100644 ---- a/source/test/intltest/intltest.vcxproj -+++ b/source/test/intltest/intltest.vcxproj -@@ -1,5 +1,5 @@ -  -- -+ - - - Debug -@@ -27,21 +27,25 @@ - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - -@@ -229,7 +233,7 @@ - - - -- false -+ false - - - -@@ -260,7 +264,7 @@ - - - -- false -+ false - - - false -@@ -276,7 +280,7 @@ - - - -- false -+ false - - - -@@ -284,7 +288,7 @@ - - - -- false -+ false - - - -@@ -326,13 +330,13 @@ - - - -- false -+ false - - - - - -- false -+ false - - - false -@@ -351,7 +355,7 @@ - - - -- false -+ false - - - -@@ -360,35 +364,35 @@ - - - -- false -+ false - - -- false -+ false - - -- false -+ false - - - - - -- false -+ false - - - - -- false -+ false - - -- false -+ false - - -- false -+ false - - - - -- false -+ false - - - -@@ -561,4 +565,4 @@ - - - -- -+ -\ No newline at end of file -diff --git a/source/test/iotest/iotest.vcxproj b/source/test/iotest/iotest.vcxproj -index 0d39d29..5172208 100644 ---- a/source/test/iotest/iotest.vcxproj -+++ b/source/test/iotest/iotest.vcxproj -@@ -1,5 +1,5 @@ -  -- -+ - - - Debug -@@ -26,21 +26,25 @@ - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - -@@ -259,4 +263,4 @@ - - - -- -+ -\ No newline at end of file -diff --git a/source/test/letest/letest.vcxproj b/source/test/letest/letest.vcxproj -index a71d629..be01399 100644 ---- a/source/test/letest/letest.vcxproj -+++ b/source/test/letest/letest.vcxproj -@@ -1,5 +1,5 @@ -  -- -+ - - - Debug -@@ -26,21 +26,25 @@ - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - -@@ -274,4 +278,4 @@ - - - -- -+ -\ No newline at end of file -diff --git a/source/tools/ctestfw/ctestfw.vcxproj b/source/tools/ctestfw/ctestfw.vcxproj -index 7dbdc9f..9281a1b 100644 ---- a/source/tools/ctestfw/ctestfw.vcxproj -+++ b/source/tools/ctestfw/ctestfw.vcxproj -@@ -1,5 +1,5 @@ -  -- -+ - - - Debug -@@ -26,21 +26,25 @@ - DynamicLibrary - false - MultiByte -+ v120 - - - DynamicLibrary - false - MultiByte -+ v120 - - - DynamicLibrary - false - MultiByte -+ v120 - - - DynamicLibrary - false - MultiByte -+ v120 - - - -@@ -280,4 +284,4 @@ - - - -- -+ -\ No newline at end of file -diff --git a/source/tools/genbrk/genbrk.vcxproj b/source/tools/genbrk/genbrk.vcxproj -index 73e5372..8ae2620 100644 ---- a/source/tools/genbrk/genbrk.vcxproj -+++ b/source/tools/genbrk/genbrk.vcxproj -@@ -1,5 +1,5 @@ -  -- -+ - - - Debug -@@ -26,21 +26,25 @@ - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - -@@ -255,4 +259,4 @@ - - - -- -+ -\ No newline at end of file -diff --git a/source/tools/genccode/genccode.vcxproj b/source/tools/genccode/genccode.vcxproj -index f6fd59d..e1bb8fb 100644 ---- a/source/tools/genccode/genccode.vcxproj -+++ b/source/tools/genccode/genccode.vcxproj -@@ -1,5 +1,5 @@ -  -- -+ - - - Debug -@@ -26,21 +26,25 @@ - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - -@@ -251,4 +255,4 @@ - - - -- -+ -\ No newline at end of file -diff --git a/source/tools/gencfu/gencfu.vcxproj b/source/tools/gencfu/gencfu.vcxproj -index 18c63a6..315ca7b 100644 ---- a/source/tools/gencfu/gencfu.vcxproj -+++ b/source/tools/gencfu/gencfu.vcxproj -@@ -1,5 +1,5 @@ -  -- -+ - - - Debug -@@ -27,20 +27,24 @@ - Application - false - MultiByte -+ v120 - - - Application - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - -@@ -238,4 +242,4 @@ - - - -- -+ -\ No newline at end of file -diff --git a/source/tools/gencmn/gencmn.vcxproj b/source/tools/gencmn/gencmn.vcxproj -index 6c83ef4..91f0a64 100644 ---- a/source/tools/gencmn/gencmn.vcxproj -+++ b/source/tools/gencmn/gencmn.vcxproj -@@ -1,5 +1,5 @@ -  -- -+ - - - Debug -@@ -26,21 +26,25 @@ - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - -@@ -255,4 +259,4 @@ - - - -- -+ -\ No newline at end of file -diff --git a/source/tools/gencnval/gencnval.vcxproj b/source/tools/gencnval/gencnval.vcxproj -index ca12c12..474f1a2 100644 ---- a/source/tools/gencnval/gencnval.vcxproj -+++ b/source/tools/gencnval/gencnval.vcxproj -@@ -1,5 +1,5 @@ -  -- -+ - - - Debug -@@ -26,21 +26,25 @@ - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - -@@ -255,4 +259,4 @@ - - - -- -+ -\ No newline at end of file -diff --git a/source/tools/gendict/gendict.vcxproj b/source/tools/gendict/gendict.vcxproj -index 6852b44..968f817 100644 ---- a/source/tools/gendict/gendict.vcxproj -+++ b/source/tools/gendict/gendict.vcxproj -@@ -1,5 +1,5 @@ -  -- -+ - - - Debug -@@ -26,21 +26,25 @@ - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - -@@ -255,4 +259,4 @@ - - - -- -+ -\ No newline at end of file -diff --git a/source/tools/gennorm2/gennorm2.vcxproj b/source/tools/gennorm2/gennorm2.vcxproj -index 4245a0b..bf60570 100644 ---- a/source/tools/gennorm2/gennorm2.vcxproj -+++ b/source/tools/gennorm2/gennorm2.vcxproj -@@ -1,5 +1,5 @@ -  -- -+ - - - Debug -@@ -27,20 +27,24 @@ - - Application - Unicode -+ v120 - - - Application - Unicode - true -+ v120 - - - Application - Unicode -+ v120 - - - Application - Unicode - true -+ v120 - - - -@@ -263,4 +267,4 @@ - - - -- -+ -\ No newline at end of file -diff --git a/source/tools/genrb/derb.vcxproj b/source/tools/genrb/derb.vcxproj -index b2e27e6..9c14c94 100644 ---- a/source/tools/genrb/derb.vcxproj -+++ b/source/tools/genrb/derb.vcxproj -@@ -1,5 +1,5 @@ -  -- -+ - - - Debug -@@ -26,21 +26,25 @@ - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - -@@ -278,4 +282,4 @@ - - - -- -+ -\ No newline at end of file -diff --git a/source/tools/genrb/genrb.vcxproj b/source/tools/genrb/genrb.vcxproj -index b7f48ef..ad02f5b 100644 ---- a/source/tools/genrb/genrb.vcxproj -+++ b/source/tools/genrb/genrb.vcxproj -@@ -1,5 +1,5 @@ -  -- -+ - - - Debug -@@ -26,21 +26,25 @@ - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - -@@ -278,4 +282,4 @@ - - - -- -+ -\ No newline at end of file -diff --git a/source/tools/gensprep/gensprep.vcxproj b/source/tools/gensprep/gensprep.vcxproj -index 533b546..fad1e63 100644 ---- a/source/tools/gensprep/gensprep.vcxproj -+++ b/source/tools/gensprep/gensprep.vcxproj -@@ -1,5 +1,5 @@ -  -- -+ - - - Debug -@@ -26,21 +26,25 @@ - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - -@@ -257,4 +261,4 @@ - - - -- -+ -\ No newline at end of file -diff --git a/source/tools/gentest/gentest.vcxproj b/source/tools/gentest/gentest.vcxproj -index f8fb903..96a8b15 100644 ---- a/source/tools/gentest/gentest.vcxproj -+++ b/source/tools/gentest/gentest.vcxproj -@@ -1,5 +1,5 @@ -  -- -+ - - - Debug -@@ -27,21 +27,25 @@ - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - -@@ -244,4 +248,4 @@ - - - -- -+ -\ No newline at end of file -diff --git a/source/tools/icuinfo/icuinfo.vcxproj b/source/tools/icuinfo/icuinfo.vcxproj -index 6da52ed..864b5e7 100644 ---- a/source/tools/icuinfo/icuinfo.vcxproj -+++ b/source/tools/icuinfo/icuinfo.vcxproj -@@ -1,5 +1,5 @@ -  -- -+ - - - Debug -@@ -28,21 +28,25 @@ - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - -@@ -256,4 +260,4 @@ - - - -- -+ -\ No newline at end of file -diff --git a/source/tools/icuinfo/testplug.vcxproj b/source/tools/icuinfo/testplug.vcxproj -index edf6858..cc5a0ec 100644 ---- a/source/tools/icuinfo/testplug.vcxproj -+++ b/source/tools/icuinfo/testplug.vcxproj -@@ -1,5 +1,5 @@ -  -- -+ - - - Debug -@@ -26,21 +26,25 @@ - DynamicLibrary - false - MultiByte -+ v120 - - - DynamicLibrary - false - MultiByte -+ v120 - - - DynamicLibrary - false - MultiByte -+ v120 - - - DynamicLibrary - false - MultiByte -+ v120 - - - -@@ -255,4 +259,4 @@ - - - -- -+ -\ No newline at end of file -diff --git a/source/tools/icupkg/icupkg.vcxproj b/source/tools/icupkg/icupkg.vcxproj -index b3c762c..606276d 100644 ---- a/source/tools/icupkg/icupkg.vcxproj -+++ b/source/tools/icupkg/icupkg.vcxproj -@@ -1,5 +1,5 @@ -  -- -+ - - - Debug -@@ -27,21 +27,25 @@ - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - -@@ -244,4 +248,4 @@ - - - -- -+ -\ No newline at end of file -diff --git a/source/tools/makeconv/makeconv.vcxproj b/source/tools/makeconv/makeconv.vcxproj -index 110dee9..3d302d3 100644 ---- a/source/tools/makeconv/makeconv.vcxproj -+++ b/source/tools/makeconv/makeconv.vcxproj -@@ -1,5 +1,5 @@ -  -- -+ - - - Debug -@@ -26,21 +26,25 @@ - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - -@@ -260,4 +264,4 @@ - - - -- -+ -\ No newline at end of file -diff --git a/source/tools/pkgdata/pkgdata.vcxproj b/source/tools/pkgdata/pkgdata.vcxproj -index 18fa39d..b2d72bd 100644 ---- a/source/tools/pkgdata/pkgdata.vcxproj -+++ b/source/tools/pkgdata/pkgdata.vcxproj -@@ -1,5 +1,5 @@ -  -- -+ - - - Debug -@@ -26,21 +26,25 @@ - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - Application - false - MultiByte -+ v120 - - - -@@ -271,4 +275,4 @@ - - - -- -+ -\ No newline at end of file -diff --git a/source/tools/toolutil/toolutil.vcxproj b/source/tools/toolutil/toolutil.vcxproj -index 8cb1277..5574582 100644 ---- a/source/tools/toolutil/toolutil.vcxproj -+++ b/source/tools/toolutil/toolutil.vcxproj -@@ -1,5 +1,5 @@ -  -- -+ - - - Debug -@@ -26,21 +26,25 @@ - DynamicLibrary - false - MultiByte -+ v120 - - - DynamicLibrary - false - MultiByte -+ v120 - - - DynamicLibrary - false - MultiByte -+ v120 - - - DynamicLibrary - false - MultiByte -+ v120 - - - -@@ -267,7 +271,7 @@ - - - -- false -+ false - - - false -@@ -328,4 +332,4 @@ - - - -- -+ -\ No newline at end of file --- -1.9.0.msysgit.0 - diff --git a/windows/patches/icu/0002-Qt-requires-U_CHARSET_IS_UTF8-1.patch b/windows/patches/icu/0002-Qt-requires-U_CHARSET_IS_UTF8-1.patch deleted file mode 100644 index 5b9f3e959..000000000 --- a/windows/patches/icu/0002-Qt-requires-U_CHARSET_IS_UTF8-1.patch +++ /dev/null @@ -1,26 +0,0 @@ -From fca4313ae7ac54ebb5a6f3b46451306223b53aeb Mon Sep 17 00:00:00 2001 -From: Tim Hughes -Date: Mon, 21 Apr 2014 13:33:29 +0100 -Subject: [PATCH 2/3] Qt requires U_CHARSET_IS_UTF8 1 - -Signed-off-by: Tim Hughes ---- - source/common/unicode/platform.h | 2 +- - 1 file changed, 1 insertion(+), 1 deletion(-) - -diff --git a/source/common/unicode/platform.h b/source/common/unicode/platform.h -index 1b2ab30..cca7039 100644 ---- a/source/common/unicode/platform.h -+++ b/source/common/unicode/platform.h -@@ -543,7 +543,7 @@ - #elif U_PLATFORM == U_PF_ANDROID || U_PLATFORM_IS_DARWIN_BASED - # define U_CHARSET_IS_UTF8 1 - #else --# define U_CHARSET_IS_UTF8 0 -+# define U_CHARSET_IS_UTF8 1 - #endif - - /** @} */ --- -1.9.0.msysgit.0 - diff --git a/windows/patches/icu/0003-Add-minimal-icu.sln.patch b/windows/patches/icu/0003-Add-minimal-icu.sln.patch deleted file mode 100644 index 62ce164d8..000000000 --- a/windows/patches/icu/0003-Add-minimal-icu.sln.patch +++ /dev/null @@ -1,71 +0,0 @@ -From dcb7b9172a3f7ec5d607696a86fefad69c03a400 Mon Sep 17 00:00:00 2001 -From: Tim Hughes -Date: Mon, 21 Apr 2014 13:33:59 +0100 -Subject: [PATCH 3/3] Add minimal icu.sln - -Signed-off-by: Tim Hughes ---- - source/allinone/icu.sln | 51 +++++++++++++++++++++++++++++++++++++++++++++++++ - 1 file changed, 51 insertions(+) - create mode 100644 source/allinone/icu.sln - -diff --git a/source/allinone/icu.sln b/source/allinone/icu.sln -new file mode 100644 -index 0000000..b09697f ---- /dev/null -+++ b/source/allinone/icu.sln -@@ -0,0 +1,51 @@ -+Microsoft Visual Studio Solution File, Format Version 12.00 -+# Visual Studio Express 2013 for Windows Desktop -+VisualStudioVersion = 12.0.21005.1 -+MinimumVisualStudioVersion = 10.0.40219.1 -+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "common", "..\common\common.vcxproj", "{73C0A65B-D1F2-4DE1-B3A6-15DAD2C23F3D}" -+EndProject -+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "i18n", "..\i18n\i18n.vcxproj", "{0178B127-6269-407D-B112-93877BB62776}" -+EndProject -+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "stubdata", "..\stubdata\stubdata.vcxproj", "{203EC78A-0531-43F0-A636-285439BDE025}" -+EndProject -+Global -+ GlobalSection(SolutionConfigurationPlatforms) = preSolution -+ Debug|Win32 = Debug|Win32 -+ Debug|x64 = Debug|x64 -+ Release|Win32 = Release|Win32 -+ Release|x64 = Release|x64 -+ EndGlobalSection -+ GlobalSection(ProjectConfigurationPlatforms) = postSolution -+ {73C0A65B-D1F2-4DE1-B3A6-15DAD2C23F3D}.Debug|Win32.ActiveCfg = Debug|Win32 -+ {73C0A65B-D1F2-4DE1-B3A6-15DAD2C23F3D}.Debug|Win32.Build.0 = Debug|Win32 -+ {73C0A65B-D1F2-4DE1-B3A6-15DAD2C23F3D}.Debug|x64.ActiveCfg = Debug|x64 -+ {73C0A65B-D1F2-4DE1-B3A6-15DAD2C23F3D}.Debug|x64.Build.0 = Debug|x64 -+ {73C0A65B-D1F2-4DE1-B3A6-15DAD2C23F3D}.Release|Win32.ActiveCfg = Release|Win32 -+ {73C0A65B-D1F2-4DE1-B3A6-15DAD2C23F3D}.Release|Win32.Build.0 = Release|Win32 -+ {73C0A65B-D1F2-4DE1-B3A6-15DAD2C23F3D}.Release|x64.ActiveCfg = Release|x64 -+ {73C0A65B-D1F2-4DE1-B3A6-15DAD2C23F3D}.Release|x64.Build.0 = Release|x64 -+ {0178B127-6269-407D-B112-93877BB62776}.Debug|Win32.ActiveCfg = Debug|Win32 -+ {0178B127-6269-407D-B112-93877BB62776}.Debug|Win32.Build.0 = Debug|Win32 -+ {0178B127-6269-407D-B112-93877BB62776}.Debug|x64.ActiveCfg = Debug|x64 -+ {0178B127-6269-407D-B112-93877BB62776}.Debug|x64.Build.0 = Debug|x64 -+ {0178B127-6269-407D-B112-93877BB62776}.Release|Win32.ActiveCfg = Release|Win32 -+ {0178B127-6269-407D-B112-93877BB62776}.Release|Win32.Build.0 = Release|Win32 -+ {0178B127-6269-407D-B112-93877BB62776}.Release|x64.ActiveCfg = Release|x64 -+ {0178B127-6269-407D-B112-93877BB62776}.Release|x64.Build.0 = Release|x64 -+ {203EC78A-0531-43F0-A636-285439BDE025}.Debug|Win32.ActiveCfg = Debug|Win32 -+ {203EC78A-0531-43F0-A636-285439BDE025}.Debug|Win32.Build.0 = Debug|Win32 -+ {203EC78A-0531-43F0-A636-285439BDE025}.Debug|x64.ActiveCfg = Debug|x64 -+ {203EC78A-0531-43F0-A636-285439BDE025}.Debug|x64.Build.0 = Debug|x64 -+ {203EC78A-0531-43F0-A636-285439BDE025}.Release|Win32.ActiveCfg = Release|Win32 -+ {203EC78A-0531-43F0-A636-285439BDE025}.Release|Win32.Build.0 = Release|Win32 -+ {203EC78A-0531-43F0-A636-285439BDE025}.Release|x64.ActiveCfg = Release|x64 -+ {203EC78A-0531-43F0-A636-285439BDE025}.Release|x64.Build.0 = Release|x64 -+ EndGlobalSection -+ GlobalSection(SolutionProperties) = preSolution -+ HideSolutionNode = FALSE -+ EndGlobalSection -+ GlobalSection(SubversionScc) = preSolution -+ Svn-Managed = True -+ Manager = AnkhSVN - Subversion Support for Visual Studio -+ EndGlobalSection -+EndGlobal --- -1.9.0.msysgit.0 - diff --git a/windows/qt_plugin_import.cpp b/windows/qt_plugin_import.cpp deleted file mode 100644 index b3afd8a4e..000000000 --- a/windows/qt_plugin_import.cpp +++ /dev/null @@ -1,4 +0,0 @@ -// This file is autogenerated by qmake. It imports static plugin classes for -// static plugins specified using QTPLUGIN and QT_PLUGIN_CLASS. variables. -#include -Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin) diff --git a/windows/stdafx.h b/windows/stdafx.h deleted file mode 100644 index 5a4e4d27d..000000000 --- a/windows/stdafx.h +++ /dev/null @@ -1,60 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - cpp-ethereum is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with cpp-ethereum. If not, see . -*/ -/** @file stdafx.h - * @author Tim Hughes - * @date 2014 - */ - -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#include -#include -#include -#include - -#pragma warning(push) -#pragma warning(disable: 4100 4267) -#include -#pragma warning(pop) - -