<commit_before>/*

Copyright (c) 2007, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include "libtorrent/pch.hpp"

#include "libtorrent/lsd.hpp"
#include "libtorrent/io.hpp"
#include "libtorrent/http_tracker_connection.hpp"

#include <boost/bind.hpp>
#include <boost/ref.hpp>
#include <asio/ip/host_name.hpp>
#include <asio/ip/multicast.hpp>
#include <boost/thread/mutex.hpp>
#include <cstdlib>
#include <boost/config.hpp>

using boost::bind;
using namespace libtorrent;

namespace libtorrent
{
	// defined in broadcast_socket.cpp
	address guess_local_address(asio::io_service&);
}

lsd::lsd(io_service& ios, address const& listen_interface
	, peer_callback_t const& cb)
	: m_callback(cb)
	, m_retry_count(0)
	, m_socket(ios, udp::endpoint(address_v4::from_string("239.192.152.143"), 6771)
		, bind(&lsd::on_announce, self(), _1, _2, _3))
	, m_broadcast_timer(ios)
	, m_disabled(false)
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
	m_log.open("lsd.log", std::ios::in | std::ios::out | std::ios::trunc);
#endif
}

lsd::~lsd() {}

void lsd::announce(sha1_hash const& ih, int listen_port)
{
	if (m_disabled) return;

	std::stringstream btsearch;
	btsearch << "BT-SEARCH * HTTP/1.1\r\n"
		"Host: 239.192.152.143:6771\r\n"
		"Port: " << listen_port << "\r\n"
		"Infohash: " << ih << "\r\n"
		"\r\n\r\n";
	std::string const& msg = btsearch.str();

	m_retry_count = 0;
	asio::error_code ec;
	m_socket.send(msg.c_str(), int(msg.size()), ec);
	if (ec)
	{
		m_disabled = true;
		return;
	}

#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
	m_log << time_now_string()
		<< " ==> announce: ih: " << ih << " port: " << listen_port << std::endl;
#endif

	m_broadcast_timer.expires_from_now(milliseconds(250 * m_retry_count));
	m_broadcast_timer.async_wait(bind(&lsd::resend_announce, self(), _1, msg));
}

void lsd::resend_announce(asio::error_code const& e, std::string msg) try
{
	if (e) return;

	asio::error_code ec;
	m_socket.send(msg.c_str(), int(msg.size()), ec);

	++m_retry_count;
	if (m_retry_count >= 5)
		return;

	m_broadcast_timer.expires_from_now(milliseconds(250 * m_retry_count));
	m_broadcast_timer.async_wait(bind(&lsd::resend_announce, self(), _1, msg));
}
catch (std::exception&)
{}

void lsd::on_announce(udp::endpoint const& from, char* buffer
	, std::size_t bytes_transferred)
{
	using namespace libtorrent::detail;

	http_parser p;

	p.incoming(buffer::const_interval(buffer, buffer + bytes_transferred));

	if (!p.header_finished())
	{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
	m_log << time_now_string()
		<< " <== announce: incomplete HTTP message\n";
#endif
		return;
	}

	if (p.method() != "bt-search")
	{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
	m_log << time_now_string()
		<< " <== announce: invalid HTTP method: " << p.method() << std::endl;
#endif
		return;
	}

	std::string const& port_str = p.header("port");
	if (port_str.empty())
	{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
	m_log << time_now_string()
		<< " <== announce: invalid BT-SEARCH, missing port" << std::endl;
#endif
		return;
	}

	std::string const& ih_str = p.header("infohash");
	if (ih_str.empty())
	{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
	m_log << time_now_string()
		<< " <== announce: invalid BT-SEARCH, missing infohash" << std::endl;
#endif
		return;
	}

	sha1_hash ih(0);
	std::istringstream ih_sstr(ih_str);
	ih_sstr >> ih;
	int port = atoi(port_str.c_str());

	if (!ih.is_all_zeros() && port != 0)
	{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
		m_log << time_now_string()
			<< " *** incoming local announce " << from.address()
			<< ":" << port << " ih: " << ih << std::endl;
#endif
		// we got an announce, pass it on through the callback
		try { m_callback(tcp::endpoint(from.address(), port), ih); }
		catch (std::exception&) {}
	}
}

void lsd::close()
{
	m_socket.close();
}

<commit_msg>lsd close fix<commit_after>/*

Copyright (c) 2007, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include "libtorrent/pch.hpp"

#include "libtorrent/lsd.hpp"
#include "libtorrent/io.hpp"
#include "libtorrent/http_tracker_connection.hpp"

#include <boost/bind.hpp>
#include <boost/ref.hpp>
#include <asio/ip/host_name.hpp>
#include <asio/ip/multicast.hpp>
#include <boost/thread/mutex.hpp>
#include <cstdlib>
#include <boost/config.hpp>

using boost::bind;
using namespace libtorrent;

namespace libtorrent
{
	// defined in broadcast_socket.cpp
	address guess_local_address(asio::io_service&);
}

lsd::lsd(io_service& ios, address const& listen_interface
	, peer_callback_t const& cb)
	: m_callback(cb)
	, m_retry_count(0)
	, m_socket(ios, udp::endpoint(address_v4::from_string("239.192.152.143"), 6771)
		, bind(&lsd::on_announce, self(), _1, _2, _3))
	, m_broadcast_timer(ios)
	, m_disabled(false)
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
	m_log.open("lsd.log", std::ios::in | std::ios::out | std::ios::trunc);
#endif
}

lsd::~lsd() {}

void lsd::announce(sha1_hash const& ih, int listen_port)
{
	if (m_disabled) return;

	std::stringstream btsearch;
	btsearch << "BT-SEARCH * HTTP/1.1\r\n"
		"Host: 239.192.152.143:6771\r\n"
		"Port: " << listen_port << "\r\n"
		"Infohash: " << ih << "\r\n"
		"\r\n\r\n";
	std::string const& msg = btsearch.str();

	m_retry_count = 0;
	asio::error_code ec;
	m_socket.send(msg.c_str(), int(msg.size()), ec);
	if (ec)
	{
		m_disabled = true;
		return;
	}

#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
	m_log << time_now_string()
		<< " ==> announce: ih: " << ih << " port: " << listen_port << std::endl;
#endif

	m_broadcast_timer.expires_from_now(milliseconds(250 * m_retry_count));
	m_broadcast_timer.async_wait(bind(&lsd::resend_announce, self(), _1, msg));
}

void lsd::resend_announce(asio::error_code const& e, std::string msg) try
{
	if (e) return;

	asio::error_code ec;
	m_socket.send(msg.c_str(), int(msg.size()), ec);

	++m_retry_count;
	if (m_retry_count >= 5)
		return;

	m_broadcast_timer.expires_from_now(milliseconds(250 * m_retry_count));
	m_broadcast_timer.async_wait(bind(&lsd::resend_announce, self(), _1, msg));
}
catch (std::exception&)
{}

void lsd::on_announce(udp::endpoint const& from, char* buffer
	, std::size_t bytes_transferred)
{
	using namespace libtorrent::detail;

	http_parser p;

	p.incoming(buffer::const_interval(buffer, buffer + bytes_transferred));

	if (!p.header_finished())
	{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
	m_log << time_now_string()
		<< " <== announce: incomplete HTTP message\n";
#endif
		return;
	}

	if (p.method() != "bt-search")
	{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
	m_log << time_now_string()
		<< " <== announce: invalid HTTP method: " << p.method() << std::endl;
#endif
		return;
	}

	std::string const& port_str = p.header("port");
	if (port_str.empty())
	{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
	m_log << time_now_string()
		<< " <== announce: invalid BT-SEARCH, missing port" << std::endl;
#endif
		return;
	}

	std::string const& ih_str = p.header("infohash");
	if (ih_str.empty())
	{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
	m_log << time_now_string()
		<< " <== announce: invalid BT-SEARCH, missing infohash" << std::endl;
#endif
		return;
	}

	sha1_hash ih(0);
	std::istringstream ih_sstr(ih_str);
	ih_sstr >> ih;
	int port = atoi(port_str.c_str());

	if (!ih.is_all_zeros() && port != 0)
	{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
		m_log << time_now_string()
			<< " *** incoming local announce " << from.address()
			<< ":" << port << " ih: " << ih << std::endl;
#endif
		// we got an announce, pass it on through the callback
		try { m_callback(tcp::endpoint(from.address(), port), ih); }
		catch (std::exception&) {}
	}
}

void lsd::close()
{
	asio::error_code ec;
	m_socket.close(ec);
	m_broadcast_timer.cancel();
}

<|endoftext|>


<commit_before>// Copyright (c) 2014-2017 The Dash Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "activeznode.h"
#include "consensus/consensus.h"
#include "znode.h"
#include "znode-sync.h"
#include "znode-payments.h"
#include "znodeman.h"
#include "protocol.h"
#include "netbase.h"

// TODO: upgrade to new dash, remove this hack
#define vNodes (g_connman->vNodes)
#define cs_vNodes (g_connman->cs_vNodes)

extern CWallet *pwalletMain;

// Keep track of the active Znode
CActiveZnode activeZnode;

void CActiveZnode::ManageState() {
    LogPrint("znode", "CActiveZnode::ManageState -- Start\n");
    if (!fMasternodeMode) {
        LogPrint("znode", "CActiveZnode::ManageState -- Not a znode, returning\n");
        return;
    }

    if (Params().NetworkIDString() != CBaseChainParams::REGTEST && !znodeSync.IsBlockchainSynced()) {
        nState = ACTIVE_ZNODE_SYNC_IN_PROCESS;
        LogPrintf("CActiveZnode::ManageState -- %s: %s\n", GetStateString(), GetStatus());
        return;
    }

    if (nState == ACTIVE_ZNODE_SYNC_IN_PROCESS) {
        nState = ACTIVE_ZNODE_INITIAL;
    }

    LogPrint("znode", "CActiveZnode::ManageState -- status = %s, type = %s, pinger enabled = %d\n",
             GetStatus(), GetTypeString(), fPingerEnabled);

    if (eType == ZNODE_UNKNOWN) {
        ManageStateInitial();
    }

    if (eType == ZNODE_REMOTE) {
        ManageStateRemote();
    } else if (eType == ZNODE_LOCAL) {
        // Try Remote Start first so the started local znode can be restarted without recreate znode broadcast.
        ManageStateRemote();
        if (nState != ACTIVE_ZNODE_STARTED)
            ManageStateLocal();
    }

    SendZnodePing();
}

std::string CActiveZnode::GetStateString() const {
    switch (nState) {
        case ACTIVE_ZNODE_INITIAL:
            return "INITIAL";
        case ACTIVE_ZNODE_SYNC_IN_PROCESS:
            return "SYNC_IN_PROCESS";
        case ACTIVE_ZNODE_INPUT_TOO_NEW:
            return "INPUT_TOO_NEW";
        case ACTIVE_ZNODE_NOT_CAPABLE:
            return "NOT_CAPABLE";
        case ACTIVE_ZNODE_STARTED:
            return "STARTED";
        default:
            return "UNKNOWN";
    }
}

std::string CActiveZnode::GetStatus() const {
    switch (nState) {
        case ACTIVE_ZNODE_INITIAL:
            return "Node just started, not yet activated";
        case ACTIVE_ZNODE_SYNC_IN_PROCESS:
            return "Sync in progress. Must wait until sync is complete to start Znode";
        case ACTIVE_ZNODE_INPUT_TOO_NEW:
            return strprintf("Znode input must have at least %d confirmations",
                             Params().GetConsensus().nZnodeMinimumConfirmations);
        case ACTIVE_ZNODE_NOT_CAPABLE:
            return "Not capable znode: " + strNotCapableReason;
        case ACTIVE_ZNODE_STARTED:
            return "Znode successfully started";
        default:
            return "Unknown";
    }
}

std::string CActiveZnode::GetTypeString() const {
    std::string strType;
    switch (eType) {
        case ZNODE_UNKNOWN:
            strType = "UNKNOWN";
            break;
        case ZNODE_REMOTE:
            strType = "REMOTE";
            break;
        case ZNODE_LOCAL:
            strType = "LOCAL";
            break;
        default:
            strType = "UNKNOWN";
            break;
    }
    return strType;
}

bool CActiveZnode::SendZnodePing() {
    if (!fPingerEnabled) {
        LogPrint("znode",
                 "CActiveZnode::SendZnodePing -- %s: znode ping service is disabled, skipping...\n",
                 GetStateString());
        return false;
    }

    if (!mnodeman.Has(vin)) {
        strNotCapableReason = "Znode not in znode list";
        nState = ACTIVE_ZNODE_NOT_CAPABLE;
        LogPrintf("CActiveZnode::SendZnodePing -- %s: %s\n", GetStateString(), strNotCapableReason);
        return false;
    }

    CZnodePing mnp(vin);
    if (!mnp.Sign(keyZnode, pubKeyZnode)) {
        LogPrintf("CActiveZnode::SendZnodePing -- ERROR: Couldn't sign Znode Ping\n");
        return false;
    }

    // Update lastPing for our znode in Znode list
    if (mnodeman.IsZnodePingedWithin(vin, ZNODE_MIN_MNP_SECONDS, mnp.sigTime)) {
        LogPrintf("CActiveZnode::SendZnodePing -- Too early to send Znode Ping\n");
        return false;
    }

    mnodeman.SetZnodeLastPing(vin, mnp);

    LogPrintf("CActiveZnode::SendZnodePing -- Relaying ping, collateral=%s\n", vin.ToString());
    mnp.Relay();

    return true;
}

void CActiveZnode::ManageStateInitial() {
    LogPrint("znode", "CActiveZnode::ManageStateInitial -- status = %s, type = %s, pinger enabled = %d\n",
             GetStatus(), GetTypeString(), fPingerEnabled);

    // Check that our local network configuration is correct
    if (!fListen) {
        // listen option is probably overwritten by smth else, no good
        nState = ACTIVE_ZNODE_NOT_CAPABLE;
        strNotCapableReason = "Znode must accept connections from outside. Make sure listen configuration option is not overwritten by some another parameter.";
        LogPrintf("CActiveZnode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason);
        return;
    }

    bool fFoundLocal = false;
    if(Params().NetworkIDString() == CBaseChainParams::REGTEST) {
        std::string const & serv = GetArg("-externalip", "");
        if(!serv.empty()) {
            if (Lookup(serv.c_str(), service, 0, false))
                fFoundLocal = true;
        }

    }
    if(!fFoundLocal)
    {
        LOCK(cs_vNodes);

        // First try to find whatever local address is specified by externalip option
        fFoundLocal = GetLocal(service) && CZnode::IsValidNetAddr(service);
        if (!fFoundLocal) {
            // nothing and no live connections, can't do anything for now
            if (vNodes.empty()) {
                nState = ACTIVE_ZNODE_NOT_CAPABLE;
                strNotCapableReason = "Can't detect valid external address. Will retry when there are some connections available.";
                LogPrintf("CActiveZnode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason);
                return;
            }
            // We have some peers, let's try to find our local address from one of them
            BOOST_FOREACH(CNode * pnode, vNodes)
            {
                if (pnode->fSuccessfullyConnected && pnode->addr.IsIPv4()) {
                    fFoundLocal = GetLocal(service, &pnode->addr) && CZnode::IsValidNetAddr(service);
                    if (fFoundLocal) break;
                }
            }
        }
    }

    if (!fFoundLocal) {
        nState = ACTIVE_ZNODE_NOT_CAPABLE;
        strNotCapableReason = "Can't detect valid external address. Please consider using the externalip configuration option if problem persists. Make sure to use IPv4 address only.";
        LogPrintf("CActiveZnode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason);
        return;
    }

    int mainnetDefaultPort = Params(CBaseChainParams::MAIN).GetDefaultPort();
    if (Params().NetworkIDString() == CBaseChainParams::MAIN) {
        if (service.GetPort() != mainnetDefaultPort) {
            nState = ACTIVE_ZNODE_NOT_CAPABLE;
            strNotCapableReason = strprintf("Invalid port: %u - only %d is supported on mainnet.", service.GetPort(),
                                            mainnetDefaultPort);
            LogPrintf("CActiveZnode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason);
            return;
        }
    } else if (service.GetPort() == mainnetDefaultPort) {
        nState = ACTIVE_ZNODE_NOT_CAPABLE;
        strNotCapableReason = strprintf("Invalid port: %u - %d is only supported on mainnet.", service.GetPort(),
                                        mainnetDefaultPort);
        LogPrintf("CActiveZnode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason);
        return;
    }

    LogPrintf("CActiveZnode::ManageStateInitial -- Checking inbound connection to '%s'\n", service.ToString());
    //TODO
    if (!g_connman->OpenMasternodeConnection(CAddress(service, NODE_NETWORK))) {
        nState = ACTIVE_ZNODE_NOT_CAPABLE;
        strNotCapableReason = "Could not connect to " + service.ToString();
        LogPrintf("CActiveZnode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason);
        return;
    }

    // Default to REMOTE
    eType = ZNODE_REMOTE;

    // Check if wallet funds are available
    if (!pwalletMain) {
        LogPrintf("CActiveZnode::ManageStateInitial -- %s: Wallet not available\n", GetStateString());
        return;
    }

    if (pwalletMain->IsLocked()) {
        LogPrintf("CActiveZnode::ManageStateInitial -- %s: Wallet is locked\n", GetStateString());
        return;
    }

    if (pwalletMain->GetBalance() < ZNODE_COIN_REQUIRED * COIN) {
        LogPrintf("CActiveZnode::ManageStateInitial -- %s: Wallet balance is < 1000 XZC\n", GetStateString());
        return;
    }

    // Choose coins to use
    CPubKey pubKeyCollateral;
    CKey keyCollateral;

    // If collateral is found switch to LOCAL mode
    if (pwalletMain->GetZnodeVinAndKeys(vin, pubKeyCollateral, keyCollateral)) {
        eType = ZNODE_LOCAL;
    }

    LogPrint("znode", "CActiveZnode::ManageStateInitial -- End status = %s, type = %s, pinger enabled = %d\n",
             GetStatus(), GetTypeString(), fPingerEnabled);
}

void CActiveZnode::ManageStateRemote() {
    LogPrint("znode",
             "CActiveZnode::ManageStateRemote -- Start status = %s, type = %s, pinger enabled = %d, pubKeyZnode.GetID() = %s\n",
             GetStatus(), fPingerEnabled, GetTypeString(), pubKeyZnode.GetID().ToString());

    mnodeman.CheckZnode(pubKeyZnode);
    znode_info_t infoMn = mnodeman.GetZnodeInfo(pubKeyZnode);

    if (infoMn.fInfoValid) {
        if (infoMn.nProtocolVersion < MIN_ZNODE_PAYMENT_PROTO_VERSION_1
                || infoMn.nProtocolVersion > MIN_ZNODE_PAYMENT_PROTO_VERSION_2) {
            nState = ACTIVE_ZNODE_NOT_CAPABLE;
            strNotCapableReason = "Invalid protocol version";
            LogPrintf("CActiveZnode::ManageStateRemote -- %s: %s\n", GetStateString(), strNotCapableReason);
            return;
        }
        if (service != infoMn.addr) {
            nState = ACTIVE_ZNODE_NOT_CAPABLE;
            // LogPrintf("service: %s\n", service.ToString());
            // LogPrintf("infoMn.addr: %s\n", infoMn.addr.ToString());
            strNotCapableReason = "Broadcasted IP doesn't match our external address. Make sure you issued a new broadcast if IP of this znode changed recently.";
            LogPrintf("CActiveZnode::ManageStateRemote -- %s: %s\n", GetStateString(), strNotCapableReason);
            return;
        }
        if (!CZnode::IsValidStateForAutoStart(infoMn.nActiveState)) {
            nState = ACTIVE_ZNODE_NOT_CAPABLE;
            strNotCapableReason = strprintf("Znode in %s state", CZnode::StateToString(infoMn.nActiveState));
            LogPrintf("CActiveZnode::ManageStateRemote -- %s: %s\n", GetStateString(), strNotCapableReason);
            return;
        }
        if (nState != ACTIVE_ZNODE_STARTED) {
            LogPrintf("CActiveZnode::ManageStateRemote -- STARTED!\n");
            vin = infoMn.vin;
            service = infoMn.addr;
            fPingerEnabled = true;
            nState = ACTIVE_ZNODE_STARTED;
        }
    } else {
        nState = ACTIVE_ZNODE_NOT_CAPABLE;
        strNotCapableReason = "Znode not in znode list";
        LogPrintf("CActiveZnode::ManageStateRemote -- %s: %s\n", GetStateString(), strNotCapableReason);
    }
}

void CActiveZnode::ManageStateLocal() {
    LogPrint("znode", "CActiveZnode::ManageStateLocal -- status = %s, type = %s, pinger enabled = %d\n",
             GetStatus(), GetTypeString(), fPingerEnabled);
    if (nState == ACTIVE_ZNODE_STARTED) {
        return;
    }

    // Choose coins to use
    CPubKey pubKeyCollateral;
    CKey keyCollateral;

    if (pwalletMain->GetZnodeVinAndKeys(vin, pubKeyCollateral, keyCollateral)) {
        int nInputAge = GetInputAge(vin);
        if (nInputAge < Params().GetConsensus().nZnodeMinimumConfirmations) {
            nState = ACTIVE_ZNODE_INPUT_TOO_NEW;
            strNotCapableReason = strprintf(_("%s - %d confirmations"), GetStatus(), nInputAge);
            LogPrintf("CActiveZnode::ManageStateLocal -- %s: %s\n", GetStateString(), strNotCapableReason);
            return;
        }

        {
            LOCK(pwalletMain->cs_wallet);
            pwalletMain->LockCoin(vin.prevout);
        }

        CZnodeBroadcast mnb;
        std::string strError;
        if (!CZnodeBroadcast::Create(vin, service, keyCollateral, pubKeyCollateral, keyZnode,
                                     pubKeyZnode, strError, mnb)) {
            nState = ACTIVE_ZNODE_NOT_CAPABLE;
            strNotCapableReason = "Error creating mastenode broadcast: " + strError;
            LogPrintf("CActiveZnode::ManageStateLocal -- %s: %s\n", GetStateString(), strNotCapableReason);
            return;
        }

        fPingerEnabled = true;
        nState = ACTIVE_ZNODE_STARTED;

        //update to znode list
        LogPrintf("CActiveZnode::ManageStateLocal -- Update Znode List\n");
        mnodeman.UpdateZnodeList(mnb);
        mnodeman.NotifyZnodeUpdates();

        //send to all peers
        LogPrintf("CActiveZnode::ManageStateLocal -- Relay broadcast, vin=%s\n", vin.ToString());
        mnb.RelayZNode();
    }
}
<commit_msg>Legacy znode code bugfix<commit_after>// Copyright (c) 2014-2017 The Dash Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "activeznode.h"
#include "consensus/consensus.h"
#include "znode.h"
#include "znode-sync.h"
#include "znode-payments.h"
#include "znodeman.h"
#include "protocol.h"
#include "netbase.h"

// TODO: upgrade to new dash, remove this hack
#define vNodes (g_connman->vNodes)
#define cs_vNodes (g_connman->cs_vNodes)

extern CWallet *pwalletMain;

// Keep track of the active Znode
CActiveZnode activeZnode;

void CActiveZnode::ManageState() {
    LogPrint("znode", "CActiveZnode::ManageState -- Start\n");
    if (!fMasternodeMode) {
        LogPrint("znode", "CActiveZnode::ManageState -- Not a znode, returning\n");
        return;
    }

    if (Params().NetworkIDString() != CBaseChainParams::REGTEST && !znodeSync.IsBlockchainSynced()) {
        nState = ACTIVE_ZNODE_SYNC_IN_PROCESS;
        LogPrintf("CActiveZnode::ManageState -- %s: %s\n", GetStateString(), GetStatus());
        return;
    }

    if (nState == ACTIVE_ZNODE_SYNC_IN_PROCESS) {
        nState = ACTIVE_ZNODE_INITIAL;
    }

    LogPrint("znode", "CActiveZnode::ManageState -- status = %s, type = %s, pinger enabled = %d\n",
             GetStatus(), GetTypeString(), fPingerEnabled);

    if (eType == ZNODE_UNKNOWN) {
        ManageStateInitial();
    }

    if (eType == ZNODE_REMOTE) {
        ManageStateRemote();
    } else if (eType == ZNODE_LOCAL) {
        // Try Remote Start first so the started local znode can be restarted without recreate znode broadcast.
        ManageStateRemote();
        if (nState != ACTIVE_ZNODE_STARTED)
            ManageStateLocal();
    }

    SendZnodePing();
}

std::string CActiveZnode::GetStateString() const {
    switch (nState) {
        case ACTIVE_ZNODE_INITIAL:
            return "INITIAL";
        case ACTIVE_ZNODE_SYNC_IN_PROCESS:
            return "SYNC_IN_PROCESS";
        case ACTIVE_ZNODE_INPUT_TOO_NEW:
            return "INPUT_TOO_NEW";
        case ACTIVE_ZNODE_NOT_CAPABLE:
            return "NOT_CAPABLE";
        case ACTIVE_ZNODE_STARTED:
            return "STARTED";
        default:
            return "UNKNOWN";
    }
}

std::string CActiveZnode::GetStatus() const {
    switch (nState) {
        case ACTIVE_ZNODE_INITIAL:
            return "Node just started, not yet activated";
        case ACTIVE_ZNODE_SYNC_IN_PROCESS:
            return "Sync in progress. Must wait until sync is complete to start Znode";
        case ACTIVE_ZNODE_INPUT_TOO_NEW:
            return strprintf("Znode input must have at least %d confirmations",
                             Params().GetConsensus().nZnodeMinimumConfirmations);
        case ACTIVE_ZNODE_NOT_CAPABLE:
            return "Not capable znode: " + strNotCapableReason;
        case ACTIVE_ZNODE_STARTED:
            return "Znode successfully started";
        default:
            return "Unknown";
    }
}

std::string CActiveZnode::GetTypeString() const {
    std::string strType;
    switch (eType) {
        case ZNODE_UNKNOWN:
            strType = "UNKNOWN";
            break;
        case ZNODE_REMOTE:
            strType = "REMOTE";
            break;
        case ZNODE_LOCAL:
            strType = "LOCAL";
            break;
        default:
            strType = "UNKNOWN";
            break;
    }
    return strType;
}

bool CActiveZnode::SendZnodePing() {
    if (!fPingerEnabled) {
        LogPrint("znode",
                 "CActiveZnode::SendZnodePing -- %s: znode ping service is disabled, skipping...\n",
                 GetStateString());
        return false;
    }

    if (!mnodeman.Has(vin)) {
        strNotCapableReason = "Znode not in znode list";
        nState = ACTIVE_ZNODE_NOT_CAPABLE;
        LogPrintf("CActiveZnode::SendZnodePing -- %s: %s\n", GetStateString(), strNotCapableReason);
        return false;
    }

    CZnodePing mnp(vin);
    if (!mnp.Sign(keyZnode, pubKeyZnode)) {
        LogPrintf("CActiveZnode::SendZnodePing -- ERROR: Couldn't sign Znode Ping\n");
        return false;
    }

    // Update lastPing for our znode in Znode list
    if (mnodeman.IsZnodePingedWithin(vin, ZNODE_MIN_MNP_SECONDS, mnp.sigTime)) {
        LogPrintf("CActiveZnode::SendZnodePing -- Too early to send Znode Ping\n");
        return false;
    }

    mnodeman.SetZnodeLastPing(vin, mnp);

    LogPrintf("CActiveZnode::SendZnodePing -- Relaying ping, collateral=%s\n", vin.ToString());
    mnp.Relay();

    return true;
}

void CActiveZnode::ManageStateInitial() {
    LogPrint("znode", "CActiveZnode::ManageStateInitial -- status = %s, type = %s, pinger enabled = %d\n",
             GetStatus(), GetTypeString(), fPingerEnabled);

    // Check that our local network configuration is correct
    if (!fListen) {
        // listen option is probably overwritten by smth else, no good
        nState = ACTIVE_ZNODE_NOT_CAPABLE;
        strNotCapableReason = "Znode must accept connections from outside. Make sure listen configuration option is not overwritten by some another parameter.";
        LogPrintf("CActiveZnode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason);
        return;
    }

    bool fFoundLocal = false;
    {
        LOCK(cs_vNodes);

        // First try to find whatever local address is specified by externalip option
        fFoundLocal = GetLocal(service) && CZnode::IsValidNetAddr(service);
        if (!fFoundLocal) {
            // nothing and no live connections, can't do anything for now
            if (vNodes.empty()) {
                nState = ACTIVE_ZNODE_NOT_CAPABLE;
                strNotCapableReason = "Can't detect valid external address. Will retry when there are some connections available.";
                LogPrintf("CActiveZnode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason);
                return;
            }
            // We have some peers, let's try to find our local address from one of them
            BOOST_FOREACH(CNode * pnode, vNodes)
            {
                if (pnode->fSuccessfullyConnected && pnode->addr.IsIPv4()) {
                    fFoundLocal = GetLocal(service, &pnode->addr) && CZnode::IsValidNetAddr(service);
                    if (fFoundLocal) break;
                }
            }
        }
    }

    if(Params().NetworkIDString() == CBaseChainParams::REGTEST) {
        std::string const & serv = GetArg("-externalip", "");
        if(!serv.empty()) {
            if (Lookup(serv.c_str(), service, 0, false))
                fFoundLocal = true;
        }

    }
    if(!fFoundLocal)
    {
        LOCK(cs_vNodes);

        // First try to find whatever local address is specified by externalip option
        fFoundLocal = GetLocal(service) && CZnode::IsValidNetAddr(service);
        if (!fFoundLocal) {
            // nothing and no live connections, can't do anything for now
            if (vNodes.empty()) {
                nState = ACTIVE_ZNODE_NOT_CAPABLE;
                strNotCapableReason = "Can't detect valid external address. Will retry when there are some connections available.";
                LogPrintf("CActiveZnode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason);
                return;
            }
            // We have some peers, let's try to find our local address from one of them
            BOOST_FOREACH(CNode * pnode, vNodes)
            {
                if (pnode->fSuccessfullyConnected && pnode->addr.IsIPv4()) {
                    fFoundLocal = GetLocal(service, &pnode->addr) && CZnode::IsValidNetAddr(service);
                    if (fFoundLocal) break;
                }
            }
        }
    }

    if (!fFoundLocal) {
        nState = ACTIVE_ZNODE_NOT_CAPABLE;
        strNotCapableReason = "Can't detect valid external address. Please consider using the externalip configuration option if problem persists. Make sure to use IPv4 address only.";
        LogPrintf("CActiveZnode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason);
        return;
    }

    int mainnetDefaultPort = Params(CBaseChainParams::MAIN).GetDefaultPort();
    if (Params().NetworkIDString() == CBaseChainParams::MAIN) {
        if (service.GetPort() != mainnetDefaultPort) {
            nState = ACTIVE_ZNODE_NOT_CAPABLE;
            strNotCapableReason = strprintf("Invalid port: %u - only %d is supported on mainnet.", service.GetPort(),
                                            mainnetDefaultPort);
            LogPrintf("CActiveZnode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason);
            return;
        }
    } else if (service.GetPort() == mainnetDefaultPort) {
        nState = ACTIVE_ZNODE_NOT_CAPABLE;
        strNotCapableReason = strprintf("Invalid port: %u - %d is only supported on mainnet.", service.GetPort(),
                                        mainnetDefaultPort);
        LogPrintf("CActiveZnode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason);
        return;
    }

    LogPrintf("CActiveZnode::ManageStateInitial -- Checking inbound connection to '%s'\n", service.ToString());
    //TODO
    if (!g_connman->OpenMasternodeConnection(CAddress(service, NODE_NETWORK))) {
        nState = ACTIVE_ZNODE_NOT_CAPABLE;
        strNotCapableReason = "Could not connect to " + service.ToString();
        LogPrintf("CActiveZnode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason);
        return;
    }

    // Default to REMOTE
    eType = ZNODE_REMOTE;

    // Check if wallet funds are available
    if (!pwalletMain) {
        LogPrintf("CActiveZnode::ManageStateInitial -- %s: Wallet not available\n", GetStateString());
        return;
    }

    if (pwalletMain->IsLocked()) {
        LogPrintf("CActiveZnode::ManageStateInitial -- %s: Wallet is locked\n", GetStateString());
        return;
    }

    if (pwalletMain->GetBalance() < ZNODE_COIN_REQUIRED * COIN) {
        LogPrintf("CActiveZnode::ManageStateInitial -- %s: Wallet balance is < 1000 XZC\n", GetStateString());
        return;
    }

    // Choose coins to use
    CPubKey pubKeyCollateral;
    CKey keyCollateral;

    // If collateral is found switch to LOCAL mode
    if (pwalletMain->GetZnodeVinAndKeys(vin, pubKeyCollateral, keyCollateral)) {
        eType = ZNODE_LOCAL;
    }

    LogPrint("znode", "CActiveZnode::ManageStateInitial -- End status = %s, type = %s, pinger enabled = %d\n",
             GetStatus(), GetTypeString(), fPingerEnabled);
}

void CActiveZnode::ManageStateRemote() {
    LogPrint("znode",
             "CActiveZnode::ManageStateRemote -- Start status = %s, type = %s, pinger enabled = %d, pubKeyZnode.GetID() = %s\n",
             GetStatus(), fPingerEnabled, GetTypeString(), pubKeyZnode.GetID().ToString());

    mnodeman.CheckZnode(pubKeyZnode);
    znode_info_t infoMn = mnodeman.GetZnodeInfo(pubKeyZnode);

    if (infoMn.fInfoValid) {
        if (infoMn.nProtocolVersion < MIN_ZNODE_PAYMENT_PROTO_VERSION_1
                || infoMn.nProtocolVersion > MIN_ZNODE_PAYMENT_PROTO_VERSION_2) {
            nState = ACTIVE_ZNODE_NOT_CAPABLE;
            strNotCapableReason = "Invalid protocol version";
            LogPrintf("CActiveZnode::ManageStateRemote -- %s: %s\n", GetStateString(), strNotCapableReason);
            return;
        }
        if (service != infoMn.addr) {
            nState = ACTIVE_ZNODE_NOT_CAPABLE;
            // LogPrintf("service: %s\n", service.ToString());
            // LogPrintf("infoMn.addr: %s\n", infoMn.addr.ToString());
            strNotCapableReason = "Broadcasted IP doesn't match our external address. Make sure you issued a new broadcast if IP of this znode changed recently.";
            LogPrintf("CActiveZnode::ManageStateRemote -- %s: %s\n", GetStateString(), strNotCapableReason);
            return;
        }
        if (!CZnode::IsValidStateForAutoStart(infoMn.nActiveState)) {
            nState = ACTIVE_ZNODE_NOT_CAPABLE;
            strNotCapableReason = strprintf("Znode in %s state", CZnode::StateToString(infoMn.nActiveState));
            LogPrintf("CActiveZnode::ManageStateRemote -- %s: %s\n", GetStateString(), strNotCapableReason);
            return;
        }
        if (nState != ACTIVE_ZNODE_STARTED) {
            LogPrintf("CActiveZnode::ManageStateRemote -- STARTED!\n");
            vin = infoMn.vin;
            service = infoMn.addr;
            fPingerEnabled = true;
            nState = ACTIVE_ZNODE_STARTED;
        }
    } else {
        nState = ACTIVE_ZNODE_NOT_CAPABLE;
        strNotCapableReason = "Znode not in znode list";
        LogPrintf("CActiveZnode::ManageStateRemote -- %s: %s\n", GetStateString(), strNotCapableReason);
    }
}

void CActiveZnode::ManageStateLocal() {
    LogPrint("znode", "CActiveZnode::ManageStateLocal -- status = %s, type = %s, pinger enabled = %d\n",
             GetStatus(), GetTypeString(), fPingerEnabled);
    if (nState == ACTIVE_ZNODE_STARTED) {
        return;
    }

    // Choose coins to use
    CPubKey pubKeyCollateral;
    CKey keyCollateral;

    if (pwalletMain->GetZnodeVinAndKeys(vin, pubKeyCollateral, keyCollateral)) {
        int nInputAge = GetInputAge(vin);
        if (nInputAge < Params().GetConsensus().nZnodeMinimumConfirmations) {
            nState = ACTIVE_ZNODE_INPUT_TOO_NEW;
            strNotCapableReason = strprintf(_("%s - %d confirmations"), GetStatus(), nInputAge);
            LogPrintf("CActiveZnode::ManageStateLocal -- %s: %s\n", GetStateString(), strNotCapableReason);
            return;
        }

        {
            LOCK(pwalletMain->cs_wallet);
            pwalletMain->LockCoin(vin.prevout);
        }

        CZnodeBroadcast mnb;
        std::string strError;
        if (!CZnodeBroadcast::Create(vin, service, keyCollateral, pubKeyCollateral, keyZnode,
                                     pubKeyZnode, strError, mnb)) {
            nState = ACTIVE_ZNODE_NOT_CAPABLE;
            strNotCapableReason = "Error creating mastenode broadcast: " + strError;
            LogPrintf("CActiveZnode::ManageStateLocal -- %s: %s\n", GetStateString(), strNotCapableReason);
            return;
        }

        fPingerEnabled = true;
        nState = ACTIVE_ZNODE_STARTED;

        //update to znode list
        LogPrintf("CActiveZnode::ManageStateLocal -- Update Znode List\n");
        mnodeman.UpdateZnodeList(mnb);
        mnodeman.NotifyZnodeUpdates();

        //send to all peers
        LogPrintf("CActiveZnode::ManageStateLocal -- Relay broadcast, vin=%s\n", vin.ToString());
        mnb.RelayZNode();
    }
}
<|endoftext|>


<commit_before>/*
 * Agent.cpp
 *
 * The reinforcement learning agent: the core of the project
 */

