<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2018 The Machinecoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <protocol.h>

#include <util.h>
#include <utilstrencodings.h>

#ifndef WIN32
# include <arpa/inet.h>
#endif

namespace NetMsgType {
const char *VERSION="version";
const char *VERACK="verack";
const char *ADDR="addr";
const char *INV="inv";
const char *GETDATA="getdata";
const char *MERKLEBLOCK="merkleblock";
const char *GETBLOCKS="getblocks";
const char *GETHEADERS="getheaders";
const char *TX="tx";
const char *HEADERS="headers";
const char *BLOCK="block";
const char *GETADDR="getaddr";
const char *MEMPOOL="mempool";
const char *PING="ping";
const char *PONG="pong";
const char *NOTFOUND="notfound";
const char *FILTERLOAD="filterload";
const char *FILTERADD="filteradd";
const char *FILTERCLEAR="filterclear";
const char *REJECT="reject";
const char *SENDHEADERS="sendheaders";
const char *FEEFILTER="feefilter";
const char *SENDCMPCT="sendcmpct";
const char *CMPCTBLOCK="cmpctblock";
const char *GETBLOCKTXN="getblocktxn";
const char *BLOCKTXN="blocktxn";
// Machinecoin message types
const char *MASTERNODEPAYMENTVOTE="mnw";
const char *MASTERNODEPAYMENTBLOCK="mnwb";
const char *MASTERNODEPAYMENTSYNC="mnget";
const char *MNQUORUM="mn quorum"; // not implemented
const char *MNANNOUNCE="mnb";
const char *MNPING="mnp";
const char *DSEG="dseg";
const char *SYNCSTATUSCOUNT="ssc";
const char *MNGOVERNANCESYNC="govsync";
const char *MNGOVERNANCEOBJECT="govobj";
const char *MNGOVERNANCEOBJECTVOTE="govobjvote";
const char *MNVERIFY="mnv";
} // namespace NetMsgType

/** All known message types. Keep this in the same order as the list of
 * messages above and in protocol.h.
 */
const static std::string allNetMessageTypes[] = {
    NetMsgType::VERSION,
    NetMsgType::VERACK,
    NetMsgType::ADDR,
    NetMsgType::INV,
    NetMsgType::GETDATA,
    NetMsgType::MERKLEBLOCK,
    NetMsgType::GETBLOCKS,
    NetMsgType::GETHEADERS,
    NetMsgType::TX,
    NetMsgType::HEADERS,
    NetMsgType::BLOCK,
    NetMsgType::GETADDR,
    NetMsgType::MEMPOOL,
    NetMsgType::PING,
    NetMsgType::PONG,
    NetMsgType::NOTFOUND,
    NetMsgType::FILTERLOAD,
    NetMsgType::FILTERADD,
    NetMsgType::FILTERCLEAR,
    NetMsgType::REJECT,
    NetMsgType::SENDHEADERS,
    NetMsgType::FEEFILTER,
    NetMsgType::SENDCMPCT,
    NetMsgType::CMPCTBLOCK,
    NetMsgType::GETBLOCKTXN,
    NetMsgType::BLOCKTXN,
    // Machinecoin message types
    // NOTE: do NOT include non-implmented here, we want them to be "Unknown command" in ProcessMessage()
    NetMsgType::MASTERNODEPAYMENTVOTE,
    // NetMsgType::MASTERNODEPAYMENTBLOCK, // there is no message for this, only inventory
    NetMsgType::MASTERNODEPAYMENTSYNC,
    NetMsgType::MNANNOUNCE,
    NetMsgType::MNPING,
    NetMsgType::DSEG,
    NetMsgType::SYNCSTATUSCOUNT,
    NetMsgType::MNGOVERNANCESYNC,
    NetMsgType::MNGOVERNANCEOBJECT,
    NetMsgType::MNGOVERNANCEOBJECTVOTE,
    NetMsgType::MNVERIFY,
};
const static std::vector<std::string> allNetMessageTypesVec(allNetMessageTypes, allNetMessageTypes+ARRAYLEN(allNetMessageTypes));

CMessageHeader::CMessageHeader(const MessageStartChars& pchMessageStartIn)
{
    memcpy(pchMessageStart, pchMessageStartIn, MESSAGE_START_SIZE);
    memset(pchCommand, 0, sizeof(pchCommand));
    nMessageSize = -1;
    memset(pchChecksum, 0, CHECKSUM_SIZE);
}

CMessageHeader::CMessageHeader(const MessageStartChars& pchMessageStartIn, const char* pszCommand, unsigned int nMessageSizeIn)
{
    memcpy(pchMessageStart, pchMessageStartIn, MESSAGE_START_SIZE);
    memset(pchCommand, 0, sizeof(pchCommand));
    strncpy(pchCommand, pszCommand, COMMAND_SIZE);
    nMessageSize = nMessageSizeIn;
    memset(pchChecksum, 0, CHECKSUM_SIZE);
}

std::string CMessageHeader::GetCommand() const
{
    return std::string(pchCommand, pchCommand + strnlen(pchCommand, COMMAND_SIZE));
}

bool CMessageHeader::IsValid(const MessageStartChars& pchMessageStartIn) const
{
    // Check start string
    if (memcmp(pchMessageStart, pchMessageStartIn, MESSAGE_START_SIZE) != 0)
        return false;

    // Check the command string for errors
    for (const char* p1 = pchCommand; p1 < pchCommand + COMMAND_SIZE; p1++)
    {
        if (*p1 == 0)
        {
            // Must be all zeros after the first zero
            for (; p1 < pchCommand + COMMAND_SIZE; p1++)
                if (*p1 != 0)
                    return false;
        }
        else if (*p1 < ' ' || *p1 > 0x7E)
            return false;
    }

    // Message size
    if (nMessageSize > MAX_SIZE)
    {
        LogPrintf("CMessageHeader::IsValid(): (%s, %u bytes) nMessageSize > MAX_SIZE\n", GetCommand(), nMessageSize);
        return false;
    }

    return true;
}

CAddress::CAddress() : CService()
{
    Init();
}

CAddress::CAddress(CService ipIn, ServiceFlags nServicesIn) : CService(ipIn)
{
    Init();
    nServices = nServicesIn;
}

void CAddress::Init()
{
    nServices = NODE_NONE;
    nTime = 100000000;
}

CInv::CInv()
{
    type = 0;
    hash.SetNull();
}

CInv::CInv(int typeIn, const uint256& hashIn) : type(typeIn), hash(hashIn) {}

bool operator<(const CInv& a, const CInv& b)
{
    return (a.type < b.type || (a.type == b.type && a.hash < b.hash));
}

bool CInv::IsKnownType() const
{
    LogPrintf("TYPE: %s\n", type);
    LogPrintf("LENGTH: %s\n", (int)ARRAYLEN(allNetMessageTypes));
    LogPrintf("COMMAND: %s\n", allNetMessageTypes[type]);
    //return (type >= 1 && type < (int)ARRAYLEN(allNetMessageTypes));
}

std::string CInv::GetCommand() const
{
    IsKnownType();
    std::string cmd;
    if (type & MSG_WITNESS_FLAG)
        cmd.append("witness-");
    int masked = type & MSG_TYPE_MASK;
    switch (masked)
    {
    case MSG_TX:             return cmd.append(NetMsgType::TX);
    case MSG_BLOCK:          return cmd.append(NetMsgType::BLOCK);
    case MSG_FILTERED_BLOCK: return cmd.append(NetMsgType::MERKLEBLOCK);
    case MSG_CMPCT_BLOCK:    return cmd.append(NetMsgType::CMPCTBLOCK);
    default:
        throw std::out_of_range(strprintf("CInv::GetCommand(): type=%d unknown type", type));
    }
}

std::string CInv::ToString() const
{
    try {
        return strprintf("%s %s", GetCommand(), hash.ToString());
    } catch(const std::out_of_range &) {
        return strprintf("0x%08x %s", type, hash.ToString());
    }
}

const std::vector<std::string> &getAllNetMessageTypes()
{
    return allNetMessageTypesVec;
}
<commit_msg>no message<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2018 The Machinecoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <protocol.h>

#include <util.h>
#include <utilstrencodings.h>

#ifndef WIN32
# include <arpa/inet.h>
#endif

namespace NetMsgType {
const char *VERSION="version";
const char *VERACK="verack";
const char *ADDR="addr";
const char *INV="inv";
const char *GETDATA="getdata";
const char *MERKLEBLOCK="merkleblock";
const char *GETBLOCKS="getblocks";
const char *GETHEADERS="getheaders";
const char *TX="tx";
const char *HEADERS="headers";
const char *BLOCK="block";
const char *GETADDR="getaddr";
const char *MEMPOOL="mempool";
const char *PING="ping";
const char *PONG="pong";
const char *NOTFOUND="notfound";
const char *FILTERLOAD="filterload";
const char *FILTERADD="filteradd";
const char *FILTERCLEAR="filterclear";
const char *REJECT="reject";
const char *SENDHEADERS="sendheaders";
const char *FEEFILTER="feefilter";
const char *SENDCMPCT="sendcmpct";
const char *CMPCTBLOCK="cmpctblock";
const char *GETBLOCKTXN="getblocktxn";
const char *BLOCKTXN="blocktxn";
// Machinecoin message types
const char *MASTERNODEPAYMENTVOTE="mnw";
const char *MASTERNODEPAYMENTBLOCK="mnwb";
const char *MASTERNODEPAYMENTSYNC="mnget";
const char *MNQUORUM="mn quorum"; // not implemented
const char *MNANNOUNCE="mnb";
const char *MNPING="mnp";
const char *DSEG="dseg";
const char *SYNCSTATUSCOUNT="ssc";
const char *MNGOVERNANCESYNC="govsync";
const char *MNGOVERNANCEOBJECT="govobj";
const char *MNGOVERNANCEOBJECTVOTE="govobjvote";
const char *MNVERIFY="mnv";
} // namespace NetMsgType

/** All known message types. Keep this in the same order as the list of
 * messages above and in protocol.h.
 */
const static std::string allNetMessageTypes[] = {
    NetMsgType::VERSION,
    NetMsgType::VERACK,
    NetMsgType::ADDR,
    NetMsgType::INV,
    NetMsgType::GETDATA,
    NetMsgType::MERKLEBLOCK,
    NetMsgType::GETBLOCKS,
    NetMsgType::GETHEADERS,
    NetMsgType::TX,
    NetMsgType::HEADERS,
    NetMsgType::BLOCK,
    NetMsgType::GETADDR,
    NetMsgType::MEMPOOL,
    NetMsgType::PING,
    NetMsgType::PONG,
    NetMsgType::NOTFOUND,
    NetMsgType::FILTERLOAD,
    NetMsgType::FILTERADD,
    NetMsgType::FILTERCLEAR,
    NetMsgType::REJECT,
    NetMsgType::SENDHEADERS,
    NetMsgType::FEEFILTER,
    NetMsgType::SENDCMPCT,
    NetMsgType::CMPCTBLOCK,
    NetMsgType::GETBLOCKTXN,
    NetMsgType::BLOCKTXN,
    // Machinecoin message types
    // NOTE: do NOT include non-implmented here, we want them to be "Unknown command" in ProcessMessage()
    NetMsgType::MASTERNODEPAYMENTVOTE,
    // NetMsgType::MASTERNODEPAYMENTBLOCK, // there is no message for this, only inventory
    NetMsgType::MASTERNODEPAYMENTSYNC,
    NetMsgType::MNANNOUNCE,
    NetMsgType::MNPING,
    NetMsgType::DSEG,
    NetMsgType::SYNCSTATUSCOUNT,
    NetMsgType::MNGOVERNANCESYNC,
    NetMsgType::MNGOVERNANCEOBJECT,
    NetMsgType::MNGOVERNANCEOBJECTVOTE,
    NetMsgType::MNVERIFY,
};
const static std::vector<std::string> allNetMessageTypesVec(allNetMessageTypes, allNetMessageTypes+ARRAYLEN(allNetMessageTypes));

CMessageHeader::CMessageHeader(const MessageStartChars& pchMessageStartIn)
{
    memcpy(pchMessageStart, pchMessageStartIn, MESSAGE_START_SIZE);
    memset(pchCommand, 0, sizeof(pchCommand));
    nMessageSize = -1;
    memset(pchChecksum, 0, CHECKSUM_SIZE);
}