#include <vector>
#include <chrono>
#include <math.h>
#include <stdio.h>
#include <fstream>
#include <string>
#include <sstream>
#include <algorithm>
#include <iostream>

#include <Box2D/Box2D.h>

#include "Agent.h"

#include "../PinballBot.h"
#include "State.h"
#include "../action/Action.h"

const int	Agent::STATES_TO_BACKPORT		= 50;

const float Agent::VALUE_ADJUST_FRACTION	= 0.35f;
const float Agent::EPSILON					= 0.15f;

Agent::Agent(std::vector<Action*> availableActions):
	availableActions(availableActions), generator(seed()){

	states.reserve(std::pow(9, 9));//reserves ≈ 400 MB RAM and prevents reallocations

	loadPolicyFromFile();
}

void Agent::think(State state, std::vector<float> collectedRewards){

	int		currentStateIndex	= 0;
	float	lastValue;

	//first check whether this state already occured or not and retrieve the iterator
	std::vector<State>::iterator it = std::lower_bound(states.begin(), states.end(), state);
	currentStateIndex = (it - states.begin());

	if(currentStateIndex >= states.size() || states[currentStateIndex] != state){
		//If its a new state, add it at the *right* position to prevent a sort
		it = states.insert(it, state);

		//As we inserted an element we need to increase the index of all after the new one
		for(int i=0;i<lastActions.size();i++){
			if(lastActions[i].first >= currentStateIndex){
				lastActions[i].first++;
			}
		}
	}

	/*
	 * Maybe (actually most of the time in a pinball game) the good/bad reward isn't simply caused by the last action taken
	 * A series of actions and event have lead to this specific situation, so we need to apply the reward received for the last action
	 * to the last state in general, in other words to every possible action
	 *
	 * Example:
	 * State 0:		Action: EnableFlipperLeft		Reward:	0.0f	Cause: Ball leaves the CF in the direction of a pin
	 * State 10:	Action: DisableFlipperRight		Reward: 0.0f	Cause: Nothing, ball is still travelling in the direction of the pin
	 * State 15:	Action: DisableFlipperRight		Reward: 1.0f	Cause: Nothing BUT the ball kicked in state 0 hits the pin and causes a reward of 1.0f
	 *
	 * Now we want to series of actions taken from the last few states to occur more often because we know it was "good"
	 * We now want to apply the reward received in state 15 to the actions taken in the last few steps
	 */

	//"strange" syntax because it should be more efficent this way
	if(collectedRewards.size() == 0){

		for(int i=0;i<lastActions.size();i++){

			lastValue = states[lastActions[i].first].getValue(lastActions[i].second);
			/*
			 * If there was no reward we want to port the average value of the current state back
			 * in order to ensure it will occur more or less often. To do that, we simply converge all
			 * values of the previous [∆ - 2 - n] to the average of the last one [∆ - 1]
			 */
			lastValue = lastValue + ((VALUE_ADJUST_FRACTION) * (states[lastActions[lastActions.size()-1].first].getAverageValue() - lastValue));

			states[lastActions[i].first].setValue(lastActions[i].second, lastValue);
		}
	}else{

		for(int i=0;i<lastActions.size();i++){

			lastValue = states[lastActions[i].first].getValue(lastActions[i].second);

			//Apply all collected rewards, they can't be simply added up because then values greater than 1.0f would be possible
			for(int j=0;j<collectedRewards.size();j++){

				/* As currently we don't know more than that what we did in the last state and what the result is, we create a "connection" between the action and the reward
				 * If we receive a good reward (1.0f) the epsilonGreedy() function is more likely to select this action in exactly this state again
				 */
				lastValue = lastValue + ((VALUE_ADJUST_FRACTION) * (collectedRewards[j] - lastValue));
			}

			states[lastActions[i].first].setValue(lastActions[i].second, lastValue);

		}
	}

	//then decide what action to take next
	Action* actionToTake = this->epsilonGreedy(states[currentStateIndex], EPSILON);

	//and the JUST DO IT
	actionToTake->run();

	lastActions.push_back(std::make_pair(currentStateIndex, actionToTake));

	if(lastActions.size() > STATES_TO_BACKPORT){
		for(int i=0;i<(lastActions.size() - STATES_TO_BACKPORT);i++){
			lastActions.pop_front();
		}
	}
}

unsigned Agent::seed(){
	return (unsigned) std::chrono::system_clock::now().time_since_epoch().count();
}

float Agent::randomFloatInRange(const float &min, const float &max){
	std::uniform_real_distribution<float>		distribution
	= std::uniform_real_distribution<float>(min, max);

	return distribution(generator);
}

int Agent::randomIntInRange(const int &min, const int &max){
	std::uniform_int_distribution<int>		distribution
		= std::uniform_int_distribution<int>(min, max);

	return distribution(generator);
}

/*Action Agent::softmax(State state, unsigned long temperature){

	std::vector<double> probabilities(states.size());
	float numerator, denominator;

	for(int i = 0;i<availableActions.size();i++){

	}

	for(int i=0;i<states.size();i++){

		probabilities[i] = 0;
	}
}*/

Action* Agent::epsilonGreedy(State state, const float &epsilon){

	if(epsilon < randomFloatInRange(0.0f, 1.0f)){
		//pick a greedy state
		return greedy(state);
	}else{
		//pick a random state
		return random(availableActions);
	}
}

Action* Agent::greedy(State state){
	float					maxValue = 0;
	float					tmpValue;
	std::vector<Action*>	maxActions;

	for(int i=0;i<availableActions.size();i++){
		tmpValue		= state.getValue(availableActions[i]);

		if(tmpValue > maxValue){
			maxValue = tmpValue;

			maxActions.clear();
			maxActions.push_back(availableActions[i]);
		}else if(tmpValue == maxValue){
			maxActions.push_back(availableActions[i]);
		}
	}

	if(maxActions.size() == 1){
		return maxActions[0];
	}else{
		return random(maxActions);
	}
}