CMessageHeader::CMessageHeader(const MessageStartChars& pchMessageStartIn, const char* pszCommand, unsigned int nMessageSizeIn)
{
    memcpy(pchMessageStart, pchMessageStartIn, MESSAGE_START_SIZE);
    memset(pchCommand, 0, sizeof(pchCommand));
    strncpy(pchCommand, pszCommand, COMMAND_SIZE);
    nMessageSize = nMessageSizeIn;
    memset(pchChecksum, 0, CHECKSUM_SIZE);
}

std::string CMessageHeader::GetCommand() const
{
    return std::string(pchCommand, pchCommand + strnlen(pchCommand, COMMAND_SIZE));
}

bool CMessageHeader::IsValid(const MessageStartChars& pchMessageStartIn) const
{
    // Check start string
    if (memcmp(pchMessageStart, pchMessageStartIn, MESSAGE_START_SIZE) != 0)
        return false;

    // Check the command string for errors
    for (const char* p1 = pchCommand; p1 < pchCommand + COMMAND_SIZE; p1++)
    {
        if (*p1 == 0)
        {
            // Must be all zeros after the first zero
            for (; p1 < pchCommand + COMMAND_SIZE; p1++)
                if (*p1 != 0)
                    return false;
        }
        else if (*p1 < ' ' || *p1 > 0x7E)
            return false;
    }

    // Message size
    if (nMessageSize > MAX_SIZE)
    {
        LogPrintf("CMessageHeader::IsValid(): (%s, %u bytes) nMessageSize > MAX_SIZE\n", GetCommand(), nMessageSize);
        return false;
    }

    return true;
}

CAddress::CAddress() : CService()
{
    Init();
}

CAddress::CAddress(CService ipIn, ServiceFlags nServicesIn) : CService(ipIn)
{
    Init();
    nServices = nServicesIn;
}

void CAddress::Init()
{
    nServices = NODE_NONE;
    nTime = 100000000;
}

CInv::CInv()
{
    type = 0;
    hash.SetNull();
}

CInv::CInv(int typeIn, const uint256& hashIn) : type(typeIn), hash(hashIn) {}

bool operator<(const CInv& a, const CInv& b)
{
    return (a.type < b.type || (a.type == b.type && a.hash < b.hash));
}

bool CInv::IsKnownType() const
{
    LogPrintf("TYPE: %s\n", type);
    LogPrintf("LENGTH: %s\n", (int)ARRAYLEN(allNetMessageTypes));
    LogPrintf("COMMAND: %s\n", allNetMessageTypes[type]);
    return (type >= 1 && type < (int)ARRAYLEN(allNetMessageTypes));
}

std::string CInv::GetCommand() const
{
    //IsKnownType();
    std::string cmd;
    if (type & MSG_WITNESS_FLAG)
        cmd.append("witness-");
    int masked = type & MSG_TYPE_MASK;
    switch (masked)
    {
    case MSG_TX:             return cmd.append(NetMsgType::TX);
    case MSG_BLOCK:          return cmd.append(NetMsgType::BLOCK);
    case MSG_FILTERED_BLOCK: return cmd.append(NetMsgType::MERKLEBLOCK);
    case MSG_CMPCT_BLOCK:    return cmd.append(NetMsgType::CMPCTBLOCK);
    default:
        throw std::out_of_range(strprintf("CInv::GetCommand(): type=%d unknown type", type));
    }
}

std::string CInv::ToString() const
{
    try {
        return strprintf("%s %s", GetCommand(), hash.ToString());
    } catch(const std::out_of_range &) {
        return strprintf("0x%08x %s", type, hash.ToString());
    }
}

const std::vector<std::string> &getAllNetMessageTypes()
{
    return allNetMessageTypesVec;
}
<|endoftext|>


<commit_before>/*
 * rational.cpp
 */
#include "rational.h"

namespace c8 {
    rational::rational(double v) {
        /*
         * Split our double into a significand and an exponent.
         */
        uint64_t *vbits_ptr = reinterpret_cast<uint64_t *>(&v);
        uint64_t vbits = *vbits_ptr;
        bool neg = (vbits & 0x8000000000000000ULL) ? true : false;
        vbits &= 0x7fffffffffffffffULL;
        int64_t exp = static_cast<int64_t>(vbits >> 52) - 1023;
        uint64_t sig = static_cast<uint64_t>(vbits & 0x000fffffffffffffULL);

        /*
         * Is this a denormalized value?
         */
        if (exp == -1022) {
            /*
             * For zero values the exponent must always be zero too.
             */
            num_ = 0;
            denom_ = 1;
        } else {
            /*
             * For non-denormal numbers we have an implied 52nd bit set.  Set that
             * explicitly now!
             */
            sig |= 0x0010000000000000ULL;
            exp -= 52;

            natural n = natural(sig);

            if (exp < 0) {
                num_ = integer(n);
                denom_ = natural(1) << static_cast<unsigned int>(-exp);
            } else {
                num_ = integer(n << static_cast<unsigned int>(exp));
                denom_ = natural(1);
            }

            if (neg) {
                num_ = -num_;
            }
        }

        normalize();
    }

    rational::rational(const std::string &v) {
        /*
         * Do we have a '/' character separating a numerator and denominator?
         */
        std::size_t pos = v.find(std::string("/"));
        if (pos == std::string::npos) {
            num_ = integer(v);
        } else {
            num_ = integer(v.substr(0, pos));
            denom_ = natural(v.substr(pos + 1));
        }

        normalize();
    }

    /*
     * Add another rational to this one.
     */
    auto rational::add(const rational &v) const -> rational {
        rational res;

        res.num_ = (num_ * integer(v.denom_)) + (integer(denom_) * v.num_);
        res.denom_ = denom_ * v.denom_;

        res.normalize();

        return res;
    }

    /*
     * Subtract another rational from this one.
     *
     * Note that there is a subtle difference between the rational subtract operation
     * and the natural number version: We don't have to worry about throwing
     * exceptions for negative results.
     */
    auto rational::subtract(const rational &v) const -> rational {
        rational res;

        res.num_ = (num_ * integer(v.denom_)) - (integer(denom_) * v.num_);
        res.denom_ = denom_ * v.denom_;

        res.normalize();

        return res;
    }

    /*
     * Multiply another rational with this one.
     */
    auto rational::multiply(const rational &v) const -> rational {
        rational res;

        res.num_ = num_ * v.num_;
        res.denom_ = denom_ * v.denom_;

        res.normalize();

        return res;
    }

    /*
     * Divide this rational by another one.
     */
    auto rational::divide(const rational &v) const -> rational {
        rational res;

        /*
         * Are we attempting to divide by zero?  If we are then throw an exception.
         */
        if (iszero(abs(v.num_))) {
            throw c8::divide_by_zero();
        }

        res.num_ = num_ * integer(v.denom_);
        integer d = integer(denom_) * v.num_;
        if (isnegative(d)) {
            res.num_ = -res.num_;
        }

        res.denom_ = abs(d);

        res.normalize();

        return res;
    }

    /*
     * Compare a rational with this one.
     */
    auto rational::compare(const rational &v) const -> rational_comparison {
        integer lhs = num_ * integer(v.denom_);
        integer rhs = v.num_ * integer(denom_);

        auto ures = lhs.compare(rhs);
        switch (ures) {
        case integer_comparison::lt:
            return rational_comparison::lt;

        case integer_comparison::eq:
            return rational_comparison::eq;

        case integer_comparison::gt:
            return rational_comparison::gt;
        }
    }

    /*
     * Normalize the data.
     */
    auto rational::normalize() -> void {
        /*
         * Find the GCD of the numerator and denominator.
         */
        natural g = gcd(abs(num_), denom_);
        num_ /= g;
        denom_ /= g;
    }

    /*
     * << operator to print a rational.
     */
    auto operator<<(std::ostream &outstr, const rational &v) -> std::ostream & {
        outstr << v.num_ << '/' << v.denom_;

        return outstr;
    }
}

<commit_msg>Clean up c8::rational constructor<commit_after>/*
 * rational.cpp
 */
#include "rational.h"

namespace c8 {
    rational::rational(double v) {
        /*
         * Split our double into a significand and an exponent.
         */
        uint64_t *vbits_ptr = reinterpret_cast<uint64_t *>(&v);
        uint64_t vbits = *vbits_ptr;
        bool neg = (vbits & 0x8000000000000000ULL) ? true : false;
        vbits &= 0x7fffffffffffffffULL;
        int64_t exp = static_cast<int64_t>(vbits >> 52) - 1023;
        int64_t sig = static_cast<int64_t>(vbits & 0x000fffffffffffffULL);

        /*
         * Is this an infinity or a NaN?
         */
        if (exp == 1024) {
            throw c8::not_a_number();
        }

        /*
         * Do we have a normalized value (as opposed to a denormalized one)?  Most
         * floating point values are normalized.
         */
        if (exp != -1022) {
            /*
             * For normal numbers we have an implied 52nd bit set.  Set that
             * explicitly now!  When we do that though we're also shifting our
             * exponent by 52 places too.
             */
            sig |= 0x0010000000000000ULL;
            exp -= 52;
        }

        if (neg) {
            sig = -sig;
        }

        integer i = integer(sig);

        if (exp < 0) {
            num_ = i;
            denom_ = natural(1) << static_cast<unsigned int>(-exp);
        } else {
            num_ = i << static_cast<unsigned int>(exp);
            denom_ = natural(1);
        }

        normalize();
    }

    rational::rational(const std::string &v) {
        /*
         * Do we have a '/' character separating a numerator and denominator?
         */
        std::size_t pos = v.find(std::string("/"));
        if (pos == std::string::npos) {
            num_ = integer(v);
        } else {
            num_ = integer(v.substr(0, pos));
            denom_ = natural(v.substr(pos + 1));
        }

        normalize();
    }

    /*
     * Add another rational to this one.
     */
    auto rational::add(const rational &v) const -> rational {
        rational res;

        res.num_ = (num_ * integer(v.denom_)) + (integer(denom_) * v.num_);
        res.denom_ = denom_ * v.denom_;

        res.normalize();

        return res;
    }

    /*
     * Subtract another rational from this one.
     *
     * Note that there is a subtle difference between the rational subtract operation
     * and the natural number version: We don't have to worry about throwing
     * exceptions for negative results.
     */
    auto rational::subtract(const rational &v) const -> rational {
        rational res;

        res.num_ = (num_ * integer(v.denom_)) - (integer(denom_) * v.num_);
        res.denom_ = denom_ * v.denom_;

        res.normalize();

        return res;
    }

    /*
     * Multiply another rational with this one.
     */
    auto rational::multiply(const rational &v) const -> rational {
        rational res;

        res.num_ = num_ * v.num_;
        res.denom_ = denom_ * v.denom_;

        res.normalize();

        return res;
    }

    /*
     * Divide this rational by another one.
     */
    auto rational::divide(const rational &v) const -> rational {
        rational res;

        /*
         * Are we attempting to divide by zero?  If we are then throw an exception.
         */
        if (iszero(abs(v.num_))) {
            throw c8::divide_by_zero();
        }

        res.num_ = num_ * integer(v.denom_);
        integer d = integer(denom_) * v.num_;
        if (isnegative(d)) {
            res.num_ = -res.num_;
        }

        res.denom_ = abs(d);

        res.normalize();

        return res;
    }

    /*
     * Compare a rational with this one.
     */
    auto rational::compare(const rational &v) const -> rational_comparison {
        integer lhs = num_ * integer(v.denom_);
        integer rhs = v.num_ * integer(denom_);

        auto ures = lhs.compare(rhs);
        switch (ures) {
        case integer_comparison::lt:
            return rational_comparison::lt;

        case integer_comparison::eq:
            return rational_comparison::eq;

        case integer_comparison::gt:
            return rational_comparison::gt;
        }
    }

    /*
     * Normalize the data.
     */
    auto rational::normalize() -> void {
        /*
         * Find the GCD of the numerator and denominator.
         */
        natural g = gcd(abs(num_), denom_);
        num_ /= g;
        denom_ /= g;
    }

    /*
     * << operator to print a rational.
     */
    auto operator<<(std::ostream &outstr, const rational &v) -> std::ostream & {
        outstr << v.num_ << '/' << v.denom_;

        return outstr;
    }
}

<|endoftext|>


<commit_before>#include "SpriteRepeater.h"

using namespace cocos2d;