Action* Agent::random(std::vector<Action*> availableActions){
	return availableActions[randomIntInRange(0, availableActions.size()-1)];
}

void Agent::savePoliciesToFile(){

	if(states.size() != 0){

		std::ofstream policies;
		policies.open(PinballBot::POLICIES_FILE);

		//Generate header
		policies << "POSITION_X;POSITION_Y;VELOCITY_X;VELOCITY_Y";
		for(int i=0;i<availableActions.size();i++){
			policies << ";ACTION_" << availableActions[i]->getUID();
		}
		policies << std::endl;

		//and the content in the same order

		for(int i=0;i<states.size();i++){
			policies << states[i].ballPosition.x << ";" << states[i].ballPosition.y << ";"
								<< states[i].ballVelocity.x << ";" << states[i].ballVelocity.y;

			for(int j=0;j<availableActions.size();j++){

				if(states[i].values.find(availableActions[j]) == states[i].values.end()){
					policies << ";" << Action::DEFAULT_REWARD;
					//printf("DEFAULT Value: %f\n", Action::DEFAULT_REWARD);
				}else{
					policies << ";" << (states[i].getValue(availableActions[j]));
					//printf("Value: %f\n", (states[i].getValue(availableActions[j])));
				}
			}

			policies << std::endl;
		}
	}
}