namespace avalon {
namespace graphics {

cocos2d::Node* SpriteRepeater::createSprite()
{
    auto rootNode = cocos2d::Node::create();

    auto node = cocos2d::Sprite::createWithSpriteFrameName(fileName);
    assert(node && "Couldnt load sprite!");

    auto textureWidth = node->getTextureRect().size.width;
    auto textureHeight = node->getTextureRect().size.height;

    int countX = static_cast<int>(ceil(width / textureWidth));
    int countY = static_cast<int>(ceil(height / textureHeight));

    if (!repeatHorizontal)
        countX = 0;

    if (!repeatVertical)
        countY = 0;

    for (int x = 0; x <= countX; ++x) {
        for (int y = 0; y <= countY; ++y) {
            node = cocos2d::Sprite::createWithSpriteFrameName(fileName);
            node->setPosition({x * (textureWidth + paddingX), y * (textureHeight + paddingY)});

            cocos2d::Vec2 anchorPoint(0.0, 0.0);
            if (flipHorizontal && x % 2 == 1) {
                node->setScaleX(-1);
                anchorPoint.x = 1.0;
            }

            if (flipVertical && y % 2 == 1) {
                node->setScaleY(-1);
                anchorPoint.y = 1.0;
            }

            node->setAnchorPoint(anchorPoint);

            rootNode->addChild(node);
        }
    }

    return rootNode;
}

} // namespace graphics
} // namespace avalon
<commit_msg>bugfix: expand downwards<commit_after>#include "SpriteRepeater.h"

using namespace cocos2d;

namespace avalon {
namespace graphics {

cocos2d::Node* SpriteRepeater::createSprite()
{
    auto rootNode = cocos2d::Node::create();

    auto node = cocos2d::Sprite::createWithSpriteFrameName(fileName);
    assert(node && "Couldnt load sprite!");

    auto textureWidth = node->getTextureRect().size.width;
    auto textureHeight = node->getTextureRect().size.height;

    int countX = static_cast<int>(ceil(width / textureWidth));
    int countY = static_cast<int>(ceil(height / textureHeight));

    if (!repeatHorizontal)
        countX = 0;

    if (!repeatVertical)
        countY = 0;

    for (int x = 0; x <= countX; ++x) {
        for (int y = 0; y <= countY; ++y) {
            node = cocos2d::Sprite::createWithSpriteFrameName(fileName);
            node->setPosition({x * (textureWidth + paddingX), -y * (textureHeight + paddingY)});

            cocos2d::Vec2 anchorPoint(0.0, 0.0);
            if (flipHorizontal && x % 2 == 1) {
                node->setScaleX(-1);
                anchorPoint.x = 1.0;
            }

            if (flipVertical && y % 2 == 1) {
                node->setScaleY(-1);
                anchorPoint.y = 1.0;
            }

            node->setAnchorPoint(anchorPoint);

            rootNode->addChild(node);
        }
    }

    return rootNode;
}

} // namespace graphics
} // namespace avalon
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2014-2015 Pavel Dolgov
 *
 * See the LICENSE file for terms of use.
 */

#ifndef CONSTANTS_HPP_
#define CONSTANTS_HPP_

/** The proportion of a number in a cell */
const double NUMBER_PROPORTION = 0.900000;

/** Maximum size of the game board to resize content */
const int RESIZE_MAX = 5;

/** Minimum width/length of game board */
const int MIN_WIDTH = 3;

/** Maximum width/length of game board */
const int MAX_WIDTH = 16;

/** Minimum number of minutes to play */
const int MIN_TIME = 1;

/** Maximum number of minutes to play */
const int MAX_TIME = 1000;

/** Maximum winning score */
const int MAX_SCORE = 9999999;

/** Maximum length of indices */
const int MAX_INDEX_LENGTH = 2;

/** Minimal amount of spaces between numbers on the board */
const int NUMBER_OF_SPACES = 2;

#endif
<commit_msg>constants: delete MAX_SCORE, MAX_TIME, MIN_TIME<commit_after>/*
 * Copyright (C) 2014-2015 Pavel Dolgov
 *
 * See the LICENSE file for terms of use.
 */

#ifndef CONSTANTS_HPP_
#define CONSTANTS_HPP_

/** The proportion of a number in a cell */
const double NUMBER_PROPORTION = 0.900000;

/** Maximum size of the game board to resize content */
const int RESIZE_MAX = 5;

/** Minimum width/length of game board */
const int MIN_WIDTH = 3;

/** Maximum width/length of game board */
const int MAX_WIDTH = 16;

/** Maximum length of indices */
const int MAX_INDEX_LENGTH = 2;

/** Minimal amount of spaces between numbers on the board */
const int NUMBER_OF_SPACES = 2;

#endif
<|endoftext|>


<commit_before>#include "node.h"
#include "node_version.h"
#include <string>
using namespace v8;
using namespace node;

// For some reason this needs to be out of the object or node won't load the
// library.
static Persistent<FunctionTemplate> dataWrapperTmpl;
static Persistent<Function>         dataWrapperCtor;

class ContextifyContext : ObjectWrap {
public:
    Persistent<Context> context;
    Persistent<Object>  sandbox;
    Persistent<Object>  proxyGlobal;

    static Persistent<FunctionTemplate> jsTmpl;

    ContextifyContext(Local<Object> sbox) {
        HandleScope scope;
        #if NODE_MODULE_VERSION < 12
            sandbox = Persistent<Object>::New(sbox);
        #else
            sandbox = Persistent<Object>::New(Isolate::GetCurrent(), sbox);
        #endif
    }

    ~ContextifyContext() {
        context.Dispose();
        context.Clear();
        proxyGlobal.Dispose();
        proxyGlobal.Clear();
        sandbox.Dispose();
        sandbox.Clear();
    }

    // We override ObjectWrap::Wrap so that we can create our context after
    // we have a reference to our "host" JavaScript object.  If we try to use
    // handle_ in the ContextifyContext constructor, it will be empty since it's
    // set in ObjectWrap::Wrap.
    inline void Wrap(Handle<Object> handle) {
        ObjectWrap::Wrap(handle);
        context     = createV8Context();
        #if NODE_MODULE_VERSION < 12
            proxyGlobal = Persistent<Object>::New(context->Global());
        #else
            proxyGlobal = Persistent<Object>::New(Isolate::GetCurrent(), context->Global());
        #endif
    }

    // This is an object that just keeps an internal pointer to this
    // ContextifyContext.  It's passed to the NamedPropertyHandler.  If we
    // pass the main JavaScript context object we're embedded in, then the
    // NamedPropertyHandler will store a reference to it forever and keep it
    // from getting gc'd.
    Local<Object> createDataWrapper () {
        HandleScope scope;
        Local<Object> wrapper = dataWrapperCtor->NewInstance();
#if NODE_MAJOR_VERSION > 0 || (NODE_MINOR_VERSION == 9 && (NODE_PATCH_VERSION >= 6 && NODE_PATCH_VERSION <= 10)) || NODE_MINOR_VERSION >= 11
        wrapper->SetAlignedPointerInInternalField(0, this);
#else
        wrapper->SetPointerInInternalField(0, this);
#endif
        return scope.Close(wrapper);
    }

    Persistent<Context> createV8Context() {
        HandleScope scope;
        Local<FunctionTemplate> ftmpl = FunctionTemplate::New();
        ftmpl->SetHiddenPrototype(true);
        ftmpl->SetClassName(sandbox->GetConstructorName());
        Local<ObjectTemplate> otmpl = ftmpl->InstanceTemplate();
        otmpl->SetNamedPropertyHandler(GlobalPropertyGetter,
                                       GlobalPropertySetter,
                                       GlobalPropertyQuery,
                                       GlobalPropertyDeleter,
                                       GlobalPropertyEnumerator,
                                       createDataWrapper());
        otmpl->SetAccessCheckCallbacks(GlobalPropertyNamedAccessCheck,
                                       GlobalPropertyIndexedAccessCheck);
        #if NODE_MODULE_VERSION < 12
            return Context::New(NULL, otmpl);
        #else
            return Persistent<Context>::New(Isolate::GetCurrent(), Context::New(Isolate::GetCurrent(), NULL, otmpl));
        #endif
    }

    static void Init(Handle<Object> target) {
        HandleScope scope;
        #if NODE_MODULE_VERSION < 12
            dataWrapperTmpl = Persistent<FunctionTemplate>::New(FunctionTemplate::New());
        #else
            dataWrapperTmpl = Persistent<FunctionTemplate>::New(Isolate::GetCurrent(), FunctionTemplate::New());
        #endif
        dataWrapperTmpl->InstanceTemplate()->SetInternalFieldCount(1);
        #if NODE_MODULE_VERSION < 12
            dataWrapperCtor = Persistent<Function>::New(dataWrapperTmpl->GetFunction());
        #else
            dataWrapperCtor = Persistent<Function>::New(Isolate::GetCurrent(), dataWrapperTmpl->GetFunction());
        #endif

        #if NODE_MODULE_VERSION < 12
            jsTmpl = Persistent<FunctionTemplate>::New(FunctionTemplate::New(New));
        #else
            jsTmpl = Persistent<FunctionTemplate>::New(Isolate::GetCurrent(), FunctionTemplate::New(New));
        #endif
        jsTmpl->InstanceTemplate()->SetInternalFieldCount(1);
        jsTmpl->SetClassName(String::NewSymbol("ContextifyContext"));

        NODE_SET_PROTOTYPE_METHOD(jsTmpl, "run",       ContextifyContext::Run);
        NODE_SET_PROTOTYPE_METHOD(jsTmpl, "getGlobal", ContextifyContext::GetGlobal);

        target->Set(String::NewSymbol("ContextifyContext"), jsTmpl->GetFunction());
    }

    // args[0] = the sandbox object
    static Handle<Value> New(const Arguments& args) {
        HandleScope scope;
        if (args.Length() < 1) {
            Local<String> msg = String::New("Wrong number of arguments passed to ContextifyContext constructor");
            return ThrowException(Exception::Error(msg));
        }
        if (!args[0]->IsObject()) {
            Local<String> msg = String::New("Argument to ContextifyContext constructor must be an object.");
            return ThrowException(Exception::Error(msg));
        }
        ContextifyContext* ctx = new ContextifyContext(args[0]->ToObject());
        ctx->Wrap(args.This());
        return args.This();
    }

    static Handle<Value> Run(const Arguments& args) {
        HandleScope scope;
        if (args.Length() == 0) {
            Local<String> msg = String::New("Must supply at least 1 argument to run");
            return ThrowException(Exception::Error(msg));
        }
        if (!args[0]->IsString()) {
            Local<String> msg = String::New("First argument to run must be a String.");
            return ThrowException(Exception::Error(msg));
        }
        ContextifyContext* ctx = ObjectWrap::Unwrap<ContextifyContext>(args.This());
        Persistent<Context> context = ctx->context;
        context->Enter();
        Local<String> code = args[0]->ToString();
        TryCatch trycatch;
        Handle<Script> script;
        if (args.Length() > 1 && args[1]->IsString()) {
            script = Script::Compile(code, args[1]->ToString());
        } else {
            script = Script::Compile(code);
        }
        if (script.IsEmpty()) {
          context->Exit();
          return trycatch.ReThrow();
        }
        Handle<Value> result = script->Run();
        context->Exit();
        if (result.IsEmpty()) {
            return trycatch.ReThrow();
        }
        return scope.Close(result);
    }

    static bool InstanceOf(Handle<Value> value) {
      return !value.IsEmpty() && jsTmpl->HasInstance(value);
    }

    static Handle<Value> GetGlobal(const Arguments& args) {
        HandleScope scope;
        ContextifyContext* ctx = ObjectWrap::Unwrap<ContextifyContext>(args.This());
        return ctx->proxyGlobal;
    }

    static bool GlobalPropertyNamedAccessCheck(Local<Object> host,
                                               Local<Value>  key,
                                               AccessType    type,
                                               Local<Value>  data) {
        return true;
    }

    static bool GlobalPropertyIndexedAccessCheck(Local<Object> host,
                                                 uint32_t      key,
                                                 AccessType    type,
                                                 Local<Value>  data) {
        return true;
    }

    static Handle<Value> GlobalPropertyGetter (Local<String> property,
                                               const AccessorInfo &accessInfo) {
        HandleScope scope;
        Local<Object> data = accessInfo.Data()->ToObject();
        ContextifyContext* ctx = ObjectWrap::Unwrap<ContextifyContext>(data);
        Local<Value> rv = ctx->sandbox->GetRealNamedProperty(property);
        if (rv.IsEmpty()) {
            rv = ctx->proxyGlobal->GetRealNamedProperty(property);
        }
        return scope.Close(rv);
    }