void Agent::loadPolicyFromFile(){
	std::string					line, header;
	std::ifstream				policies;
	std::vector<std::string>	partials;

	states.clear();

	printf("Reading and parsing %s....\n", PinballBot::POLICIES_FILE.c_str());

	policies.open(PinballBot::POLICIES_FILE);

	if(std::getline(policies, header)){
		while (std::getline(policies, line)){

			b2Vec2	ballPosition;
			b2Vec2	ballVelocity;

			split(line, ';', partials);

			ballPosition.x		= stof(partials[0]);
			ballPosition.y		= stof(partials[1]);

			ballVelocity.x		= stof(partials[2]);
			ballVelocity.y		= stof(partials[3]);

			State state(ballPosition, ballVelocity);

			for(int i=0; i<availableActions.size(); i++){ //TODO check if the order in the header is the same as in available actions
				state.values[availableActions[i]] = stof(partials[4 + i]);
			}

			// push new state to states
			states.push_back(state);

			partials.clear();
		}
	}

	printf("Read and parsed %s, %lu states were imported.\n", PinballBot::POLICIES_FILE.c_str(), states.size());

	return;
}

std::vector<std::string> Agent::split(const std::string &s, char delim, std::vector<std::string> &elems) {
	std::stringstream ss(s);
	std::string item;
	while (std::getline(ss, item, delim)) {
		elems.push_back(item);
	}
	return elems;
}
<commit_msg>Hopefully fixed an std::bad_alloc error<commit_after>/*
 * Agent.cpp
 *
 * The reinforcement learning agent: the core of the project
 */

#include <vector>
#include <chrono>
#include <math.h>
#include <stdio.h>
#include <fstream>
#include <string>
#include <sstream>
#include <algorithm>
#include <iostream>

#include <Box2D/Box2D.h>

#include "Agent.h"

#include "../PinballBot.h"
#include "State.h"
#include "../action/Action.h"

const int	Agent::STATES_TO_BACKPORT		= 50;

const float Agent::VALUE_ADJUST_FRACTION	= 0.35f;
const float Agent::EPSILON					= 0.15f;

Agent::Agent(std::vector<Action*> availableActions):
	availableActions(availableActions), generator(seed()){

	//states.reserve(std::pow(2, 20));//reserves a lot a space, enough space for 2^20 = 1'048'576 elements

	loadPolicyFromFile();
}

void Agent::think(State state, std::vector<float> collectedRewards){

	int		currentStateIndex	= 0;
	float	lastValue;

	//first check whether this state already occured or not and retrieve the iterator
	std::vector<State>::iterator it = std::lower_bound(states.begin(), states.end(), state);
	currentStateIndex = (it - states.begin());

	if(currentStateIndex >= states.size() || states[currentStateIndex] != state){
		//If its a new state, add it at the *right* position to prevent a sort
		it = states.insert(it, state);

		//As we inserted an element we need to increase the index of all after the new one
		for(int i=0;i<lastActions.size();i++){
			if(lastActions[i].first >= currentStateIndex){
				lastActions[i].first++;
			}
		}
	}

	/*
	 * Maybe (actually most of the time in a pinball game) the good/bad reward isn't simply caused by the last action taken
	 * A series of actions and event have lead to this specific situation, so we need to apply the reward received for the last action
	 * to the last state in general, in other words to every possible action
	 *
	 * Example:
	 * State 0:		Action: EnableFlipperLeft		Reward:	0.0f	Cause: Ball leaves the CF in the direction of a pin
	 * State 10:	Action: DisableFlipperRight		Reward: 0.0f	Cause: Nothing, ball is still travelling in the direction of the pin
	 * State 15:	Action: DisableFlipperRight		Reward: 1.0f	Cause: Nothing BUT the ball kicked in state 0 hits the pin and causes a reward of 1.0f
	 *
	 * Now we want to series of actions taken from the last few states to occur more often because we know it was "good"
	 * We now want to apply the reward received in state 15 to the actions taken in the last few steps
	 */

	//"strange" syntax because it should be more efficent this way
	if(collectedRewards.size() == 0){

		for(int i=0;i<lastActions.size();i++){

			lastValue = states[lastActions[i].first].getValue(lastActions[i].second);
			/*
			 * If there was no reward we want to port the average value of the current state back
			 * in order to ensure it will occur more or less often. To do that, we simply converge all
			 * values of the previous [∆ - 2 - n] to the average of the last one [∆ - 1]
			 */
			lastValue = lastValue + ((VALUE_ADJUST_FRACTION) * (states[lastActions[lastActions.size()-1].first].getAverageValue() - lastValue));

			states[lastActions[i].first].setValue(lastActions[i].second, lastValue);
		}
	}else{

		for(int i=0;i<lastActions.size();i++){

			lastValue = states[lastActions[i].first].getValue(lastActions[i].second);

			//Apply all collected rewards, they can't be simply added up because then values greater than 1.0f would be possible
			for(int j=0;j<collectedRewards.size();j++){

				/* As currently we don't know more than that what we did in the last state and what the result is, we create a "connection" between the action and the reward
				 * If we receive a good reward (1.0f) the epsilonGreedy() function is more likely to select this action in exactly this state again
				 */
				lastValue = lastValue + ((VALUE_ADJUST_FRACTION) * (collectedRewards[j] - lastValue));
			}

			states[lastActions[i].first].setValue(lastActions[i].second, lastValue);

		}
	}

	//then decide what action to take next
	Action* actionToTake = this->epsilonGreedy(states[currentStateIndex], EPSILON);

	//and the JUST DO IT
	actionToTake->run();

	lastActions.push_back(std::make_pair(currentStateIndex, actionToTake));

	if(lastActions.size() > STATES_TO_BACKPORT){
		for(int i=0;i<(lastActions.size() - STATES_TO_BACKPORT);i++){
			lastActions.pop_front();
		}
	}
}

unsigned Agent::seed(){
	return (unsigned) std::chrono::system_clock::now().time_since_epoch().count();
}

float Agent::randomFloatInRange(const float &min, const float &max){
	std::uniform_real_distribution<float>		distribution
	= std::uniform_real_distribution<float>(min, max);

	return distribution(generator);
}

int Agent::randomIntInRange(const int &min, const int &max){
	std::uniform_int_distribution<int>		distribution
		= std::uniform_int_distribution<int>(min, max);

	return distribution(generator);
}

/*Action Agent::softmax(State state, unsigned long temperature){

	std::vector<double> probabilities(states.size());
	float numerator, denominator;

	for(int i = 0;i<availableActions.size();i++){

	}

	for(int i=0;i<states.size();i++){

		probabilities[i] = 0;
	}
}*/

Action* Agent::epsilonGreedy(State state, const float &epsilon){

	if(epsilon < randomFloatInRange(0.0f, 1.0f)){
		//pick a greedy state
		return greedy(state);
	}else{
		//pick a random state
		return random(availableActions);
	}
}

Action* Agent::greedy(State state){
	float					maxValue = 0;
	float					tmpValue;
	std::vector<Action*>	maxActions;

	for(int i=0;i<availableActions.size();i++){
		tmpValue		= state.getValue(availableActions[i]);

		if(tmpValue > maxValue){
			maxValue = tmpValue;

			maxActions.clear();
			maxActions.push_back(availableActions[i]);
		}else if(tmpValue == maxValue){
			maxActions.push_back(availableActions[i]);
		}
	}

	if(maxActions.size() == 1){
		return maxActions[0];
	}else{
		return random(maxActions);
	}
}

Action* Agent::random(std::vector<Action*> availableActions){
	return availableActions[randomIntInRange(0, availableActions.size()-1)];
}

void Agent::savePoliciesToFile(){

	if(states.size() != 0){

		std::ofstream policies;
		policies.open(PinballBot::POLICIES_FILE);

		//Generate header
		policies << "POSITION_X;POSITION_Y;VELOCITY_X;VELOCITY_Y";
		for(int i=0;i<availableActions.size();i++){
			policies << ";ACTION_" << availableActions[i]->getUID();
		}
		policies << std::endl;

		//and the content in the same order

		for(int i=0;i<states.size();i++){
			policies << states[i].ballPosition.x << ";" << states[i].ballPosition.y << ";"
								<< states[i].ballVelocity.x << ";" << states[i].ballVelocity.y;

			for(int j=0;j<availableActions.size();j++){

				if(states[i].values.find(availableActions[j]) == states[i].values.end()){
					policies << ";" << Action::DEFAULT_REWARD;
					//printf("DEFAULT Value: %f\n", Action::DEFAULT_REWARD);
				}else{
					policies << ";" << (states[i].getValue(availableActions[j]));
					//printf("Value: %f\n", (states[i].getValue(availableActions[j])));
				}
			}

			policies << std::endl;
		}
	}
}