    static Handle<Value> GlobalPropertySetter (Local<String> property,
                                               Local<Value> value,
                                               const AccessorInfo &accessInfo) {
        HandleScope scope;
        Local<Object> data = accessInfo.Data()->ToObject();
        ContextifyContext* ctx = ObjectWrap::Unwrap<ContextifyContext>(data);
        ctx->sandbox->Set(property, value);
        return scope.Close(value);
    }

    static Handle<Integer> GlobalPropertyQuery(Local<String> property,
                                               const AccessorInfo &accessInfo) {
        HandleScope scope;
        Local<Object> data = accessInfo.Data()->ToObject();
        ContextifyContext* ctx = ObjectWrap::Unwrap<ContextifyContext>(data);
        if (!ctx->sandbox->GetRealNamedProperty(property).IsEmpty() ||
            !ctx->proxyGlobal->GetRealNamedProperty(property).IsEmpty()) {
            return scope.Close(Integer::New(None));
        }
        return scope.Close(Handle<Integer>());
    }

    static Handle<Boolean> GlobalPropertyDeleter(Local<String> property,
                                                 const AccessorInfo &accessInfo) {
        HandleScope scope;
        Local<Object> data = accessInfo.Data()->ToObject();
        ContextifyContext* ctx = ObjectWrap::Unwrap<ContextifyContext>(data);
        bool success = ctx->sandbox->Delete(property);
        if (!success) {
            success = ctx->proxyGlobal->Delete(property);
        }
        return scope.Close(Boolean::New(success));
    }

    static Handle<Array> GlobalPropertyEnumerator(const AccessorInfo &accessInfo) {
        HandleScope scope;
        Local<Object> data = accessInfo.Data()->ToObject();
        ContextifyContext* ctx = ObjectWrap::Unwrap<ContextifyContext>(data);
        return scope.Close(ctx->sandbox->GetPropertyNames());
    }
};

class ContextifyScript : ObjectWrap {
public:
    static Persistent<FunctionTemplate> scriptTmpl;
    Persistent<Script> script;

    static void Init(Handle<Object> target) {
        HandleScope scope;
        #if NODE_MODULE_VERSION < 12
            scriptTmpl = Persistent<FunctionTemplate>::New(FunctionTemplate::New(New));
        #else
            scriptTmpl = Persistent<FunctionTemplate>::New(Isolate::GetCurrent(), FunctionTemplate::New(New));
        #endif
        scriptTmpl->InstanceTemplate()->SetInternalFieldCount(1);
        scriptTmpl->SetClassName(String::NewSymbol("ContextifyScript"));

        NODE_SET_PROTOTYPE_METHOD(scriptTmpl, "runInContext", RunInContext);

        target->Set(String::NewSymbol("ContextifyScript"),
                    scriptTmpl->GetFunction());
    }

    static Handle<Value> New(const Arguments& args) {
      HandleScope scope;

      ContextifyScript *contextify_script = new ContextifyScript();
      contextify_script->Wrap(args.Holder());

      if (args.Length() < 1) {
        return ThrowException(Exception::TypeError(
              String::New("needs at least 'code' argument.")));
      }

      Local<String> code = args[0]->ToString();
      Local<String> filename = args.Length() > 1
                               ? args[1]->ToString()
                               : String::New("ContextifyScript.<anonymous>");

      Handle<Context> context = Context::GetCurrent();
      Context::Scope context_scope(context);

      // Catch errors
      TryCatch trycatch;

      Handle<Script> v8_script = Script::New(code, filename);

      if (v8_script.IsEmpty()) {
        return trycatch.ReThrow();
      }

      #if NODE_MODULE_VERSION < 12
          contextify_script->script = Persistent<Script>::New(v8_script);
      #else
          contextify_script->script = Persistent<Script>::New(Isolate::GetCurrent(), v8_script);
      #endif

      return args.This();
    }

    static Handle<Value> RunInContext(const Arguments& args) {
        HandleScope scope;
        if (args.Length() == 0) {
            Local<String> msg = String::New("Must supply at least 1 argument to runInContext");
            return ThrowException(Exception::Error(msg));
        }
        if (!ContextifyContext::InstanceOf(args[0]->ToObject())) {
            Local<String> msg = String::New("First argument must be a ContextifyContext.");
            return ThrowException(Exception::TypeError(msg));
        }
        ContextifyContext* ctx = ObjectWrap::Unwrap<ContextifyContext>(args[0]->ToObject());
        Persistent<Context> context = ctx->context;
        context->Enter();
        ContextifyScript* wrapped_script = ObjectWrap::Unwrap<ContextifyScript>(args.This());
        Handle<Script> script = wrapped_script->script;
        TryCatch trycatch;
        if (script.IsEmpty()) {
          context->Exit();
          return trycatch.ReThrow();
        }
        Handle<Value> result = script->Run();
        context->Exit();
        if (result.IsEmpty()) {
            return trycatch.ReThrow();
        }
        return scope.Close(result);
    }

    ~ContextifyScript() {
        script.Dispose();
    }
};

Persistent<FunctionTemplate> ContextifyContext::jsTmpl;
Persistent<FunctionTemplate> ContextifyScript::scriptTmpl;

extern "C" {
    static void init(Handle<Object> target) {
        ContextifyContext::Init(target);
        ContextifyScript::Init(target);
    }
    NODE_MODULE(contextify, init);
};
<commit_msg>Better way of checking for node version.<commit_after>#include "node.h"
#include "node_version.h"
#include <string>
using namespace v8;
using namespace node;

// For some reason this needs to be out of the object or node won't load the
// library.
static Persistent<FunctionTemplate> dataWrapperTmpl;
static Persistent<Function>         dataWrapperCtor;

class ContextifyContext : ObjectWrap {
public:
    Persistent<Context> context;
    Persistent<Object>  sandbox;
    Persistent<Object>  proxyGlobal;

    static Persistent<FunctionTemplate> jsTmpl;

    ContextifyContext(Local<Object> sbox) {
        HandleScope scope;
        #if NODE_VERSION_AT_LEAST(0, 11, 3)
            sandbox = Persistent<Object>::New(Isolate::GetCurrent(), sbox);
        #else
            sandbox = Persistent<Object>::New(sbox);
        #endif
    }

    ~ContextifyContext() {
        context.Dispose();
        context.Clear();
        proxyGlobal.Dispose();
        proxyGlobal.Clear();
        sandbox.Dispose();
        sandbox.Clear();
    }

    // We override ObjectWrap::Wrap so that we can create our context after
    // we have a reference to our "host" JavaScript object.  If we try to use
    // handle_ in the ContextifyContext constructor, it will be empty since it's
    // set in ObjectWrap::Wrap.
    inline void Wrap(Handle<Object> handle) {
        ObjectWrap::Wrap(handle);
        context     = createV8Context();
        #if NODE_VERSION_AT_LEAST(0, 11, 3)
            proxyGlobal = Persistent<Object>::New(Isolate::GetCurrent(), context->Global());
        #else
            proxyGlobal = Persistent<Object>::New(context->Global());
        #endif
    }

    // This is an object that just keeps an internal pointer to this
    // ContextifyContext.  It's passed to the NamedPropertyHandler.  If we
    // pass the main JavaScript context object we're embedded in, then the
    // NamedPropertyHandler will store a reference to it forever and keep it
    // from getting gc'd.
    Local<Object> createDataWrapper () {
        HandleScope scope;
        Local<Object> wrapper = dataWrapperCtor->NewInstance();
#if NODE_MAJOR_VERSION > 0 || (NODE_MINOR_VERSION == 9 && (NODE_PATCH_VERSION >= 6 && NODE_PATCH_VERSION <= 10)) || NODE_MINOR_VERSION >= 11
        wrapper->SetAlignedPointerInInternalField(0, this);
#else
        wrapper->SetPointerInInternalField(0, this);
#endif
        return scope.Close(wrapper);
    }

    Persistent<Context> createV8Context() {
        HandleScope scope;
        Local<FunctionTemplate> ftmpl = FunctionTemplate::New();
        ftmpl->SetHiddenPrototype(true);
        ftmpl->SetClassName(sandbox->GetConstructorName());
        Local<ObjectTemplate> otmpl = ftmpl->InstanceTemplate();
        otmpl->SetNamedPropertyHandler(GlobalPropertyGetter,
                                       GlobalPropertySetter,
                                       GlobalPropertyQuery,
                                       GlobalPropertyDeleter,
                                       GlobalPropertyEnumerator,
                                       createDataWrapper());
        otmpl->SetAccessCheckCallbacks(GlobalPropertyNamedAccessCheck,
                                       GlobalPropertyIndexedAccessCheck);
        #if NODE_VERSION_AT_LEAST(0, 11, 3)
            return Persistent<Context>::New(Isolate::GetCurrent(), Context::New(Isolate::GetCurrent(), NULL, otmpl));
        #else
            return Context::New(NULL, otmpl);
        #endif
    }

    static void Init(Handle<Object> target) {
        HandleScope scope;
        #if NODE_VERSION_AT_LEAST(0, 11, 3)
            dataWrapperTmpl = Persistent<FunctionTemplate>::New(Isolate::GetCurrent(), FunctionTemplate::New());
        #else
            dataWrapperTmpl = Persistent<FunctionTemplate>::New(FunctionTemplate::New());
        #endif
        dataWrapperTmpl->InstanceTemplate()->SetInternalFieldCount(1);
        #if NODE_VERSION_AT_LEAST(0, 11, 3)
            dataWrapperCtor = Persistent<Function>::New(Isolate::GetCurrent(), dataWrapperTmpl->GetFunction());
        #else
            dataWrapperCtor = Persistent<Function>::New(dataWrapperTmpl->GetFunction());
        #endif

        #if NODE_VERSION_AT_LEAST(0, 11, 3)
            jsTmpl = Persistent<FunctionTemplate>::New(Isolate::GetCurrent(), FunctionTemplate::New(New));
        #else
            jsTmpl = Persistent<FunctionTemplate>::New(FunctionTemplate::New(New));
        #endif
        jsTmpl->InstanceTemplate()->SetInternalFieldCount(1);
        jsTmpl->SetClassName(String::NewSymbol("ContextifyContext"));

        NODE_SET_PROTOTYPE_METHOD(jsTmpl, "run",       ContextifyContext::Run);
        NODE_SET_PROTOTYPE_METHOD(jsTmpl, "getGlobal", ContextifyContext::GetGlobal);

        target->Set(String::NewSymbol("ContextifyContext"), jsTmpl->GetFunction());
    }

    // args[0] = the sandbox object
    static Handle<Value> New(const Arguments& args) {
        HandleScope scope;
        if (args.Length() < 1) {
            Local<String> msg = String::New("Wrong number of arguments passed to ContextifyContext constructor");
            return ThrowException(Exception::Error(msg));
        }
        if (!args[0]->IsObject()) {
            Local<String> msg = String::New("Argument to ContextifyContext constructor must be an object.");
            return ThrowException(Exception::Error(msg));
        }
        ContextifyContext* ctx = new ContextifyContext(args[0]->ToObject());
        ctx->Wrap(args.This());
        return args.This();
    }

    static Handle<Value> Run(const Arguments& args) {
        HandleScope scope;
        if (args.Length() == 0) {
            Local<String> msg = String::New("Must supply at least 1 argument to run");
            return ThrowException(Exception::Error(msg));
        }
        if (!args[0]->IsString()) {
            Local<String> msg = String::New("First argument to run must be a String.");
            return ThrowException(Exception::Error(msg));
        }
        ContextifyContext* ctx = ObjectWrap::Unwrap<ContextifyContext>(args.This());
        Persistent<Context> context = ctx->context;
        context->Enter();
        Local<String> code = args[0]->ToString();
        TryCatch trycatch;
        Handle<Script> script;
        if (args.Length() > 1 && args[1]->IsString()) {
            script = Script::Compile(code, args[1]->ToString());
        } else {
            script = Script::Compile(code);
        }
        if (script.IsEmpty()) {
          context->Exit();
          return trycatch.ReThrow();
        }
        Handle<Value> result = script->Run();
        context->Exit();
        if (result.IsEmpty()) {
            return trycatch.ReThrow();
        }
        return scope.Close(result);
    }

    static bool InstanceOf(Handle<Value> value) {
      return !value.IsEmpty() && jsTmpl->HasInstance(value);
    }

    static Handle<Value> GetGlobal(const Arguments& args) {
        HandleScope scope;
        ContextifyContext* ctx = ObjectWrap::Unwrap<ContextifyContext>(args.This());
        return ctx->proxyGlobal;
    }

    static bool GlobalPropertyNamedAccessCheck(Local<Object> host,
                                               Local<Value>  key,
                                               AccessType    type,
                                               Local<Value>  data) {
        return true;
    }

    static bool GlobalPropertyIndexedAccessCheck(Local<Object> host,
                                                 uint32_t      key,
                                                 AccessType    type,
                                                 Local<Value>  data) {
        return true;
    }

    static Handle<Value> GlobalPropertyGetter (Local<String> property,
                                               const AccessorInfo &accessInfo) {
        HandleScope scope;
        Local<Object> data = accessInfo.Data()->ToObject();
        ContextifyContext* ctx = ObjectWrap::Unwrap<ContextifyContext>(data);
        Local<Value> rv = ctx->sandbox->GetRealNamedProperty(property);
        if (rv.IsEmpty()) {
            rv = ctx->proxyGlobal->GetRealNamedProperty(property);
        }
        return scope.Close(rv);
    }

    static Handle<Value> GlobalPropertySetter (Local<String> property,
                                               Local<Value> value,
                                               const AccessorInfo &accessInfo) {
        HandleScope scope;
        Local<Object> data = accessInfo.Data()->ToObject();
        ContextifyContext* ctx = ObjectWrap::Unwrap<ContextifyContext>(data);
        ctx->sandbox->Set(property, value);
        return scope.Close(value);
    }

    static Handle<Integer> GlobalPropertyQuery(Local<String> property,
                                               const AccessorInfo &accessInfo) {
        HandleScope scope;
        Local<Object> data = accessInfo.Data()->ToObject();
        ContextifyContext* ctx = ObjectWrap::Unwrap<ContextifyContext>(data);
        if (!ctx->sandbox->GetRealNamedProperty(property).IsEmpty() ||
            !ctx->proxyGlobal->GetRealNamedProperty(property).IsEmpty()) {
            return scope.Close(Integer::New(None));
        }
        return scope.Close(Handle<Integer>());
    }

    static Handle<Boolean> GlobalPropertyDeleter(Local<String> property,
                                                 const AccessorInfo &accessInfo) {
        HandleScope scope;
        Local<Object> data = accessInfo.Data()->ToObject();
        ContextifyContext* ctx = ObjectWrap::Unwrap<ContextifyContext>(data);
        bool success = ctx->sandbox->Delete(property);
        if (!success) {
            success = ctx->proxyGlobal->Delete(property);
        }
        return scope.Close(Boolean::New(success));
    }

    static Handle<Array> GlobalPropertyEnumerator(const AccessorInfo &accessInfo) {
        HandleScope scope;
        Local<Object> data = accessInfo.Data()->ToObject();
        ContextifyContext* ctx = ObjectWrap::Unwrap<ContextifyContext>(data);
        return scope.Close(ctx->sandbox->GetPropertyNames());
    }
};

class ContextifyScript : ObjectWrap {
public:
    static Persistent<FunctionTemplate> scriptTmpl;
    Persistent<Script> script;

    static void Init(Handle<Object> target) {
        HandleScope scope;
        #if NODE_VERSION_AT_LEAST(0, 11, 3)
            scriptTmpl = Persistent<FunctionTemplate>::New(Isolate::GetCurrent(), FunctionTemplate::New(New));
        #else
            scriptTmpl = Persistent<FunctionTemplate>::New(FunctionTemplate::New(New));
        #endif
        scriptTmpl->InstanceTemplate()->SetInternalFieldCount(1);
        scriptTmpl->SetClassName(String::NewSymbol("ContextifyScript"));

        NODE_SET_PROTOTYPE_METHOD(scriptTmpl, "runInContext", RunInContext);

        target->Set(String::NewSymbol("ContextifyScript"),
                    scriptTmpl->GetFunction());
    }

    static Handle<Value> New(const Arguments& args) {
      HandleScope scope;

      ContextifyScript *contextify_script = new ContextifyScript();
      contextify_script->Wrap(args.Holder());

      if (args.Length() < 1) {
        return ThrowException(Exception::TypeError(
              String::New("needs at least 'code' argument.")));
      }

      Local<String> code = args[0]->ToString();
      Local<String> filename = args.Length() > 1
                               ? args[1]->ToString()
                               : String::New("ContextifyScript.<anonymous>");

      Handle<Context> context = Context::GetCurrent();
      Context::Scope context_scope(context);

      // Catch errors
      TryCatch trycatch;

      Handle<Script> v8_script = Script::New(code, filename);

      if (v8_script.IsEmpty()) {
        return trycatch.ReThrow();
      }

      #if NODE_VERSION_AT_LEAST(0, 11, 3)
          contextify_script->script = Persistent<Script>::New(Isolate::GetCurrent(), v8_script);
      #else
          contextify_script->script = Persistent<Script>::New(v8_script);
      #endif

      return args.This();
    }

    static Handle<Value> RunInContext(const Arguments& args) {
        HandleScope scope;
        if (args.Length() == 0) {
            Local<String> msg = String::New("Must supply at least 1 argument to runInContext");
            return ThrowException(Exception::Error(msg));
        }
        if (!ContextifyContext::InstanceOf(args[0]->ToObject())) {
            Local<String> msg = String::New("First argument must be a ContextifyContext.");
            return ThrowException(Exception::TypeError(msg));
        }
        ContextifyContext* ctx = ObjectWrap::Unwrap<ContextifyContext>(args[0]->ToObject());
        Persistent<Context> context = ctx->context;
        context->Enter();
        ContextifyScript* wrapped_script = ObjectWrap::Unwrap<ContextifyScript>(args.This());
        Handle<Script> script = wrapped_script->script;
        TryCatch trycatch;
        if (script.IsEmpty()) {
          context->Exit();
          return trycatch.ReThrow();
        }
        Handle<Value> result = script->Run();
        context->Exit();
        if (result.IsEmpty()) {
            return trycatch.ReThrow();
        }
        return scope.Close(result);
    }

    ~ContextifyScript() {
        script.Dispose();
    }
};

Persistent<FunctionTemplate> ContextifyContext::jsTmpl;
Persistent<FunctionTemplate> ContextifyScript::scriptTmpl;

extern "C" {
    static void init(Handle<Object> target) {
        ContextifyContext::Init(target);
        ContextifyScript::Init(target);
    }
    NODE_MODULE(contextify, init);
};
<|endoftext|>


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

#include <primitives/block.h>
#include <primitives/transaction.h>
#include <script/script.h>
#include <script/sign.h>
#include <serialize.h>
#include <streams.h>
#include <univalue.h>
#include <util/strencodings.h>
#include <version.h>

#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/algorithm/string/split.hpp>

#include <algorithm>

CScript ParseScript(const std::string& s)
{
    CScript result;

    static std::map<std::string, opcodetype> mapOpNames;

    if (mapOpNames.empty())
    {
        for (unsigned int op = 0; op <= MAX_OPCODE; op++)
        {
            // Allow OP_RESERVED to get into mapOpNames
            if (op < OP_NOP && op != OP_RESERVED)
                continue;

            const char* name = GetOpName(static_cast<opcodetype>(op));
            if (strcmp(name, "OP_UNKNOWN") == 0)
                continue;
            std::string strName(name);
            mapOpNames[strName] = static_cast<opcodetype>(op);
            // Convenience: OP_ADD and just ADD are both recognized:
            boost::algorithm::replace_first(strName, "OP_", "");
            mapOpNames[strName] = static_cast<opcodetype>(op);
        }
    }

    std::vector<std::string> words;
    boost::algorithm::split(words, s, boost::algorithm::is_any_of(" \t\n"), boost::algorithm::token_compress_on);

    for (std::vector<std::string>::const_iterator w = words.begin(); w != words.end(); ++w)
    {
        if (w->empty())
        {
            // Empty string, ignore. (boost::split given '' will return one word)
        }
        else if (std::all_of(w->begin(), w->end(), ::IsDigit) ||
            (w->front() == '-' && w->size() > 1 && std::all_of(w->begin()+1, w->end(), ::IsDigit)))
        {
            // Number
            int64_t n = atoi64(*w);
            result << n;
        }
        else if (w->substr(0,2) == "0x" && w->size() > 2 && IsHex(std::string(w->begin()+2, w->end())))
        {
            // Raw hex data, inserted NOT pushed onto stack:
            std::vector<unsigned char> raw = ParseHex(std::string(w->begin()+2, w->end()));
            result.insert(result.end(), raw.begin(), raw.end());
        }
        else if (w->size() >= 2 && w->front() == '\'' && w->back() == '\'')
        {
            // Single-quoted string, pushed as data. NOTE: this is poor-man's
            // parsing, spaces/tabs/newlines in single-quoted strings won't work.
            std::vector<unsigned char> value(w->begin()+1, w->end()-1);
            result << value;
        }
        else if (mapOpNames.count(*w))
        {
            // opcode, e.g. OP_ADD or ADD:
            result << mapOpNames[*w];
        }
        else
        {
            throw std::runtime_error("script parse error");
        }
    }

    return result;
}

// Check that all of the input and output scripts of a transaction contains valid opcodes
static bool CheckTxScriptsSanity(const CMutableTransaction& tx)
{
    // Check input scripts for non-coinbase txs
    if (!CTransaction(tx).IsCoinBase()) {
        for (unsigned int i = 0; i < tx.vin.size(); i++) {
            if (!tx.vin[i].scriptSig.HasValidOps() || tx.vin[i].scriptSig.size() > MAX_SCRIPT_SIZE) {
                return false;
            }
        }
    }
    // Check output scripts
    for (unsigned int i = 0; i < tx.vout.size(); i++) {
        if (!tx.vout[i].scriptPubKey.HasValidOps() || tx.vout[i].scriptPubKey.size() > MAX_SCRIPT_SIZE) {
            return false;
        }
    }

    return true;
}

bool DecodeHexTx(CMutableTransaction& tx, const std::string& hex_tx, bool try_no_witness, bool try_witness)
{
    if (!IsHex(hex_tx)) {
        return false;
    }

    std::vector<unsigned char> txData(ParseHex(hex_tx));

    if (try_no_witness) {
        CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS);
        try {
            ssData >> tx;
            if (ssData.eof() && (!try_witness || CheckTxScriptsSanity(tx))) {
                return true;
            }
        } catch (const std::exception&) {
            // Fall through.
        }
    }

    if (try_witness) {
        CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
        try {
            ssData >> tx;
            if (ssData.empty()) {
                return true;
            }
        } catch (const std::exception&) {
            // Fall through.
        }
    }

    return false;
}

bool DecodeHexBlockHeader(CBlockHeader& header, const std::string& hex_header)
{
    if (!IsHex(hex_header)) return false;

    const std::vector<unsigned char> header_data{ParseHex(hex_header)};
    CDataStream ser_header(header_data, SER_NETWORK, PROTOCOL_VERSION);
    try {
        ser_header >> header;
    } catch (const std::exception&) {
        return false;
    }
    return true;
}

bool DecodeHexBlk(CBlock& block, const std::string& strHexBlk)
{
    if (!IsHex(strHexBlk))
        return false;

    std::vector<unsigned char> blockData(ParseHex(strHexBlk));
    CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
    try {
        ssBlock >> block;
    }
    catch (const std::exception&) {
        return false;
    }

    return true;
}

bool ParseHashStr(const std::string& strHex, uint256& result)
{
    if ((strHex.size() != 64) || !IsHex(strHex))
        return false;

    result.SetHex(strHex);
    return true;
}

std::vector<unsigned char> ParseHexUV(const UniValue& v, const std::string& strName)
{
    std::string strHex;
    if (v.isStr())
        strHex = v.getValStr();
    if (!IsHex(strHex))
        throw std::runtime_error(strName + " must be hexadecimal string (not '" + strHex + "')");
    return ParseHex(strHex);
}

int ParseSighashString(const UniValue& sighash)
{
    int hash_type = SIGHASH_ALL;
    if (!sighash.isNull()) {
        static std::map<std::string, int> map_sighash_values = {
            {std::string("ALL"), int(SIGHASH_ALL)},
            {std::string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY)},
            {std::string("NONE"), int(SIGHASH_NONE)},
            {std::string("NONE|ANYONECANPAY"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY)},
            {std::string("SINGLE"), int(SIGHASH_SINGLE)},
            {std::string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY)},
        };
        std::string strHashType = sighash.get_str();
        const auto& it = map_sighash_values.find(strHashType);
        if (it != map_sighash_values.end()) {
            hash_type = it->second;
        } else {
            throw std::runtime_error(strHashType + " is not a valid sighash parameter.");
        }
    }
    return hash_type;
}
<commit_msg>Include core_io.h from core_read.cpp<commit_after>// Copyright (c) 2009-2018 The Syscoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <core_io.h>