void Agent::loadPolicyFromFile(){
	std::string					line, header;
	std::ifstream				policies;
	std::vector<std::string>	partials;

	states.clear();

	printf("Reading and parsing %s....\n", PinballBot::POLICIES_FILE.c_str());

	policies.open(PinballBot::POLICIES_FILE);

	if(std::getline(policies, header)){
		while (std::getline(policies, line)){

			b2Vec2	ballPosition;
			b2Vec2	ballVelocity;

			split(line, ';', partials);

			ballPosition.x		= stof(partials[0]);
			ballPosition.y		= stof(partials[1]);

			ballVelocity.x		= stof(partials[2]);
			ballVelocity.y		= stof(partials[3]);

			State state(ballPosition, ballVelocity);

			for(int i=0; i<availableActions.size(); i++){ //TODO check if the order in the header is the same as in available actions
				state.values[availableActions[i]] = stof(partials[4 + i]);
			}

			// push new state to states
			states.push_back(state);

			partials.clear();
		}
	}

	printf("Read and parsed %s, %lu states were imported.\n", PinballBot::POLICIES_FILE.c_str(), states.size());

	return;
}

std::vector<std::string> Agent::split(const std::string &s, char delim, std::vector<std::string> &elems) {
	std::stringstream ss(s);
	std::string item;
	while (std::getline(ss, item, delim)) {
		elems.push_back(item);
	}
	return elems;
}
<|endoftext|>


<commit_before>// Main.cc for Fluxbox Window manager
// Copyright (c) 2001 - 2002 Henrik Kinnunen (fluxgen@linuxmail.org)
//
// main.cc for Blackbox - an X11 Window manager
// Copyright (c) 1997 - 2000 Brad Hughes (bhughes@tcac.net)
//
// 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.

// $Id: main.cc,v 1.11 2002/12/03 01:46:28 fluxgen Exp $

#include "i18n.hh"
#include "fluxbox.hh"

#include "../version.h"

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif // HAVE_CONFIG_H

//use GNU extensions
#ifndef	 _GNU_SOURCE
#define	 _GNU_SOURCE
#endif // _GNU_SOURCE

#include <cstdio>
#include <cstdlib>
#include <cstring>

#ifdef HAVE_UNISTD_H
#include <sys/types.h>
#endif // HAVE_UNISTD_H

#ifdef HAVE_SYS_PARAM_H
#include <sys/param.h>
#endif // HAVE_SYS_PARAM_H

#include <iostream>
#include <stdexcept>

using namespace std;

#ifdef DEBUG_UDS

#include <uds/init.hh>
#include <uds/uds.hh>

// configure UDS
uds::uds_flags_t uds::flags = uds::leak_check | uds::std_backtraces | uds::log_allocs | uds::leak_check;

#endif //!DEBUG_UDS

const char *getNLSYesNoMsg(bool val) {
    if (val) {
        return I18n::instance()->getMessage(
            FBNLS::CommonSet, FBNLS::CommonYes,
            "yes");
    }

    return I18n::instance()->getMessage(
        FBNLS::CommonSet, FBNLS::CommonNo,
        "no");
}

int main(int argc, char **argv) {
#ifdef DEBUG_UDS
    uds::Init uds_init;
#endif //!DEBUG_UDS

    char *session_display = (char *) 0;
    char *rc_file = (char *) 0;

    NLSInit("blackbox.cat");
    I18n *i18n = I18n::instance();

    int i;
    for (i = 1; i < argc; ++i) {
        if (! strcmp(argv[i], "-rc")) {
            // look for alternative rc file to use

            if ((++i) >= argc) {
                fprintf(stderr,
                        i18n->getMessage(
                                         FBNLS::mainSet, FBNLS::mainRCRequiresArg,
                                         "error: '-rc' requires and argument\n"));
                exit(1);
            }

            rc_file = argv[i];
        } else if (! strcmp(argv[i], "-display")) {
            // check for -display option... to run on a display other than the one
            // set by the environment variable DISPLAY

            if ((++i) >= argc) {
                fprintf(stderr,
                        i18n->getMessage(
                                         FBNLS::mainSet, FBNLS::mainDISPLAYRequiresArg,
                                         "error: '-display' requires an argument\n"));
                exit(1);
            }

            session_display = argv[i];
            char dtmp[255];
            sprintf(dtmp, "DISPLAY=%s", session_display);

            if (putenv(dtmp)) {
                fprintf(stderr,
                        i18n->
                        getMessage(
                                   FBNLS::mainSet, FBNLS::mainWarnDisplaySet,
                                   "warning: couldn't set environment variable 'DISPLAY'\n"));
                perror("putenv()");
            }
        } else if (strcmp(argv[i], "-version") == 0) {
            // print current version string
            printf("Fluxbox %s : (c) 2001-2002 Henrik Kinnunen \n\n",
                   __fluxbox_version);
            exit(0);
        } else if (strcmp(argv[i], "-help") == 0) {
            // print program usage and command line options
            printf(i18n->
                   getMessage(
                              FBNLS::mainSet, FBNLS::mainUsage,
                              "Fluxbox %s : (c) 2001-2002 Henrik Kinnunen\n\n"
                              "	-display <string>\t\tuse display connection.\n"
                              "	-rc <string>\t\t\tuse alternate resource file.\n"
                              "	-version\t\t\tdisplay version and exit.\n"
                              "	-help\t\t\t\tdisplay this help text and exit.\n\n"),
                   __fluxbox_version);

            printf(i18n->
                   getMessage(
                              FBNLS::mainSet, FBNLS::mainCompileOptions,
                              "Compile time options:\n"
                              "	Debugging:\t\t\t%s\n"
                              "	Interlacing:\t\t\t%s\n"
                              "	Shape:\t\t\t%s\n"
                              "	Slit:\t\t\t\t%s\n"
                              "	8bpp Ordered Dithering:\t%s\n\n"),
#ifdef DEBUG
                   getNLSYesNoMsg(true),
#else // !DEBUG
                   getNLSYesNoMsg(false),
#endif // DEBUG

#ifdef INTERLACE
                   getNLSYesNoMsg(true),
#else // !INTERLACE
                   getNLSYesNoMsg(false),
#endif // INTERLACE

#ifdef SHAPE
                   getNLSYesNoMsg(true),
#else // !SHAPE
                   getNLSYesNoMsg(false),
#endif // SHAPE

#ifdef SLIT
                   getNLSYesNoMsg(true),
#else // !SLIT
                   getNLSYesNoMsg(false),
#endif // SLIT

#ifdef		ORDEREDPSEUDO
                   getNLSYesNoMsg(true)
#else // !ORDEREDPSEUDO
                   getNLSYesNoMsg(false)
#endif // ORDEREDPSEUDO

                   );

            ::exit(0);
        }
    }

#ifdef		__EMX__
    _chdir2(getenv("X11ROOT"));
#endif // __EMX__
    Fluxbox *fluxbox=0;
    int exitcode=EXIT_FAILURE;
    try {

        fluxbox = new Fluxbox(argc, argv, session_display, rc_file);
        fluxbox->eventLoop();
	exitcode = EXIT_SUCCESS;
    } catch (std::out_of_range &oor) {
        cerr<<"Fluxbox: Out of range: "<<oor.what()<<endl;
    } catch (std::logic_error &le) {
        cerr<<"Fluxbox: Logic error: "<<le.what()<<endl;
    } catch (std::runtime_error &re) {
        cerr<<"Fluxbox: Runtime error: "<<re.what()<<endl;
    } catch (std::bad_cast &bc) {
        cerr<<"Fluxbox: Bad cast: "<<bc.what()<<endl;
    } catch (std::bad_alloc &ba) {
        cerr<<"Fluxbox: Bad Alloc: "<<ba.what()<<endl;
    } catch (std::exception &e) {
        cerr<<"Fluxbox: Standard exception: "<<e.what()<<endl;
    } catch (std::string error_str) {
        cerr<<"Error: "<<error_str<<endl;
    } catch (...) {
        cerr<<"Fluxbox: Unknown error."<<endl;
        abort();
    }

    if (fluxbox)
        delete fluxbox;
    return exitcode;
}
<commit_msg>s/blackbox.cat/fluxbox.cat<commit_after>// Main.cc for Fluxbox Window manager
// Copyright (c) 2001 - 2002 Henrik Kinnunen (fluxgen@linuxmail.org)
//
// main.cc for Blackbox - an X11 Window manager
// Copyright (c) 1997 - 2000 Brad Hughes (bhughes@tcac.net)
//
// 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.

// $Id: main.cc,v 1.12 2002/12/09 22:51:23 fluxgen Exp $

#include "i18n.hh"
#include "fluxbox.hh"

#include "../version.h"

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif // HAVE_CONFIG_H

//use GNU extensions
#ifndef	 _GNU_SOURCE
#define	 _GNU_SOURCE
#endif // _GNU_SOURCE

#include <cstdio>
#include <cstdlib>
#include <cstring>

#ifdef HAVE_UNISTD_H
#include <sys/types.h>
#endif // HAVE_UNISTD_H

#ifdef HAVE_SYS_PARAM_H
#include <sys/param.h>
#endif // HAVE_SYS_PARAM_H

#include <iostream>
#include <stdexcept>

using namespace std;

#ifdef DEBUG_UDS

#include <uds/init.hh>
#include <uds/uds.hh>

// configure UDS
uds::uds_flags_t uds::flags = uds::leak_check | uds::std_backtraces | uds::log_allocs | uds::leak_check;

#endif //!DEBUG_UDS

const char *getNLSYesNoMsg(bool val) {
    if (val) {
        return I18n::instance()->getMessage(
            FBNLS::CommonSet, FBNLS::CommonYes,
            "yes");
    }

    return I18n::instance()->getMessage(
        FBNLS::CommonSet, FBNLS::CommonNo,
        "no");
}