#include <primitives/block.h>
#include <primitives/transaction.h>
#include <script/script.h>
#include <script/sign.h>
#include <serialize.h>
#include <streams.h>
#include <univalue.h>
#include <util/strencodings.h>
#include <version.h>

#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/algorithm/string/split.hpp>

#include <algorithm>

CScript ParseScript(const std::string& s)
{
    CScript result;

    static std::map<std::string, opcodetype> mapOpNames;

    if (mapOpNames.empty())
    {
        for (unsigned int op = 0; op <= MAX_OPCODE; op++)
        {
            // Allow OP_RESERVED to get into mapOpNames
            if (op < OP_NOP && op != OP_RESERVED)
                continue;

            const char* name = GetOpName(static_cast<opcodetype>(op));
            if (strcmp(name, "OP_UNKNOWN") == 0)
                continue;
            std::string strName(name);
            mapOpNames[strName] = static_cast<opcodetype>(op);
            // Convenience: OP_ADD and just ADD are both recognized:
            boost::algorithm::replace_first(strName, "OP_", "");
            mapOpNames[strName] = static_cast<opcodetype>(op);
        }
    }

    std::vector<std::string> words;
    boost::algorithm::split(words, s, boost::algorithm::is_any_of(" \t\n"), boost::algorithm::token_compress_on);

    for (std::vector<std::string>::const_iterator w = words.begin(); w != words.end(); ++w)
    {
        if (w->empty())
        {
            // Empty string, ignore. (boost::split given '' will return one word)
        }
        else if (std::all_of(w->begin(), w->end(), ::IsDigit) ||
            (w->front() == '-' && w->size() > 1 && std::all_of(w->begin()+1, w->end(), ::IsDigit)))
        {
            // Number
            int64_t n = atoi64(*w);
            result << n;
        }
        else if (w->substr(0,2) == "0x" && w->size() > 2 && IsHex(std::string(w->begin()+2, w->end())))
        {
            // Raw hex data, inserted NOT pushed onto stack:
            std::vector<unsigned char> raw = ParseHex(std::string(w->begin()+2, w->end()));
            result.insert(result.end(), raw.begin(), raw.end());
        }
        else if (w->size() >= 2 && w->front() == '\'' && w->back() == '\'')
        {
            // Single-quoted string, pushed as data. NOTE: this is poor-man's
            // parsing, spaces/tabs/newlines in single-quoted strings won't work.
            std::vector<unsigned char> value(w->begin()+1, w->end()-1);
            result << value;
        }
        else if (mapOpNames.count(*w))
        {
            // opcode, e.g. OP_ADD or ADD:
            result << mapOpNames[*w];
        }
        else
        {
            throw std::runtime_error("script parse error");
        }
    }

    return result;
}

// Check that all of the input and output scripts of a transaction contains valid opcodes
static bool CheckTxScriptsSanity(const CMutableTransaction& tx)
{
    // Check input scripts for non-coinbase txs
    if (!CTransaction(tx).IsCoinBase()) {
        for (unsigned int i = 0; i < tx.vin.size(); i++) {
            if (!tx.vin[i].scriptSig.HasValidOps() || tx.vin[i].scriptSig.size() > MAX_SCRIPT_SIZE) {
                return false;
            }
        }
    }
    // Check output scripts
    for (unsigned int i = 0; i < tx.vout.size(); i++) {
        if (!tx.vout[i].scriptPubKey.HasValidOps() || tx.vout[i].scriptPubKey.size() > MAX_SCRIPT_SIZE) {
            return false;
        }
    }

    return true;
}

bool DecodeHexTx(CMutableTransaction& tx, const std::string& hex_tx, bool try_no_witness, bool try_witness)
{
    if (!IsHex(hex_tx)) {
        return false;
    }

    std::vector<unsigned char> txData(ParseHex(hex_tx));

    if (try_no_witness) {
        CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS);
        try {
            ssData >> tx;
            if (ssData.eof() && (!try_witness || CheckTxScriptsSanity(tx))) {
                return true;
            }
        } catch (const std::exception&) {
            // Fall through.
        }
    }

    if (try_witness) {
        CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
        try {
            ssData >> tx;
            if (ssData.empty()) {
                return true;
            }
        } catch (const std::exception&) {
            // Fall through.
        }
    }

    return false;
}

bool DecodeHexBlockHeader(CBlockHeader& header, const std::string& hex_header)
{
    if (!IsHex(hex_header)) return false;

    const std::vector<unsigned char> header_data{ParseHex(hex_header)};
    CDataStream ser_header(header_data, SER_NETWORK, PROTOCOL_VERSION);
    try {
        ser_header >> header;
    } catch (const std::exception&) {
        return false;
    }
    return true;
}

bool DecodeHexBlk(CBlock& block, const std::string& strHexBlk)
{
    if (!IsHex(strHexBlk))
        return false;

    std::vector<unsigned char> blockData(ParseHex(strHexBlk));
    CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
    try {
        ssBlock >> block;
    }
    catch (const std::exception&) {
        return false;
    }

    return true;
}

bool ParseHashStr(const std::string& strHex, uint256& result)
{
    if ((strHex.size() != 64) || !IsHex(strHex))
        return false;

    result.SetHex(strHex);
    return true;
}

std::vector<unsigned char> ParseHexUV(const UniValue& v, const std::string& strName)
{
    std::string strHex;
    if (v.isStr())
        strHex = v.getValStr();
    if (!IsHex(strHex))
        throw std::runtime_error(strName + " must be hexadecimal string (not '" + strHex + "')");
    return ParseHex(strHex);
}

int ParseSighashString(const UniValue& sighash)
{
    int hash_type = SIGHASH_ALL;
    if (!sighash.isNull()) {
        static std::map<std::string, int> map_sighash_values = {
            {std::string("ALL"), int(SIGHASH_ALL)},
            {std::string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY)},
            {std::string("NONE"), int(SIGHASH_NONE)},
            {std::string("NONE|ANYONECANPAY"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY)},
            {std::string("SINGLE"), int(SIGHASH_SINGLE)},
            {std::string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY)},
        };
        std::string strHashType = sighash.get_str();
        const auto& it = map_sighash_values.find(strHashType);
        if (it != map_sighash_values.end()) {
            hash_type = it->second;
        } else {
            throw std::runtime_error(strHashType + " is not a valid sighash parameter.");
        }
    }
    return hash_type;
}
<|endoftext|>


<commit_before>#include "settings.h"
#include "ui_settings.h"

#include <QDebug>

Settings::Settings(QWidget *parent) :
  QDialog(parent),
  ui(new Ui::Settings)
{
  ui->setupUi(this);
  restoreSettings(); // initializes the GUI with values
}

Settings::~Settings()
{
  delete ui;
}

void Settings::on_ok_clicked()
{
  qDebug() << "Settings have been modified";
  saveSettings();
  emit settingsChanged();
  hide();
}

void Settings::on_cancel_clicked()
{
  qDebug() << "Getting settings from system";
  restoreSettings();
  hide();
}

// temparily records the settings
void Settings::saveSettings()
{
  // Local settings
  QSettings settings;
  if(ui->name_edit->text() != "")
    settings.setValue("local/Name",         ui->name_edit->text());
  if(ui->username_edit->text() != "")
    settings.setValue("local/Username",     ui->username_edit->text());

  // Video settings
  settings.setValue("video/Preset",       ui->preset->currentText());

  if(ui->scaled_height->text() != "")
    settings.setValue("video/ScaledHeight", ui->scaled_height->text());
  if(ui->scaled_width->text() != "")
    settings.setValue("video/ScaledWidth",  ui->scaled_width->text());
  if(ui->threads->text() != "")
    settings.setValue("video/Threads",      ui->threads->text());

  settings.setValue("video/QP",             QString::number(ui->qp->value()));

  if(ui->wpp->isChecked())
    settings.setValue("video/WPP",          "1");
  else
    settings.setValue("video/WPP",          "0");

  if(ui->vps->text() != "")
    settings.setValue("video/VPS",          ui->vps->text());
  if(ui->intra->text() != "")
    settings.setValue("video/Intra",        ui->intra->text());

  //settings.sync(); // TODO is this needed?
}

// restores temporarily recorded settings
void Settings::restoreSettings()
{
  QSettings settings;
  bool missingSettings = false;

  QStringList list = settings.allKeys();

  for(auto key : list)
  {
    qDebug() << "Found settings key:" << key << "value:" << settings.value(key).toString();
    if(!missingSettings && settings.value(key).isNull())
      missingSettings = true;
  }

  if(list.size() < 11) // Remember to update this value
    missingSettings = true;

  //get values from QSettings
  if(!missingSettings)
  {
    qDebug() << "Restoring previous settings";
    ui->name_edit->setText      (settings.value("local/Name").toString());
    ui->username_edit->setText  (settings.value("local/Username").toString());

    int index = ui->preset->findText(settings.value("video/Preset").toString());
    if(index != -1)
      ui->preset->setCurrentIndex(index);
    ui->scaled_height->setText  (settings.value("video/ScaledHeight").toString());
    ui->scaled_width->setText   (settings.value("video/ScaledWidth").toString());
    ui->threads->setText        (settings.value("video/Threads").toString());
    ui->qp->setValue            (settings.value("video/QP").toInt());

    if(settings.value("video/WPP").toString() == "1")
      ui->wpp->setChecked(true);
    else if(settings.value("video/WPP").toString() == "0")
      ui->wpp->setChecked(false);
    ui->vps->setText            (settings.value("video/VPS").toString());
    ui->intra->setText          (settings.value("video/Intra").toString());
  }
  else
  {
    // Some settings have not been initialized (due to new settings). Use defaults in GUI
    qDebug() << "Resettings settings to defaults";
    saveSettings();
  }
}
<commit_msg>Settings is now correctly restored.<commit_after>#include "settings.h"
#include "ui_settings.h"

#include <QDebug>

const int SETTINGCOUNT = 10;

Settings::Settings(QWidget *parent) :
  QDialog(parent),
  ui(new Ui::Settings)
{
  ui->setupUi(this);
  restoreSettings(); // initializes the GUI with values
}

Settings::~Settings()
{
  delete ui;
}

void Settings::on_ok_clicked()
{
  qDebug() << "Settings have been modified";
  saveSettings();
  emit settingsChanged();
  hide();
}

void Settings::on_cancel_clicked()
{
  qDebug() << "Getting settings from system";
  restoreSettings();
  hide();
}

// temparily records the settings
void Settings::saveSettings()
{
  // Local settings
  QSettings settings;
  if(ui->name_edit->text() != "")
    settings.setValue("local/Name",         ui->name_edit->text());
  if(ui->username_edit->text() != "")
    settings.setValue("local/Username",     ui->username_edit->text());

  // Video settings
  settings.setValue("video/Preset",       ui->preset->currentText());

  if(ui->scaled_height->text() != "")
    settings.setValue("video/ScaledHeight", ui->scaled_height->text());
  if(ui->scaled_width->text() != "")
    settings.setValue("video/ScaledWidth",  ui->scaled_width->text());
  if(ui->threads->text() != "")
    settings.setValue("video/Threads",      ui->threads->text());

  settings.setValue("video/QP",             QString::number(ui->qp->value()));

  if(ui->wpp->isChecked())
    settings.setValue("video/WPP",          "1");
  else
    settings.setValue("video/WPP",          "0");

  if(ui->vps->text() != "")
    settings.setValue("video/VPS",          ui->vps->text());
  if(ui->intra->text() != "")
    settings.setValue("video/Intra",        ui->intra->text());

  //settings.sync(); // TODO is this needed?
}

// restores temporarily recorded settings
void Settings::restoreSettings()
{
  QSettings settings;
  bool missingSettings = false;

  QStringList list = settings.allKeys();

  for(auto key : list)
  {
    qDebug() << "Found settings key:" << key << "value:" << settings.value(key).toString();
    if(!missingSettings && settings.value(key).isNull())
      missingSettings = true;
  }

  if(list.size() < SETTINGCOUNT) // Remember to update this value
  {
    qDebug() << "Settings found:" << list.size() << "Expected:" << SETTINGCOUNT;
    missingSettings = true;
  }

  //get values from QSettings
  if(!missingSettings)
  {
    qDebug() << "Restoring previous settings";
    ui->name_edit->setText      (settings.value("local/Name").toString());
    ui->username_edit->setText  (settings.value("local/Username").toString());

    int index = ui->preset->findText(settings.value("video/Preset").toString());
    if(index != -1)
      ui->preset->setCurrentIndex(index);
    ui->scaled_height->setText  (settings.value("video/ScaledHeight").toString());
    ui->scaled_width->setText   (settings.value("video/ScaledWidth").toString());
    ui->threads->setText        (settings.value("video/Threads").toString());
    ui->qp->setValue            (settings.value("video/QP").toInt());

    if(settings.value("video/WPP").toString() == "1")
      ui->wpp->setChecked(true);
    else if(settings.value("video/WPP").toString() == "0")
      ui->wpp->setChecked(false);
    ui->vps->setText            (settings.value("video/VPS").toString());
    ui->intra->setText          (settings.value("video/Intra").toString());
  }
  else
  {
    // Some settings have not been initialized (due to new settings). Use defaults in GUI
    qDebug() << "Resettings settings to defaults";
    saveSettings();
  }
}
<|endoftext|>


<commit_before>#include "cvm.h"

struct DabVM_debug
{
    DabVM &vm;
    DabVM_debug(DabVM &vm) : vm(vm)
    {
    }
    void print_registers();
    void print_classes();
    void print_functions();
    void print_constants();
    void print_stack();
};

void DabVM_debug::print_registers()
{
    fprintf(stderr, "IP = %p (%d) Frame = %d\n", (void *)vm.ip(), (int)vm.ip(),
            (int)vm.frame_position);
}

void DabVM_debug::print_classes()
{
    for (const auto &it : vm.classes)
    {
        fprintf(stderr, " - 0x%04x %s (super = 0x%04x)\n", it.first, it.second.name.c_str(),
                it.second.superclass_index);
        for (const auto &fin : it.second.static_functions)
        {
            fprintf(stderr, "   ::%s\n", fin.first.c_str());
        }
        for (const auto &fin : it.second.functions)
        {
            fprintf(stderr, "    .%s\n", fin.first.c_str());
        }
    }
}

void DabVM_debug::print_functions()
{
    for (auto it : vm.functions)
    {
        auto &fun = it.second;
        fprintf(stderr, " - %s: %s at %p\n", fun.name.c_str(), fun.regular ? "regular" : "extra",
                (void *)fun.address);
    }
}

void DabVM_debug::print_constants()
{
    vm._dump("constants", vm.constants);
}

void DabVM_debug::print_stack()
{
    vm._dump("stack", vm.stack._data);
}

void DabVM::execute_debug(Stream &input)
{
    DabVM_debug debug(*this);
    while (!input.eof())
    {
        char rawcmd[2048];
        fprintf(stderr, "> ");
        fgets(rawcmd, sizeof(rawcmd), stdin);
        std::string cmd = rawcmd;

        cmd = cmd.substr(0, cmd.length() - 1);

        if (cmd == "help")
        {
            fprintf(stderr, "Help:\n");
            fprintf(stderr, "help - print this\n");
            fprintf(stderr, "[s]tep - run single instruction\n");
            fprintf(stderr, "[r]egisters - show registers\n");
            fprintf(stderr, "classes - print classes\n");
            fprintf(stderr, "functions - print functions\n");
            fprintf(stderr, "constants - dump constants\n");
            fprintf(stderr, "stack - dump stack\n");
        }
        else if (cmd == "step" || cmd == "s")
        {
            execute_single(input);
        }
        else if (cmd == "registers" || cmd == "r")
        {
            debug.print_registers();
        }
        else if (cmd == "classes")
        {
            debug.print_classes();
        }
        else if (cmd == "functions")
        {
            debug.print_functions();
        }
        else if (cmd == "constants")
        {
            debug.print_constants();
        }
        else if (cmd == "stack")
        {
            debug.print_stack();
        }
        else if (cmd == "quit")
        {
            exit(0);
        }
        else
        {
            fprintf(stderr, "Unknown command, type <help> to get available commands.\n");
        }
    }
}
<commit_msg>vm/debug: print on stdout<commit_after>#include "cvm.h"

struct DabVM_debug
{
    DabVM &vm;
    DabVM_debug(DabVM &vm) : vm(vm)
    {
    }
    void print_registers();
    void print_classes();
    void print_functions();
    void print_constants();
    void print_stack();
};

void DabVM_debug::print_registers()
{
    fprintf(stderr, "IP = %p (%d) Frame = %d\n", (void *)vm.ip(), (int)vm.ip(),
            (int)vm.frame_position);
}

void DabVM_debug::print_classes()
{
    for (const auto &it : vm.classes)
    {
        fprintf(stderr, " - 0x%04x %s (super = 0x%04x)\n", it.first, it.second.name.c_str(),
                it.second.superclass_index);
        for (const auto &fin : it.second.static_functions)
        {
            fprintf(stderr, "   ::%s\n", fin.first.c_str());
        }
        for (const auto &fin : it.second.functions)
        {
            fprintf(stderr, "    .%s\n", fin.first.c_str());
        }
    }
}

void DabVM_debug::print_functions()
{
    for (auto it : vm.functions)
    {
        auto &fun = it.second;
        fprintf(stderr, " - %s: %s at %p\n", fun.name.c_str(), fun.regular ? "regular" : "extra",
                (void *)fun.address);
    }
}

void DabVM_debug::print_constants()
{
    vm._dump("constants", vm.constants);
}

void DabVM_debug::print_stack()
{
    vm._dump("stack", vm.stack._data);
}

void DabVM::execute_debug(Stream &input)
{
    auto err_stream = stdout;

    DabVM_debug debug(*this);
    while (!input.eof())
    {
        char rawcmd[2048];
        fprintf(stderr, "> ");
        fgets(rawcmd, sizeof(rawcmd), stdin);
        std::string cmd = rawcmd;

        cmd = cmd.substr(0, cmd.length() - 1);

        if (cmd == "help")
        {
            fprintf(err_stream, "Help:\n");
            fprintf(err_stream, "help - print this\n");
            fprintf(err_stream, "[s]tep - run single instruction\n");
            fprintf(err_stream, "[r]egisters - show registers\n");
            fprintf(err_stream, "classes - print classes\n");
            fprintf(err_stream, "functions - print functions\n");
            fprintf(err_stream, "constants - dump constants\n");
            fprintf(err_stream, "stack - dump stack\n");
            fprintf(err_stream, "quit - quit\n");
        }
        else if (cmd == "step" || cmd == "s")
        {
            execute_single(input);
        }
        else if (cmd == "registers" || cmd == "r")
        {
            debug.print_registers();
        }
        else if (cmd == "classes")
        {
            debug.print_classes();
        }
        else if (cmd == "functions")
        {
            debug.print_functions();
        }
        else if (cmd == "constants")
        {
            debug.print_constants();
        }
        else if (cmd == "stack")
        {
            debug.print_stack();
        }
        else if (cmd == "quit")
        {
            exit(0);
        }
        else
        {
            fprintf(stderr, "Unknown command, type <help> to get available commands.\n");
        }
    }
}
<|endoftext|>


<commit_before>#include <iostream>
#include <pqxx/pqxx>

using namespace std;
using namespace pqxx;

// clang++ update.cpp -o update -lpqxx -lpq

int main() {
   const char * sql;

   try {
      connection C("dbname=benchcare user=synod password= \
      hostaddr=127.0.0.1 port=5432");
      if (C.is_open()) {
         cout << "Opened database successfully: " << C.dbname() << endl;
      } else {
         cout << "Can't open database" << endl;
         return 1;
      }

      /* Create a transactional object. */
      work W(C);
      /* Create  SQL UPDATE statement */
      sql = "UPDATE COMPANY set SALARY = 25000.00 where ID=1";
      /* Execute SQL query */
      W.exec( sql );
      W.commit();
      cout << "Records updated successfully" << endl;

      /* Create SQL SELECT statement */
      sql = "SELECT * from COMPANY";

      /* Create a non-transactional object. */
      nontransaction N(C);

      /* Execute SQL query */
      result R( N.exec( sql ));

      /* List down all the records */
      for (result::const_iterator c = R.begin(); c != R.end(); ++c) {
         cout << "ID = " << c[0].as<int>() << endl;
         cout << "Name = " << c[1].as<string>() << endl;
         cout << "Age = " << c[2].as<int>() << endl;
         cout << "Address = " << c[3].as<string>() << endl;
         cout << "Salary = " << c[4].as<float>() << endl;
      }
      cout << "Operation done successfully" << endl;
      C.disconnect ();
   } catch (const std::exception &e) {
      cerr << e.what() << std::endl;
      return 1;
   }

   return 0;
}
<commit_msg>update query<commit_after>#include <iostream>
#include <pqxx/pqxx>

using namespace std;
using namespace pqxx;

// clang++ update.cpp -o update -lpqxx -lpq

int main() {
   const char * sql;
   const char * class_recogn;

   try {
      connection C("dbname=recognise user=synod password= \
      hostaddr=127.0.0.1 port=5432");
      if (C.is_open()) {
         cout << "Opened database successfully: " << C.dbname() << endl;
      } else {
         cout << "Can't open database" << endl;
         return 1;
      }

      /* Create a transactional object. */
      work W(C);
      /* Create  SQL UPDATE statement */
      sql = "UPDATE COMPANY set SALARY = 25000.00 where ID=1";

      class_recogn = "UPDATE class_recogn SET classes_missed=4 where id_no=1";

      /* Execute SQL query */
      W.exec( class_recogn );
      W.commit();
      cout << "Records updated successfully" << endl;

      /* Create SQL SELECT statement */
      sql = "SELECT * from class_recogn";

      /* Create a non-transactional object. */
      nontransaction N(C);

      /* Execute SQL query */
      result R( N.exec( sql ));

      /* List down all the records */
      for (result::const_iterator c = R.begin(); c != R.end(); ++c) {
         cout << "id_no = " << c[0].as<int>() << endl;
         cout << "fname = " << c[1].as<string>() << endl;
         cout << "lname = " << c[2].as<string>() << endl;
         cout << "classes_missed = " << c[3].as<int>() << endl;
         cout << "dates_missed = " << c[4].as<string>() << endl;
         cout << "last_time = " << c[5].as<string>() << endl;
      }
      cout << "Operation done successfully" << endl;
      C.disconnect ();
   } catch (const std::exception &e) {
      cerr << e.what() << std::endl;
      return 1;
   }

   return 0;
}
<|endoftext|>


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

#include <dbwrapper.h>

#include <fs.h>
#include <util.h>
#include <random.h>

#include <leveldb/cache.h>
#include <leveldb/env.h>
#include <leveldb/filter_policy.h>
#include <memenv.h>
#include <stdint.h>
#include <algorithm>

class CBitcoinLevelDBLogger : public leveldb::Logger {
public:
    // This code is adapted from posix_logger.h, which is why it is using vsprintf.
    // Please do not do this in normal code
    void Logv(const char * format, va_list ap) override {
            if (!LogAcceptCategory(BCLog::LEVELDB)) {
                return;
            }
            char buffer[500];
            for (int iter = 0; iter < 2; iter++) {
                char* base;
                int bufsize;
                if (iter == 0) {
                    bufsize = sizeof(buffer);
                    base = buffer;
                }
                else {
                    bufsize = 30000;
                    base = new char[bufsize];
                }
                char* p = base;
                char* limit = base + bufsize;

                // Print the message
                if (p < limit) {
                    va_list backup_ap;
                    va_copy(backup_ap, ap);
                    // Do not use vsnprintf elsewhere in bitcoin source code, see above.
                    p += vsnprintf(p, limit - p, format, backup_ap);
                    va_end(backup_ap);
                }

                // Truncate to available space if necessary
                if (p >= limit) {
                    if (iter == 0) {
                        continue;       // Try again with larger buffer
                    }
                    else {
                        p = limit - 1;
                    }
                }

                // Add newline if necessary
                if (p == base || p[-1] != '\n') {
                    *p++ = '\n';
                }

                assert(p <= limit);
                base[std::min(bufsize - 1, (int)(p - base))] = '\0';
                LogPrintStr(base);
                if (base != buffer) {
                    delete[] base;
                }
                break;
            }
    }
};