int main(int argc, char **argv) {
#ifdef DEBUG_UDS
    uds::Init uds_init;
#endif //!DEBUG_UDS

    char *session_display = (char *) 0;
    char *rc_file = (char *) 0;

    NLSInit("fluxbox.cat");
    I18n *i18n = I18n::instance();

    int i;
    for (i = 1; i < argc; ++i) {
        if (! strcmp(argv[i], "-rc")) {
            // look for alternative rc file to use

            if ((++i) >= argc) {
                fprintf(stderr,
                        i18n->getMessage(
                                         FBNLS::mainSet, FBNLS::mainRCRequiresArg,
                                         "error: '-rc' requires and argument\n"));
                exit(1);
            }

            rc_file = argv[i];
        } else if (! strcmp(argv[i], "-display")) {
            // check for -display option... to run on a display other than the one
            // set by the environment variable DISPLAY

            if ((++i) >= argc) {
                fprintf(stderr,
                        i18n->getMessage(
                                         FBNLS::mainSet, FBNLS::mainDISPLAYRequiresArg,
                                         "error: '-display' requires an argument\n"));
                exit(1);
            }

            session_display = argv[i];
            char dtmp[255];
            sprintf(dtmp, "DISPLAY=%s", session_display);

            if (putenv(dtmp)) {
                fprintf(stderr,
                        i18n->
                        getMessage(
                                   FBNLS::mainSet, FBNLS::mainWarnDisplaySet,
                                   "warning: couldn't set environment variable 'DISPLAY'\n"));
                perror("putenv()");
            }
        } else if (strcmp(argv[i], "-version") == 0) {
            // print current version string
            printf("Fluxbox %s : (c) 2001-2002 Henrik Kinnunen \n\n",
                   __fluxbox_version);
            exit(0);
        } else if (strcmp(argv[i], "-help") == 0) {
            // print program usage and command line options
            printf(i18n->
                   getMessage(
                              FBNLS::mainSet, FBNLS::mainUsage,
                              "Fluxbox %s : (c) 2001-2002 Henrik Kinnunen\n\n"
                              "	-display <string>\t\tuse display connection.\n"
                              "	-rc <string>\t\t\tuse alternate resource file.\n"
                              "	-version\t\t\tdisplay version and exit.\n"
                              "	-help\t\t\t\tdisplay this help text and exit.\n\n"),
                   __fluxbox_version);

            printf(i18n->
                   getMessage(
                              FBNLS::mainSet, FBNLS::mainCompileOptions,
                              "Compile time options:\n"
                              "	Debugging:\t\t\t%s\n"
                              "	Interlacing:\t\t\t%s\n"
                              "	Shape:\t\t\t%s\n"
                              "	Slit:\t\t\t\t%s\n"
                              "	8bpp Ordered Dithering:\t%s\n\n"),
#ifdef DEBUG
                   getNLSYesNoMsg(true),
#else // !DEBUG
                   getNLSYesNoMsg(false),
#endif // DEBUG

#ifdef INTERLACE
                   getNLSYesNoMsg(true),
#else // !INTERLACE
                   getNLSYesNoMsg(false),
#endif // INTERLACE

#ifdef SHAPE
                   getNLSYesNoMsg(true),
#else // !SHAPE
                   getNLSYesNoMsg(false),
#endif // SHAPE

#ifdef SLIT
                   getNLSYesNoMsg(true),
#else // !SLIT
                   getNLSYesNoMsg(false),
#endif // SLIT

#ifdef		ORDEREDPSEUDO
                   getNLSYesNoMsg(true)
#else // !ORDEREDPSEUDO
                   getNLSYesNoMsg(false)
#endif // ORDEREDPSEUDO

                   );

            ::exit(0);
        }
    }

#ifdef		__EMX__
    _chdir2(getenv("X11ROOT"));
#endif // __EMX__
    Fluxbox *fluxbox=0;
    int exitcode=EXIT_FAILURE;
    try {

        fluxbox = new Fluxbox(argc, argv, session_display, rc_file);
        fluxbox->eventLoop();
	exitcode = EXIT_SUCCESS;
    } catch (std::out_of_range &oor) {
        cerr<<"Fluxbox: Out of range: "<<oor.what()<<endl;
    } catch (std::logic_error &le) {
        cerr<<"Fluxbox: Logic error: "<<le.what()<<endl;
    } catch (std::runtime_error &re) {
        cerr<<"Fluxbox: Runtime error: "<<re.what()<<endl;
    } catch (std::bad_cast &bc) {
        cerr<<"Fluxbox: Bad cast: "<<bc.what()<<endl;
    } catch (std::bad_alloc &ba) {
        cerr<<"Fluxbox: Bad Alloc: "<<ba.what()<<endl;
    } catch (std::exception &e) {
        cerr<<"Fluxbox: Standard exception: "<<e.what()<<endl;
    } catch (std::string error_str) {
        cerr<<"Error: "<<error_str<<endl;
    } catch (...) {
        cerr<<"Fluxbox: Unknown error."<<endl;
        abort();
    }

    if (fluxbox)
        delete fluxbox;
    return exitcode;
}
<|endoftext|>


<commit_before>#include "code_gen.h"
#include "cpp.h"
#include "error.h"
#include "parser.h"
#include "scanner.h"

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <list>
#include <string>
#include <vector>

#include <fcntl.h>
#include <unistd.h>
#include <sys/wait.h>

std::string program;
std::string filename_in;
std::string filename_out;
bool debug = false;
static bool only_preprocess = false;
static bool only_compile = false;
static bool specified_out_name = false;
static std::list<std::string> filenames_in;
static std::list<std::string> gcc_filenames_in;
static std::list<std::string> gcc_args;
static std::list<std::string> defines;
static std::list<std::string> include_paths;

static void Usage() {
  printf("Usage: wgtcc [options] file...\n"
       "Options: \n"
       "  -h        Display this information\n"
       "  -D        Define object like macro\n"
       "  -I        Add search path\n"
       "  -E        Preprocess only; do not compile, assemble or link\n"
       "  -S        Compile only; do not assemble or link\n"
       "  -o        specify output file\n");

  exit(-2);
}

static std::string GetExtension(const std::string& filename) {
  return filename.substr(filename.size() >= 2 ? filename.size() - 2 : 0);
}

static void ValidateFileName(const std::string& filename) {
  auto ext = GetExtension(filename);
  if (ext != ".c" && ext != ".s" && ext != ".o" && ext != ".a")
    Error("bad file name format:'%s'", filename.c_str());
}

static void DefineMacro(Preprocessor& cpp, const std::string& def) {
  auto pos = def.find('=');
  std::string macro;
  std::string* replace;
  if (pos == std::string::npos) {
    macro = def;
    replace = new std::string();
  } else {
    macro = def.substr(0, pos);
    replace = new std::string(def.substr(pos + 1));
  }
  cpp.AddMacro(macro, replace);
}

static std::string GetName(const std::string& path) {
  auto pos = path.rfind('/');
  if (pos == std::string::npos)
    return path;
  return path.substr(pos + 1);
}

static int RunWgtcc() {
  if (GetExtension(filename_in) != ".c")
    return 0;

  Preprocessor cpp(&filename_in);
  for (auto& def: defines)
    DefineMacro(cpp, def);
  for (auto& path: include_paths)
    cpp.AddSearchPath(path);

  FILE* fp = stdout;
  if (specified_out_name) {
    fp = fopen(filename_out.c_str(), "w");
  }
  TokenSequence ts;
  cpp.Process(ts);
  if (only_preprocess) {
    ts.Print(fp);
    return 0;
  }

  if (!only_compile || !specified_out_name) {
    filename_out = GetName(filename_in);
    filename_out.back() = 's';
  }
  fp = fopen(filename_out.c_str(), "w");

  Parser parser(ts);
  parser.Parse();
  Generator::SetInOut(&parser, fp);
  Generator().Gen();
  fclose(fp);
  return 0;
}

static int RunGcc() {
  // Froce C11
  bool spec_std = false;
  for (auto& arg: gcc_args) {
    if (arg.substr(0, 4) == "-std") {
      arg = "-std=c11";
      spec_std = true;
    }
  }
  if (!spec_std) {
    gcc_args.push_front("-std=c11");
  }

  std::string systemArg = "gcc";
  for (const auto& arg: gcc_args) {
    systemArg += " " + arg;
  }
  auto ret = system(systemArg.c_str());
  return ret;
}

static void ParseInclude(int argc, char* argv[], int& i) {
  if (argv[i][2]) {
    include_paths.push_front(&argv[i][2]);
    return;
  }

  if (i == argc - 1) {
    Error("missing argument to '%s'", argv[i]);
  }
  include_paths.push_front(argv[++i]);
  gcc_args.push_back(argv[i]);
}

static void ParseDefine(int argc, char* argv[], int& i) {
  if (argv[i][2]) {
    defines.push_back(&argv[i][2]);
    return;
  }

  if (i == argc - 1)
    Error("missing argument to '%s'", argv[i]);
  defines.push_back(argv[++i]);
  gcc_args.push_back(argv[i]);
}

static void ParseOut(int argc, char* argv[], int& i) {
  if (i == argc - 1)
    Error("missing argument to '%s'", argv[i]);
  filename_out = argv[++i];
  gcc_args.push_back(argv[i]);
}

/* Use:
 *   wgtcc: compile
 *   gcc: assemble and link
 * Allowing multi file may not be a good idea...
 */
int main(int argc, char* argv[]) {
  if (argc < 2)
    Usage();

  program = std::string(argv[0]);
  for (auto i = 1; i < argc; ++i) {
    if (argv[i][0] != '-') {
      filename_in = std::string(argv[i]);
      ValidateFileName(filename_in);
      filenames_in.push_back(filename_in);
      continue;
    }

    gcc_args.push_back(argv[i]);
    switch (argv[i][1]) {
    case 'h': Usage(); break;
    case 'E': only_preprocess = true; break;
    case 'S': only_compile = true; break;
    case 'I': ParseInclude(argc, argv, i); break;
    case 'D': ParseDefine(argc, argv, i); break;
    case 'o':
      specified_out_name = true;
      ParseOut(argc, argv, i); break;
    case 'g': gcc_args.pop_back(); debug = true; break;
    default:;
    }
  }

#ifdef DEBUG
  RunWgtcc();
#else
  for (const auto& filename: filenames_in) {
    filename_in = filename;
    pid_t pid = fork();
    if (pid < 0) {
      Error("fork error");
    } else if (pid == 0) {
      // Do work in child process
      return RunWgtcc();
    }
  }

  for (size_t i = 0; i < filenames_in.size(); ++i) {
      int stat;
      wait(&stat);
      if (WIFEXITED(stat) && WEXITSTATUS(stat) != 0)
        return 0;
  }
#endif

  if (only_preprocess || only_compile) {
    if (specified_out_name && filenames_in.size() > 1)
      Error("cannot specifier output filename with multiple input file");
    return 0;
  }

  std::list<std::string> filenames_out;
  for (auto& filename: filenames_in) {
    if (GetExtension(filename) == ".c") {
      gcc_args.push_back(GetName(filename));
      gcc_args.back().back() = 's';
    } else {
      gcc_args.clear();
      for (int i = 1; i < argc; ++i)
        gcc_args.push_back(argv[i]);
      break;
    }
  }
  auto ret = RunGcc();
  auto cmd = "rm -f " + filename_out;
  if (system(cmd.c_str())) {}
  return ret;
}
<commit_msg>cleanup shit<commit_after>#include "code_gen.h"
#include "cpp.h"
#include "error.h"
#include "parser.h"
#include "scanner.h"

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <list>
#include <string>
#include <vector>

#include <fcntl.h>
#include <unistd.h>
#include <sys/wait.h>