static leveldb::Options GetOptions(size_t nCacheSize)
{
    leveldb::Options options;
    options.block_cache = leveldb::NewLRUCache(nCacheSize / 2);
    options.write_buffer_size = nCacheSize / 4; // up to two write buffers may be held in memory simultaneously
    options.filter_policy = leveldb::NewBloomFilterPolicy(10);
    options.compression = leveldb::kNoCompression;
    options.max_open_files = 64;
    options.info_log = new CBitcoinLevelDBLogger();
    if (leveldb::kMajorVersion > 1 || (leveldb::kMajorVersion == 1 && leveldb::kMinorVersion >= 16)) {
        // LevelDB versions before 1.16 consider short writes to be corruption. Only trigger error
        // on corruption in later versions.
        options.paranoid_checks = true;
    }
    return options;
}

CDBWrapper::CDBWrapper(const fs::path& path, size_t nCacheSize, bool fMemory, bool fWipe, bool obfuscate)
{
    penv = nullptr;
    readoptions.verify_checksums = true;
    iteroptions.verify_checksums = true;
    iteroptions.fill_cache = false;
    syncoptions.sync = true;
    options = GetOptions(nCacheSize);
    options.create_if_missing = true;
    if (fMemory) {
        penv = leveldb::NewMemEnv(leveldb::Env::Default());
        options.env = penv;
    } else {
        if (fWipe) {
            LogPrintf("Wiping LevelDB in %s\n", path.string());
            leveldb::Status result = leveldb::DestroyDB(path.string(), options);
            dbwrapper_private::HandleError(result);
        }
        TryCreateDirectories(path);
        LogPrintf("Opening LevelDB in %s\n", path.string());
    }
    leveldb::Status status = leveldb::DB::Open(options, path.string(), &pdb);
    dbwrapper_private::HandleError(status);
    LogPrintf("Opened LevelDB successfully\n");

    if (gArgs.GetBoolArg("-forcecompactdb", false)) {
        LogPrintf("Starting database compaction of %s\n", path.string());
        pdb->CompactRange(nullptr, nullptr);
        LogPrintf("Finished database compaction of %s\n", path.string());
    }

    // The base-case obfuscation key, which is a noop.
    obfuscate_key = std::vector<unsigned char>(OBFUSCATE_KEY_NUM_BYTES, '\000');

    bool key_exists = Read(OBFUSCATE_KEY_KEY, obfuscate_key);

    if (!key_exists && obfuscate && IsEmpty()) {
        // Initialize non-degenerate obfuscation if it won't upset
        // existing, non-obfuscated data.
        std::vector<unsigned char> new_key = CreateObfuscateKey();

        // Write `new_key` so we don't obfuscate the key with itself
        Write(OBFUSCATE_KEY_KEY, new_key);
        obfuscate_key = new_key;

        LogPrintf("Wrote new obfuscate key for %s: %s\n", path.string(), HexStr(obfuscate_key));
    }

    LogPrintf("Using obfuscation key for %s: %s\n", path.string(), HexStr(obfuscate_key));
}

CDBWrapper::~CDBWrapper()
{
    delete pdb;
    pdb = nullptr;
    delete options.filter_policy;
    options.filter_policy = nullptr;
    delete options.info_log;
    options.info_log = nullptr;
    delete options.block_cache;
    options.block_cache = nullptr;
    delete penv;
    options.env = nullptr;
}

bool CDBWrapper::WriteBatch(CDBBatch& batch, bool fSync)
{
    leveldb::Status status = pdb->Write(fSync ? syncoptions : writeoptions, &batch.batch);
    dbwrapper_private::HandleError(status);
    return true;
}

// Prefixed with null character to avoid collisions with other keys
//
// We must use a string constructor which specifies length so that we copy
// past the null-terminator.
const std::string CDBWrapper::OBFUSCATE_KEY_KEY("\000obfuscate_key", 14);

const unsigned int CDBWrapper::OBFUSCATE_KEY_NUM_BYTES = 8;

/**
 * Returns a string (consisting of 8 random bytes) suitable for use as an
 * obfuscating XOR key.
 */
std::vector<unsigned char> CDBWrapper::CreateObfuscateKey() const
{
    unsigned char buff[OBFUSCATE_KEY_NUM_BYTES];
    GetRandBytes(buff, OBFUSCATE_KEY_NUM_BYTES);
    return std::vector<unsigned char>(&buff[0], &buff[OBFUSCATE_KEY_NUM_BYTES]);

}

bool CDBWrapper::IsEmpty()
{
    std::unique_ptr<CDBIterator> it(NewIterator());
    it->SeekToFirst();
    return !(it->Valid());
}

CDBIterator::~CDBIterator() { delete piter; }
bool CDBIterator::Valid() const { return piter->Valid(); }
void CDBIterator::SeekToFirst() { piter->SeekToFirst(); }
void CDBIterator::Next() { piter->Next(); }

namespace dbwrapper_private {

void HandleError(const leveldb::Status& status)
{
    if (status.ok())
        return;
    LogPrintf("%s\n", status.ToString());
    if (status.IsCorruption())
        throw dbwrapper_error("Database corrupted");
    if (status.IsIOError())
        throw dbwrapper_error("Database I/O error");
    if (status.IsNotFound())
        throw dbwrapper_error("Database entry missing");
    throw dbwrapper_error("Unknown database error");
}

const std::vector<unsigned char>& GetObfuscateKey(const CDBWrapper &w)
{
    return w.obfuscate_key;
}

} // namespace dbwrapper_private
<commit_msg>Prefix leveldb debug logging<commit_after>// Copyright (c) 2012-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <dbwrapper.h>

#include <fs.h>
#include <util.h>
#include <random.h>

#include <leveldb/cache.h>
#include <leveldb/env.h>
#include <leveldb/filter_policy.h>
#include <memenv.h>
#include <stdint.h>
#include <algorithm>

class CBitcoinLevelDBLogger : public leveldb::Logger {
public:
    // This code is adapted from posix_logger.h, which is why it is using vsprintf.
    // Please do not do this in normal code
    void Logv(const char * format, va_list ap) override {
            if (!LogAcceptCategory(BCLog::LEVELDB)) {
                return;
            }
            char buffer[500];
            for (int iter = 0; iter < 2; iter++) {
                char* base;
                int bufsize;
                if (iter == 0) {
                    bufsize = sizeof(buffer);
                    base = buffer;
                }
                else {
                    bufsize = 30000;
                    base = new char[bufsize];
                }
                char* p = base;
                char* limit = base + bufsize;

                // Print the message
                if (p < limit) {
                    va_list backup_ap;
                    va_copy(backup_ap, ap);
                    // Do not use vsnprintf elsewhere in bitcoin source code, see above.
                    p += vsnprintf(p, limit - p, format, backup_ap);
                    va_end(backup_ap);
                }

                // Truncate to available space if necessary
                if (p >= limit) {
                    if (iter == 0) {
                        continue;       // Try again with larger buffer
                    }
                    else {
                        p = limit - 1;
                    }
                }

                // Add newline if necessary
                if (p == base || p[-1] != '\n') {
                    *p++ = '\n';
                }

                assert(p <= limit);
                base[std::min(bufsize - 1, (int)(p - base))] = '\0';
                LogPrintf("leveldb: %s", base);
                if (base != buffer) {
                    delete[] base;
                }
                break;
            }
    }
};

static leveldb::Options GetOptions(size_t nCacheSize)
{
    leveldb::Options options;
    options.block_cache = leveldb::NewLRUCache(nCacheSize / 2);
    options.write_buffer_size = nCacheSize / 4; // up to two write buffers may be held in memory simultaneously
    options.filter_policy = leveldb::NewBloomFilterPolicy(10);
    options.compression = leveldb::kNoCompression;
    options.max_open_files = 64;
    options.info_log = new CBitcoinLevelDBLogger();
    if (leveldb::kMajorVersion > 1 || (leveldb::kMajorVersion == 1 && leveldb::kMinorVersion >= 16)) {
        // LevelDB versions before 1.16 consider short writes to be corruption. Only trigger error
        // on corruption in later versions.
        options.paranoid_checks = true;
    }
    return options;
}

CDBWrapper::CDBWrapper(const fs::path& path, size_t nCacheSize, bool fMemory, bool fWipe, bool obfuscate)
{
    penv = nullptr;
    readoptions.verify_checksums = true;
    iteroptions.verify_checksums = true;
    iteroptions.fill_cache = false;
    syncoptions.sync = true;
    options = GetOptions(nCacheSize);
    options.create_if_missing = true;
    if (fMemory) {
        penv = leveldb::NewMemEnv(leveldb::Env::Default());
        options.env = penv;
    } else {
        if (fWipe) {
            LogPrintf("Wiping LevelDB in %s\n", path.string());
            leveldb::Status result = leveldb::DestroyDB(path.string(), options);
            dbwrapper_private::HandleError(result);
        }
        TryCreateDirectories(path);
        LogPrintf("Opening LevelDB in %s\n", path.string());
    }
    leveldb::Status status = leveldb::DB::Open(options, path.string(), &pdb);
    dbwrapper_private::HandleError(status);
    LogPrintf("Opened LevelDB successfully\n");

    if (gArgs.GetBoolArg("-forcecompactdb", false)) {
        LogPrintf("Starting database compaction of %s\n", path.string());
        pdb->CompactRange(nullptr, nullptr);
        LogPrintf("Finished database compaction of %s\n", path.string());
    }

    // The base-case obfuscation key, which is a noop.
    obfuscate_key = std::vector<unsigned char>(OBFUSCATE_KEY_NUM_BYTES, '\000');

    bool key_exists = Read(OBFUSCATE_KEY_KEY, obfuscate_key);

    if (!key_exists && obfuscate && IsEmpty()) {
        // Initialize non-degenerate obfuscation if it won't upset
        // existing, non-obfuscated data.
        std::vector<unsigned char> new_key = CreateObfuscateKey();

        // Write `new_key` so we don't obfuscate the key with itself
        Write(OBFUSCATE_KEY_KEY, new_key);
        obfuscate_key = new_key;

        LogPrintf("Wrote new obfuscate key for %s: %s\n", path.string(), HexStr(obfuscate_key));
    }

    LogPrintf("Using obfuscation key for %s: %s\n", path.string(), HexStr(obfuscate_key));
}

CDBWrapper::~CDBWrapper()
{
    delete pdb;
    pdb = nullptr;
    delete options.filter_policy;
    options.filter_policy = nullptr;
    delete options.info_log;
    options.info_log = nullptr;
    delete options.block_cache;
    options.block_cache = nullptr;
    delete penv;
    options.env = nullptr;
}

bool CDBWrapper::WriteBatch(CDBBatch& batch, bool fSync)
{
    leveldb::Status status = pdb->Write(fSync ? syncoptions : writeoptions, &batch.batch);
    dbwrapper_private::HandleError(status);
    return true;
}

// Prefixed with null character to avoid collisions with other keys
//
// We must use a string constructor which specifies length so that we copy
// past the null-terminator.
const std::string CDBWrapper::OBFUSCATE_KEY_KEY("\000obfuscate_key", 14);

const unsigned int CDBWrapper::OBFUSCATE_KEY_NUM_BYTES = 8;

/**
 * Returns a string (consisting of 8 random bytes) suitable for use as an
 * obfuscating XOR key.
 */
std::vector<unsigned char> CDBWrapper::CreateObfuscateKey() const
{
    unsigned char buff[OBFUSCATE_KEY_NUM_BYTES];
    GetRandBytes(buff, OBFUSCATE_KEY_NUM_BYTES);
    return std::vector<unsigned char>(&buff[0], &buff[OBFUSCATE_KEY_NUM_BYTES]);

}

bool CDBWrapper::IsEmpty()
{
    std::unique_ptr<CDBIterator> it(NewIterator());
    it->SeekToFirst();
    return !(it->Valid());
}

CDBIterator::~CDBIterator() { delete piter; }
bool CDBIterator::Valid() const { return piter->Valid(); }
void CDBIterator::SeekToFirst() { piter->SeekToFirst(); }
void CDBIterator::Next() { piter->Next(); }

namespace dbwrapper_private {

void HandleError(const leveldb::Status& status)
{
    if (status.ok())
        return;
    LogPrintf("%s\n", status.ToString());
    if (status.IsCorruption())
        throw dbwrapper_error("Database corrupted");
    if (status.IsIOError())
        throw dbwrapper_error("Database I/O error");
    if (status.IsNotFound())
        throw dbwrapper_error("Database entry missing");
    throw dbwrapper_error("Unknown database error");
}

const std::vector<unsigned char>& GetObfuscateKey(const CDBWrapper &w)
{
    return w.obfuscate_key;
}

} // namespace dbwrapper_private
<|endoftext|>