std::string program;
std::string filename_in;
std::string filename_out;
bool debug = false;
static bool only_preprocess = false;
static bool only_compile = false;
static bool specified_out_name = false;
static std::list<std::string> filenames_in;
static std::list<std::string> gcc_filenames_in;
static std::list<std::string> gcc_args;
static std::list<std::string> defines;
static std::list<std::string> include_paths;

static void Usage() {
  printf("Usage: wgtcc [options] file...\n"
       "Options: \n"
       "  -h        Display this information\n"
       "  -D        Define object like macro\n"
       "  -I        Add search path\n"
       "  -E        Preprocess only; do not compile, assemble or link\n"
       "  -S        Compile only; do not assemble or link\n"
       "  -o        specify output file\n");

  exit(-2);
}

static std::string GetExtension(const std::string& filename) {
  return filename.substr(filename.size() >= 2 ? filename.size() - 2 : 0);
}

static void ValidateFileName(const std::string& filename) {
  auto ext = GetExtension(filename);
  if (ext != ".c" && ext != ".s" && ext != ".o" && ext != ".a")
    Error("bad file name format:'%s'", filename.c_str());
}

static void DefineMacro(Preprocessor& cpp, const std::string& def) {
  auto pos = def.find('=');
  std::string macro;
  std::string* replace;
  if (pos == std::string::npos) {
    macro = def;
    replace = new std::string();
  } else {
    macro = def.substr(0, pos);
    replace = new std::string(def.substr(pos + 1));
  }
  cpp.AddMacro(macro, replace);
}

static std::string GetName(const std::string& path) {
  auto pos = path.rfind('/');
  if (pos == std::string::npos)
    return path;
  return path.substr(pos + 1);
}

static int RunWgtcc() {
  if (GetExtension(filename_in) != ".c")
    return 0;

  Preprocessor cpp(&filename_in);
  for (auto& def: defines)
    DefineMacro(cpp, def);
  for (auto& path: include_paths)
    cpp.AddSearchPath(path);

  FILE* fp = stdout;
  if (specified_out_name) {
    fp = fopen(filename_out.c_str(), "w");
  }
  TokenSequence ts;
  cpp.Process(ts);
  if (only_preprocess) {
    ts.Print(fp);
    return 0;
  }

  if (!only_compile || !specified_out_name) {
    filename_out = GetName(filename_in);
    filename_out.back() = 's';
  }
  fp = fopen(filename_out.c_str(), "w");

  Parser parser(ts);
  parser.Parse();
  Generator::SetInOut(&parser, fp);
  Generator().Gen();
  fclose(fp);
  return 0;
}

static int RunGcc() {
  // Froce C11
  bool spec_std = false;
  for (auto& arg: gcc_args) {
    if (arg.substr(0, 4) == "-std") {
      arg = "-std=c11";
      spec_std = true;
    }
  }
  if (!spec_std) {
    gcc_args.push_front("-std=c11");
  }

  std::string systemArg = "gcc";
  for (const auto& arg: gcc_args) {
    systemArg += " " + arg;
  }
  auto ret = system(systemArg.c_str());
  return ret;
}

static void ParseInclude(int argc, char* argv[], int& i) {
  if (argv[i][2]) {
    include_paths.push_front(&argv[i][2]);
    return;
  }

  if (i == argc - 1) {
    Error("missing argument to '%s'", argv[i]);
  }
  include_paths.push_front(argv[++i]);
  gcc_args.push_back(argv[i]);
}

static void ParseDefine(int argc, char* argv[], int& i) {
  if (argv[i][2]) {
    defines.push_back(&argv[i][2]);
    return;
  }

  if (i == argc - 1)
    Error("missing argument to '%s'", argv[i]);
  defines.push_back(argv[++i]);
  gcc_args.push_back(argv[i]);
}

static void ParseOut(int argc, char* argv[], int& i) {
  if (i == argc - 1)
    Error("missing argument to '%s'", argv[i]);
  filename_out = argv[++i];
  gcc_args.push_back(argv[i]);
}

/* Use:
 *   wgtcc: compile
 *   gcc: assemble and link
 * Allowing multi file may not be a good idea...
 */
int main(int argc, char* argv[]) {
  if (argc < 2)
    Usage();

  program = std::string(argv[0]);
  for (auto i = 1; i < argc; ++i) {
    if (argv[i][0] != '-') {
      filename_in = std::string(argv[i]);
      ValidateFileName(filename_in);
      filenames_in.push_back(filename_in);
      continue;
    }

    gcc_args.push_back(argv[i]);
    switch (argv[i][1]) {
    case 'h': Usage(); break;
    case 'E': only_preprocess = true; break;
    case 'S': only_compile = true; break;
    case 'I': ParseInclude(argc, argv, i); break;
    case 'D': ParseDefine(argc, argv, i); break;
    case 'o':
      specified_out_name = true;
      ParseOut(argc, argv, i); break;
    case 'g': gcc_args.pop_back(); debug = true; break;
    default:;
    }
  }

#ifdef DEBUG
  RunWgtcc();
#else
  for (const auto& filename: filenames_in) {
    filename_in = filename;
    pid_t pid = fork();
    if (pid < 0) {
      Error("fork error");
    } else if (pid == 0) {
      // Do work in child process
      return RunWgtcc();
    }
  }

  for (size_t i = 0; i < filenames_in.size(); ++i) {
      int stat;
      wait(&stat);
      if (WIFEXITED(stat) && WEXITSTATUS(stat))
        return 0;
  }
#endif

  if (only_preprocess || only_compile) {
    if (specified_out_name && filenames_in.size() > 1)
      Error("cannot specifier output filename with multiple input file");
    return 0;
  }

  std::list<std::string> filenames_out;
  for (auto& filename: filenames_in) {
    if (GetExtension(filename) == ".c") {
      gcc_args.push_back(GetName(filename));
      gcc_args.back().back() = 's';
    } else {
      gcc_args.clear();
      for (int i = 1; i < argc; ++i)
        gcc_args.push_back(argv[i]);
      break;
    }
  }
  auto ret = RunGcc();
  auto cmd = "rm -f " + filename_out;
  if (system(cmd.c_str())) {}
  return ret;
}
<|endoftext|>


<commit_before>#include "includes.h"
#include "parser/includes.h"

extern int yyparse();
extern void yyrestart(FILE*);

string get_load_path(int argc, char **argv)
{
  for(int i = 1; i < argc; i++) {
    if(strcmp(argv[i], "-I") == 0) {
      return string(argv[i+1]);
    }
  }
  return "";
}

void prepare_argv(int argc, char **argv)
{
  // set command line arguments in global ARGV variable as Array
  Array_p args_arr = new Array();
  for(int i = 1; i < argc; i++) {
    string arg(argv[i]);
    // skip -I + root loadpath arg
    if(arg == "-I") {
      i++;
      continue;
    }
    args_arr->insert(String::from_value(arg));
  }
  global_scope->define("ARGV", args_arr);
}

void exec_from_stdin()
{
  yyrestart(stdin);
  try {
    yyparse();
  } catch(FancyException *ex) {
    errorln("GOT UNCAUGHT EXCEPTION, ABORTING.");
    errorln(ex->to_s());
    // keep it running!
    exec_from_stdin();
  }
}

int main(int argc, char **argv)
{
  GC_INIT();

  fancy::parser::load_path.push_back(get_load_path(argc, argv));
  fancy::bootstrap::init_core_classes();
  fancy::bootstrap::init_global_objects();
  fancy::bootstrap::init_global_scope();
  fancy::Number::init_cache();

  string boot_file = "lib/boot.fnc";
  fancy::parser::parse_file(boot_file);

  try {
    if (argc > 1) {
      prepare_argv(argc, argv);
      string filename = string(argv[1]);
      if(filename == "-I") {
        if(argc > 3) {
          filename = string(argv[3]);
          fancy::parser::parse_file(filename);
        } else {
          exec_from_stdin();
        }
      } else {
        fancy::parser::parse_file(filename);
      }
    } else {
      exec_from_stdin();
    }
  } catch(UnknownIdentifierError &ex) {
    cout << "Error:" << endl;
  }

  // cout << "heap size: " << GC_get_bytes_since_gc() << endl;
  // GC_gcollect();
  // cout << "heap size after collect: " << GC_get_bytes_since_gc() << endl;
  // cout << "Completed " << GC_gc_no << " collections" <<endl;
  // cout << "Heap size is " << GC_get_heap_size() << endl;

  return 0;
}

<commit_msg>src/main.cc: small tweak to load path for boot.fnc file.<commit_after>#include "includes.h"
#include "parser/includes.h"

extern int yyparse();
extern void yyrestart(FILE*);

string get_load_path(int argc, char **argv)
{
  for(int i = 1; i < argc; i++) {
    if(strcmp(argv[i], "-I") == 0) {
      return string(argv[i+1]);
    }
  }
  return "."; // current dir
}

void prepare_argv(int argc, char **argv)
{
  // set command line arguments in global ARGV variable as Array
  Array_p args_arr = new Array();
  for(int i = 1; i < argc; i++) {
    string arg(argv[i]);
    // skip -I + root loadpath arg
    if(arg == "-I") {
      i++;
      continue;
    }
    args_arr->insert(String::from_value(arg));
  }
  global_scope->define("ARGV", args_arr);
}

void exec_from_stdin()
{
  yyrestart(stdin);
  try {
    yyparse();
  } catch(FancyException *ex) {
    errorln("GOT UNCAUGHT EXCEPTION, ABORTING.");
    errorln(ex->to_s());
    // keep it running!
    exec_from_stdin();
  }
}

int main(int argc, char **argv)
{
  GC_INIT();

  fancy::parser::load_path.push_back(get_load_path(argc, argv));
  fancy::bootstrap::init_core_classes();
  fancy::bootstrap::init_global_objects();
  fancy::bootstrap::init_global_scope();
  fancy::Number::init_cache();

  string boot_file = "boot.fnc";
  string stdlib_path = get_load_path(argc, argv) + "/lib";
  fancy::parser::load_path.push_back(stdlib_path);
  fancy::parser::parse_file(boot_file);

  try {
    if (argc > 1) {
      prepare_argv(argc, argv);
      string filename = string(argv[1]);
      if(filename == "-I") {
        if(argc > 3) {
          filename = string(argv[3]);
          fancy::parser::parse_file(filename);
        } else {
          exec_from_stdin();
        }
      } else {
        fancy::parser::parse_file(filename);
      }
    } else {
      exec_from_stdin();
    }
  } catch(UnknownIdentifierError &ex) {
    cout << "Error:" << endl;
  }

  // cout << "heap size: " << GC_get_bytes_since_gc() << endl;
  // GC_gcollect();
  // cout << "heap size after collect: " << GC_get_bytes_since_gc() << endl;
  // cout << "Completed " << GC_gc_no << " collections" <<endl;
  // cout << "Heap size is " << GC_get_heap_size() << endl;

  return 0;
}

<|endoftext|>