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

#include "checkpoints.h"

#include "main.h"
#include "uint256.h"

#include <stdint.h>

#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>

namespace Checkpoints
{
    typedef std::map<int64_t, uint320> MapCheckpoints;

    // How many times we expect transactions after the last checkpoint to
    // be slower. This number is a compromise, as it can't be accurate for
    // every system. When reindexing from a fast disk with a slow CPU, it
    // can be up to 20, while when downloading from a slow network with a
    // fast multicore CPU, it won't be much higher than 1.
    static const double SIGCHECK_VERIFICATION_FACTOR = 5.0;

    struct CCheckpointData {
        const MapCheckpoints *mapCheckpoints;
        int64_t nTimeLastCheckpoint;
        int64_t nTransactionsLastCheckpoint;
        double fTransactionsPerDay;
    };

    bool fEnabled = true;

    // What makes a good checkpoint block?
    // + Is surrounded by blocks with reasonable timestamps
    //   (no blocks before with a timestamp after, none after with
    //    timestamp before)
    // + Contains no strange transactions
    static MapCheckpoints mapCheckpoints =
        boost::assign::map_list_of
        (99, uint320("00000018CE97B434F8396CB989C61190BB72B8CD2A7352C48C91AEDB2E0F8AFCE8CDB7A59334E95B"))
        (5000, uint320("0000000BC13E7BCFC9CFB664D4EA05D6732F5FB49DED407DA33E45FE351A5BD3A81F003BFC2096AC"))
        (5098, uint320("0000000853574F2FEEEE8EE642C72D8E1A40DBDFAFD01CC1B8F23EE6EBC565B16EDFF9E336B0DA0F"))
        (5600, uint320("000000012A064B7393C4A6C6CCD71B52640804A5DD8ABE76FDE35AD12EF00D7FE3DCE691938535DD"))
        (5749, uint320("00000001DE53835FEFC5CE5327F18FC4B9A33BEBA538B37CACDBDCE7E100BD6E88809CD449F17B6B"))
        (5860, uint320("00000002561825F14E3818161AD74D3C6E3E2E26C53FA2A20DD10CE3208D5D5CC7BB73EE55ADE64D"))
        (5900, uint320("00000017EB2CD60A7D328340F4B37BC1A99B89D18BC09C3840B611FA1C701FD50271E54CBFD72E23"))
        (8600, uint320("0000000161808757702034BF82F3C8764FABF0EC6C1E4075C4F3081705225AF36F9B2E22B13A150F"))
        (9100, uint320("000000022CA3F85EAE7CC50023B7AF2FC460BFFC015E79F4CDE7E1931A02F38960889980A39CC889"))
        (50000, uint320("0000000474061A227E8B28D6386A576EA85A1403A6CF24A9A43A1307BDC6F0EDEEA5E57F7CCD75D1"))
        (100000, uint320("000000067F4B33EAA5A5E93F24828D263AB3A6ECC07F385EBCABC90C9C475382A81321612D0B0934"))
        ;
    static const CCheckpointData data = {
        &mapCheckpoints,
        0x14E98C8E6E0, // * UNIX timestamp of last checkpoint block
        263508,        // * total number of transactions between genesis and last checkpoint
                       //   (the tx=... number in the SetBestChain debug.log lines)
        10000.0        // * estimated number of transactions per day after checkpoint
    };

    static MapCheckpoints mapCheckpointsTestnet =
        boost::assign::map_list_of
        ( 0, uint320(0))
        ;
    static const CCheckpointData dataTestnet = {
        &mapCheckpointsTestnet,
        0x1488DDBA3EE,
        0,
        300.0
    };

    static MapCheckpoints mapCheckpointsRegtest =
        boost::assign::map_list_of
        ( 0, uint320(0))
        ;
    static const CCheckpointData dataRegtest = {
        &mapCheckpointsRegtest,
        0,
        0,
        0
    };

    const CCheckpointData &Checkpoints() {
        if (Params().NetworkID() == CChainParams::TESTNET) {
            return dataTestnet;
        }
        else if (Params().NetworkID() == CChainParams::MAIN) {
            return data;
        }
        else {
            return dataRegtest;
        }
    }

    bool CheckBlock(int64_t nHeight, const uint320& hash)
    {
        if (!fEnabled) {
            return true;
        }
        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
        if (i == checkpoints.end()) {
            return true;
        }
        return hash == i->second;
    }

    // Guess how far we are in the verification process at the given block index
    double GuessVerificationProgress(CBlockIndex *pindex, bool fSigchecks) {
        if (pindex == NULL) {
            return 0.0;
        }
        int64_t nNow = time(NULL);

        double fSigcheckVerificationFactor = fSigchecks ? SIGCHECK_VERIFICATION_FACTOR : 1.0;
        double fWorkBefore = 0.0; // Amount of work done before pindex
        double fWorkAfter = 0.0;  // Amount of work left after pindex (estimated)
        // Work is defined as: 1.0 per transaction before the last checkpoint, and
        // fSigcheckVerificationFactor per transaction after.

        const CCheckpointData &data = Checkpoints();

        if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) {
            double nCheapBefore = pindex->nChainTx;
            double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx;
            double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint/1000)/86400.0*data.fTransactionsPerDay;
            fWorkBefore = nCheapBefore;
            fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor;
        } else {
            double nCheapBefore = data.nTransactionsLastCheckpoint;
            double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint;
            double nExpensiveAfter = (nNow - pindex->nTxTime/1000)/86400.0*data.fTransactionsPerDay;
            fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor;
            fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor;
        }

        return fWorkBefore / (fWorkBefore + fWorkAfter);
    }

    int64_t GetTotalBlocksEstimate()
    {
        if (!fEnabled) {
            return 0;
        }
        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        return checkpoints.rbegin()->first;
    }

    CBlockIndex* GetLastCheckpoint(const std::map<uint320, CBlockIndex*>& mapBlockIndex)
    {
        if (!fEnabled) {
            return NULL;
        }
        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
        {
            const uint320& hash = i.second;
            std::map<uint320, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
            if (t != mapBlockIndex.end()) {
                return t->second;
            }
        }
        return NULL;
    }
}

namespace PIDCheckpoints
{
    typedef std::map<int64_t, CPID> MapPIDCheckpoints;

    struct CPIDCheckpointData {
        const MapPIDCheckpoints *mapPIDCheckpoints;
        int64_t nTimeLastCheckpoint;
    };

    bool fEnabled = true;

    static MapPIDCheckpoints mapPIDCheckpoints =
        boost::assign::map_list_of
        (0, CPID(180.0f, 1.0f, 0.05f, 0.1f))
        (5600, CPID(180.0f, 1.0f, 0.05f, 0.1f, 256.0f, 102.0f, 62.0f, 0, 5599, 108.30000305f, 0x2507ffff))
        (5700, CPID(180.0f, 1.0f, 0.05f, 0.1f, 256.0f, 102.0f, 62.0f, 0, 5699, 108.30000305f, 0x251751ff))
        (5800, CPID(180.0f, 1.0f, 0.05f, 0.1f, 256.0f, 102.0f, 62.0f, 0, 5799, 108.30000305f, 0x251995ff))
        (5900, CPID(180.0f, 1.0f, 0.05f, 0.1f, 256.0f, 102.0f, 62.0f, 0, 5899, 108.30000305f, 0x251a64ff))
        (8600, CPID(180.0f, 1.0f, 0.05f, 0.1f, 201.0f, -30.0f,-25.0f, 0, 8599, -25.75000000f, 0x2501aeff))
        (9100, CPID(180.0f, 1.0f, 0.05f, 0.1f, -41.000000f, -79.000000f, -44.000000f, 0, 9099, -76.85000610f, 0x25028aff))
        (50000, CPID(180.0f, 1.0f, 0.05f, 0.1f, -256.000000f, -54.000000f, -37.000000f, 0, 49999, -70.50000000f, 0x250493ff))
        (100000, CPID(180.0f, 1.0f, 0.05f, 0.1f, 79.000000f, 4.000000f, -9.000000f, 0, 99999, 5.14999962f, 0x251069ff))
        ;
    static const CPIDCheckpointData data = {
        &mapPIDCheckpoints,
        0x14C24DE7120, // * timestamp of last PID checkpoint
    };

    static MapPIDCheckpoints mapPIDCheckpointsTestnet =
        boost::assign::map_list_of
        (0, CPID(180.0f, 1.0f, 0.05f, 0.1f))
        ;
    static const CPIDCheckpointData dataTestnet = {
        &mapPIDCheckpointsTestnet,
        0x148d455b42a
    };

    static MapPIDCheckpoints mapPIDCheckpointsRegtest =
        boost::assign::map_list_of
        (0, CPID(180.0f, 1.0f, 0.05f, 0.1f))
        ;
    static const CPIDCheckpointData dataRegtest = {
        &mapPIDCheckpointsRegtest,
        0
    };

    const CPIDCheckpointData &PIDCheckpoints() {
        if (Params().NetworkID() == CChainParams::TESTNET) {
            return dataTestnet;
        }
        else if (Params().NetworkID() == CChainParams::MAIN) {
            return data;
        }
        else {
            return dataRegtest;
        }
    }

    int64_t PIDGetHeightLastCheckpoint()
    {
        if (!fEnabled) {
            return 0;
        }
        const MapPIDCheckpoints& PIDcheckpoints = *PIDCheckpoints().mapPIDCheckpoints;

        return PIDcheckpoints.rbegin()->first;
    }

    int64_t PIDGetTimeLastCheckpoint()
    {
        if (!fEnabled) {
            return 0;
        }
        const int64_t PIDcheckpointTime = PIDCheckpoints().nTimeLastCheckpoint;

        return PIDcheckpointTime;
    }

    const CPID* GetPIDCheckpoint(int64_t height)
    {
        if (!fEnabled) {
            return NULL;
        }
        const MapPIDCheckpoints& PIDcheckpoints = *PIDCheckpoints().mapPIDCheckpoints;

        BOOST_REVERSE_FOREACH(const MapPIDCheckpoints::value_type& i, PIDcheckpoints)
        {
            if (i.first <= height) {
                const CPID& PIDChkpoint = i.second;
                return &PIDChkpoint;
            }
        }
        return NULL;
    }

}
<commit_msg>Checkpoint at block 109500<commit_after>// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014 Kryptohash developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "checkpoints.h"

#include "main.h"
#include "uint256.h"

#include <stdint.h>

#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>

namespace Checkpoints
{
    typedef std::map<int64_t, uint320> MapCheckpoints;

    // How many times we expect transactions after the last checkpoint to
    // be slower. This number is a compromise, as it can't be accurate for
    // every system. When reindexing from a fast disk with a slow CPU, it
    // can be up to 20, while when downloading from a slow network with a
    // fast multicore CPU, it won't be much higher than 1.
    static const double SIGCHECK_VERIFICATION_FACTOR = 5.0;

    struct CCheckpointData {
        const MapCheckpoints *mapCheckpoints;
        int64_t nTimeLastCheckpoint;
        int64_t nTransactionsLastCheckpoint;
        double fTransactionsPerDay;
    };

    bool fEnabled = true;

    // What makes a good checkpoint block?
    // + Is surrounded by blocks with reasonable timestamps
    //   (no blocks before with a timestamp after, none after with
    //    timestamp before)
    // + Contains no strange transactions
    static MapCheckpoints mapCheckpoints =
        boost::assign::map_list_of
        (99, uint320("00000018CE97B434F8396CB989C61190BB72B8CD2A7352C48C91AEDB2E0F8AFCE8CDB7A59334E95B"))
        (5000, uint320("0000000BC13E7BCFC9CFB664D4EA05D6732F5FB49DED407DA33E45FE351A5BD3A81F003BFC2096AC"))
        (5098, uint320("0000000853574F2FEEEE8EE642C72D8E1A40DBDFAFD01CC1B8F23EE6EBC565B16EDFF9E336B0DA0F"))
        (5600, uint320("000000012A064B7393C4A6C6CCD71B52640804A5DD8ABE76FDE35AD12EF00D7FE3DCE691938535DD"))
        (5749, uint320("00000001DE53835FEFC5CE5327F18FC4B9A33BEBA538B37CACDBDCE7E100BD6E88809CD449F17B6B"))
        (5860, uint320("00000002561825F14E3818161AD74D3C6E3E2E26C53FA2A20DD10CE3208D5D5CC7BB73EE55ADE64D"))
        (5900, uint320("00000017EB2CD60A7D328340F4B37BC1A99B89D18BC09C3840B611FA1C701FD50271E54CBFD72E23"))
        (8600, uint320("0000000161808757702034BF82F3C8764FABF0EC6C1E4075C4F3081705225AF36F9B2E22B13A150F"))
        (9100, uint320("000000022CA3F85EAE7CC50023B7AF2FC460BFFC015E79F4CDE7E1931A02F38960889980A39CC889"))
        (50000, uint320("0000000474061A227E8B28D6386A576EA85A1403A6CF24A9A43A1307BDC6F0EDEEA5E57F7CCD75D1"))
        (100000, uint320("000000067F4B33EAA5A5E93F24828D263AB3A6ECC07F385EBCABC90C9C475382A81321612D0B0934"))
		(109500, uint320("0000000B857DBDDE81AAB910416F7DF2B7AA1588B87A05A3FE3DEA6FF68433A55F13ED7265EA87FE"))
		;
    static const CCheckpointData data = {
        &mapCheckpoints,
		0x14F11D83C20, // * UNIX timestamp of last checkpoint block
		297091,        // * total number of transactions between genesis and last checkpoint
                       //   (the tx=... number in the SetBestChain debug.log lines)
        10000.0        // * estimated number of transactions per day after checkpoint
    };

    static MapCheckpoints mapCheckpointsTestnet =
        boost::assign::map_list_of
        ( 0, uint320(0))
        ;
    static const CCheckpointData dataTestnet = {
        &mapCheckpointsTestnet,
        0x1488DDBA3EE,
        0,
        300.0
    };

    static MapCheckpoints mapCheckpointsRegtest =
        boost::assign::map_list_of
        ( 0, uint320(0))
        ;
    static const CCheckpointData dataRegtest = {
        &mapCheckpointsRegtest,
        0,
        0,
        0
    };

    const CCheckpointData &Checkpoints() {
        if (Params().NetworkID() == CChainParams::TESTNET) {
            return dataTestnet;
        }
        else if (Params().NetworkID() == CChainParams::MAIN) {
            return data;
        }
        else {
            return dataRegtest;
        }
    }

    bool CheckBlock(int64_t nHeight, const uint320& hash)
    {
        if (!fEnabled) {
            return true;
        }
        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
        if (i == checkpoints.end()) {
            return true;
        }
        return hash == i->second;
    }

    // Guess how far we are in the verification process at the given block index
    double GuessVerificationProgress(CBlockIndex *pindex, bool fSigchecks) {
        if (pindex == NULL) {
            return 0.0;
        }
        int64_t nNow = time(NULL);

        double fSigcheckVerificationFactor = fSigchecks ? SIGCHECK_VERIFICATION_FACTOR : 1.0;
        double fWorkBefore = 0.0; // Amount of work done before pindex
        double fWorkAfter = 0.0;  // Amount of work left after pindex (estimated)
        // Work is defined as: 1.0 per transaction before the last checkpoint, and
        // fSigcheckVerificationFactor per transaction after.

        const CCheckpointData &data = Checkpoints();

        if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) {
            double nCheapBefore = pindex->nChainTx;
            double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx;
            double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint/1000)/86400.0*data.fTransactionsPerDay;
            fWorkBefore = nCheapBefore;
            fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor;
        } else {
            double nCheapBefore = data.nTransactionsLastCheckpoint;
            double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint;
            double nExpensiveAfter = (nNow - pindex->nTxTime/1000)/86400.0*data.fTransactionsPerDay;
            fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor;
            fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor;
        }

        return fWorkBefore / (fWorkBefore + fWorkAfter);
    }

    int64_t GetTotalBlocksEstimate()
    {
        if (!fEnabled) {
            return 0;
        }
        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        return checkpoints.rbegin()->first;
    }

    CBlockIndex* GetLastCheckpoint(const std::map<uint320, CBlockIndex*>& mapBlockIndex)
    {
        if (!fEnabled) {
            return NULL;
        }
        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
        {
            const uint320& hash = i.second;
            std::map<uint320, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
            if (t != mapBlockIndex.end()) {
                return t->second;
            }
        }
        return NULL;
    }
}

namespace PIDCheckpoints
{
    typedef std::map<int64_t, CPID> MapPIDCheckpoints;

    struct CPIDCheckpointData {
        const MapPIDCheckpoints *mapPIDCheckpoints;
        int64_t nTimeLastCheckpoint;
    };

    bool fEnabled = true;

    static MapPIDCheckpoints mapPIDCheckpoints =
        boost::assign::map_list_of
        (0, CPID(180.0f, 1.0f, 0.05f, 0.1f))
        (5600, CPID(180.0f, 1.0f, 0.05f, 0.1f, 256.0f, 102.0f, 62.0f, 0, 5599, 108.30000305f, 0x2507ffff))
        (5700, CPID(180.0f, 1.0f, 0.05f, 0.1f, 256.0f, 102.0f, 62.0f, 0, 5699, 108.30000305f, 0x251751ff))
        (5800, CPID(180.0f, 1.0f, 0.05f, 0.1f, 256.0f, 102.0f, 62.0f, 0, 5799, 108.30000305f, 0x251995ff))
        (5900, CPID(180.0f, 1.0f, 0.05f, 0.1f, 256.0f, 102.0f, 62.0f, 0, 5899, 108.30000305f, 0x251a64ff))
        (8600, CPID(180.0f, 1.0f, 0.05f, 0.1f, 201.0f, -30.0f,-25.0f, 0, 8599, -25.75000000f, 0x2501aeff))
        (9100, CPID(180.0f, 1.0f, 0.05f, 0.1f, -41.000000f, -79.000000f, -44.000000f, 0, 9099, -76.85000610f, 0x25028aff))
        (50000, CPID(180.0f, 1.0f, 0.05f, 0.1f, -256.000000f, -54.000000f, -37.000000f, 0, 49999, -70.50000000f, 0x250493ff))
        (100000, CPID(180.0f, 1.0f, 0.05f, 0.1f, 79.000000f, 4.000000f, -9.000000f, 0, 99999, 5.14999962f, 0x251069ff))
		(109500, CPID(180.0f, 1.0f, 0.05f, 0.1f, -154.000000f, 25.000000f, -14.000000f, 0, 109499, 15.99999905f, 0x251226ff))
		;
    static const CPIDCheckpointData data = {
        &mapPIDCheckpoints,
		0x14F11D83C20, // * timestamp of last PID checkpoint
    };

    static MapPIDCheckpoints mapPIDCheckpointsTestnet =
        boost::assign::map_list_of
        (0, CPID(180.0f, 1.0f, 0.05f, 0.1f))
        ;
    static const CPIDCheckpointData dataTestnet = {
        &mapPIDCheckpointsTestnet,
        0x148d455b42a
    };

    static MapPIDCheckpoints mapPIDCheckpointsRegtest =
        boost::assign::map_list_of
        (0, CPID(180.0f, 1.0f, 0.05f, 0.1f))
        ;
    static const CPIDCheckpointData dataRegtest = {
        &mapPIDCheckpointsRegtest,
        0
    };

    const CPIDCheckpointData &PIDCheckpoints() {
        if (Params().NetworkID() == CChainParams::TESTNET) {
            return dataTestnet;
        }
        else if (Params().NetworkID() == CChainParams::MAIN) {
            return data;
        }
        else {
            return dataRegtest;
        }
    }

    int64_t PIDGetHeightLastCheckpoint()
    {
        if (!fEnabled) {
            return 0;
        }
        const MapPIDCheckpoints& PIDcheckpoints = *PIDCheckpoints().mapPIDCheckpoints;

        return PIDcheckpoints.rbegin()->first;
    }

    int64_t PIDGetTimeLastCheckpoint()
    {
        if (!fEnabled) {
            return 0;
        }
        const int64_t PIDcheckpointTime = PIDCheckpoints().nTimeLastCheckpoint;

        return PIDcheckpointTime;
    }

    const CPID* GetPIDCheckpoint(int64_t height)
    {
        if (!fEnabled) {
            return NULL;
        }
        const MapPIDCheckpoints& PIDcheckpoints = *PIDCheckpoints().mapPIDCheckpoints;

        BOOST_REVERSE_FOREACH(const MapPIDCheckpoints::value_type& i, PIDcheckpoints)
        {
            if (i.first <= height) {
                const CPID& PIDChkpoint = i.second;
                return &PIDChkpoint;
            }
        }
        return NULL;
    }

}
<|endoftext|>


<commit_before>// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2011-2012 Litecoin Developers
// Copyright (c) 2013 Americancoin Developers

// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>

#include "checkpoints.h"

#include "main.h"
#include "uint256.h"

namespace Checkpoints
{
    typedef std::map<int, uint256> MapCheckpoints;

    //
    // What makes a good checkpoint block?
    // + Is surrounded by blocks with reasonable timestamps
    //   (no blocks before with a timestamp after, none after with
    //    timestamp before)
    // + Contains no strange transactions
    //
    static MapCheckpoints mapCheckpoints =
            boost::assign::map_list_of
            (     1, uint256("0x5869b89b8ab4717e9ca9c7d82b87d44f658f700e1b0149958307d37d7d4dabe2"))
            ;

    bool CheckBlock(int nHeight, const uint256& hash)
    {
        if (fTestNet) return true; // Testnet has no checkpoints

        MapCheckpoints::const_iterator i = mapCheckpoints.find(nHeight);
        if (i == mapCheckpoints.end()) return true;
        return hash == i->second;
    }

    int GetTotalBlocksEstimate()
    {
        if (fTestNet) return 0;

		//return 0;
        return mapCheckpoints.rbegin()->first;
    }

    CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
    {
        if (fTestNet) return NULL;

        BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints)
        {
            const uint256& hash = i.second;
            std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
            if (t != mapBlockIndex.end())
                return t->second;
        }
        return NULL;
    }
}
<commit_msg>Checkpoint updates<commit_after>// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2011-2012 Litecoin Developers
// Copyright (c) 2013 Americancoin Developers

// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>

#include "checkpoints.h"

#include "main.h"
#include "uint256.h"

namespace Checkpoints
{
    typedef std::map<int, uint256> MapCheckpoints;

    //
    // What makes a good checkpoint block?
    // + Is surrounded by blocks with reasonable timestamps
    //   (no blocks before with a timestamp after, none after with
    //    timestamp before)
    // + Contains no strange transactions
    //
    static MapCheckpoints mapCheckpoints =
            boost::assign::map_list_of
            (     0, uint256("0xe235425c8314df2f26b94d89fd5582edc74d80cf39d105107ea6cd12d8898491"))
            //(     1, uint256("0x5869b89b8ab4717e9ca9c7d82b87d44f658f700e1b0149958307d37d7d4dabe2"))
            ;

    bool CheckBlock(int nHeight, const uint256& hash)
    {
        if (fTestNet) return true; // Testnet has no checkpoints

        MapCheckpoints::const_iterator i = mapCheckpoints.find(nHeight);
        if (i == mapCheckpoints.end()) return true;
        return hash == i->second;
    }

    int GetTotalBlocksEstimate()
    {
        if (fTestNet) return 0;

		//return 0;
        return mapCheckpoints.rbegin()->first;
    }

    CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
    {
        if (fTestNet) return NULL;

        BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints)
        {
            const uint256& hash = i.second;
            std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
            if (t != mapBlockIndex.end())
                return t->second;
        }
        return NULL;
    }
}
<|endoftext|>


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

#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>

#include "checkpoints.h"

#include "main.h"
#include "uint256.h"

namespace Checkpoints
{
    typedef std::map<int, uint256> MapCheckpoints;

    // How many times we expect transactions after the last checkpoint to
    // be slower. This number is a compromise, as it can't be accurate for
    // every system. When reindexing from a fast disk with a slow CPU, it
    // can be up to 20, while when downloading from a slow network with a
    // fast multicore CPU, it won't be much higher than 1.
    static const double fSigcheckVerificationFactor = 5.0;

    struct CCheckpointData {
        const MapCheckpoints *mapCheckpoints;
        int64 nTimeLastCheckpoint;
        int64 nTransactionsLastCheckpoint;
        double fTransactionsPerDay;
    };

    // What makes a good checkpoint block?
    // + Is surrounded by blocks with reasonable timestamps
    //   (no blocks before with a timestamp after, none after with
    //    timestamp before)
    // + Contains no strange transactions
    static MapCheckpoints mapCheckpoints =
        boost::assign::map_list_of
        ( 48191, uint256("0x4499f469507e9dbd2850b65dd7db62429b3fecb207b1abbd785ae84c11c793cf"))
        ;
    static const CCheckpointData data = {
        &mapCheckpoints,
        1394891781, // * UNIX timestamp of last checkpoint block
        48454,      // * total number of transactions between genesis and last checkpoint
                    //   (the tx=... number in the SetBestChain debug.log lines)
        633.4       // * estimated number of transactions per day after checkpoint
    };

    static MapCheckpoints mapCheckpointsTestnet =
        boost::assign::map_list_of
        (   546, uint256("000000002a936ca763904c3c35fce2f3556c559c0214345d31b1bcebf76acb70"))
        ;
    static const CCheckpointData dataTestnet = {
        &mapCheckpointsTestnet,
        1369685559,
        37581,
        300
    };

    const CCheckpointData &Checkpoints() {
        if (fTestNet)
            return dataTestnet;
        else
            return data;
    }

    bool CheckBlock(int nHeight, const uint256& hash)
    {
        if (fTestNet) return true; // Testnet has no checkpoints
        if (!GetBoolArg("-checkpoints", true))
            return true;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
        if (i == checkpoints.end()) return true;
        return hash == i->second;
    }

    // Guess how far we are in the verification process at the given block index
    double GuessVerificationProgress(CBlockIndex *pindex) {
        if (pindex==NULL)
            return 0.0;

        int64 nNow = time(NULL);

        double fWorkBefore = 0.0; // Amount of work done before pindex
        double fWorkAfter = 0.0;  // Amount of work left after pindex (estimated)
        // Work is defined as: 1.0 per transaction before the last checkoint, and
        // fSigcheckVerificationFactor per transaction after.

        const CCheckpointData &data = Checkpoints();

        if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) {
            double nCheapBefore = pindex->nChainTx;
            double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx;
            double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay;
            fWorkBefore = nCheapBefore;
            fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor;
        } else {
            double nCheapBefore = data.nTransactionsLastCheckpoint;
            double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint;
            double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay;
            fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor;
            fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor;
        }

        return fWorkBefore / (fWorkBefore + fWorkAfter);
    }

    int GetTotalBlocksEstimate()
    {
        if (fTestNet) return 0; // Testnet has no checkpoints
        if (!GetBoolArg("-checkpoints", true))
            return 0;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        return checkpoints.rbegin()->first;
    }

    CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
    {
        if (fTestNet) return NULL; // Testnet has no checkpoints
        if (!GetBoolArg("-checkpoints", true))
            return NULL;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
        {
            const uint256& hash = i.second;
            std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
            if (t != mapBlockIndex.end())
                return t->second;
        }
        return NULL;
    }
}
<commit_msg>Remove checkpoint for testnet<commit_after>// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>

#include "checkpoints.h"

#include "main.h"
#include "uint256.h"

namespace Checkpoints
{
    typedef std::map<int, uint256> MapCheckpoints;

    // How many times we expect transactions after the last checkpoint to
    // be slower. This number is a compromise, as it can't be accurate for
    // every system. When reindexing from a fast disk with a slow CPU, it
    // can be up to 20, while when downloading from a slow network with a
    // fast multicore CPU, it won't be much higher than 1.
    static const double fSigcheckVerificationFactor = 5.0;

    struct CCheckpointData {
        const MapCheckpoints *mapCheckpoints;
        int64 nTimeLastCheckpoint;
        int64 nTransactionsLastCheckpoint;
        double fTransactionsPerDay;
    };

    // What makes a good checkpoint block?
    // + Is surrounded by blocks with reasonable timestamps
    //   (no blocks before with a timestamp after, none after with
    //    timestamp before)
    // + Contains no strange transactions
    static MapCheckpoints mapCheckpoints =
        boost::assign::map_list_of
        ( 48191, uint256("0x4499f469507e9dbd2850b65dd7db62429b3fecb207b1abbd785ae84c11c793cf"))
        ;
    static const CCheckpointData data = {
        &mapCheckpoints,
        1394891781, // * UNIX timestamp of last checkpoint block
        48454,      // * total number of transactions between genesis and last checkpoint
                    //   (the tx=... number in the SetBestChain debug.log lines)
        633.4       // * estimated number of transactions per day after checkpoint
    };

    const CCheckpointData &Checkpoints() {
        return data;
    }

    bool CheckBlock(int nHeight, const uint256& hash)
    {
        if (fTestNet) return true; // Testnet has no checkpoints
        if (!GetBoolArg("-checkpoints", true))
            return true;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
        if (i == checkpoints.end()) return true;
        return hash == i->second;
    }

    // Guess how far we are in the verification process at the given block index
    double GuessVerificationProgress(CBlockIndex *pindex) {
        if (fTestNet) return 0.0; // Testnet has no checkpoints
        if (pindex==NULL)
            return 0.0;

        int64 nNow = time(NULL);

        double fWorkBefore = 0.0; // Amount of work done before pindex
        double fWorkAfter = 0.0;  // Amount of work left after pindex (estimated)
        // Work is defined as: 1.0 per transaction before the last checkoint, and
        // fSigcheckVerificationFactor per transaction after.

        const CCheckpointData &data = Checkpoints();

        if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) {
            double nCheapBefore = pindex->nChainTx;
            double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx;
            double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay;
            fWorkBefore = nCheapBefore;
            fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor;
        } else {
            double nCheapBefore = data.nTransactionsLastCheckpoint;
            double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint;
            double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay;
            fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor;
            fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor;
        }

        return fWorkBefore / (fWorkBefore + fWorkAfter);
    }

    int GetTotalBlocksEstimate()
    {
        if (fTestNet) return 0; // Testnet has no checkpoints
        if (!GetBoolArg("-checkpoints", true))
            return 0;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        return checkpoints.rbegin()->first;
    }

    CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
    {
        if (fTestNet) return NULL; // Testnet has no checkpoints
        if (!GetBoolArg("-checkpoints", true))
            return NULL;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
        {
            const uint256& hash = i.second;
            std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
            if (t != mapBlockIndex.end())
                return t->second;
        }
        return NULL;
    }
}
<|endoftext|>


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

#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>

#include "checkpoints.h"

#include "txdb.h"
#include "main.h"
#include "uint256.h"

static const int nCheckpointSpan = 500;

namespace Checkpoints
{
    typedef std::map<int, uint256> MapCheckpoints;

    //
    // What makes a good checkpoint block?
    // + Is surrounded by blocks with reasonable timestamps
    //   (no blocks before with a timestamp after, none after with
    //    timestamp before)
    // + Contains no strange transactions
    //
    static MapCheckpoints mapCheckpoints =
        boost::assign::map_list_of
        ( 0,   uint256("0x0000095667f3c1fdbf0b9b4937be57c6401162fcfe72be373df27393f0c69d93") ) // genesis
        ( 50000,   uint256("0x38de11fd0ac1ef41a3fab6d5faac3e597c509244ad028dba20a12832f9b38e92") )
        ( 100000,   uint256("0x4d32d90e958c1060a8346dbcd72b96459bcc9ded1241d51f7b09be3eaf405901") )
        ( 150000,   uint256("0x3efea69afbdfaab1a9e2d1240a014aa7c88c66cf246107febbe0d2db147e7350") )
        ( 200000,   uint256("0xf0bb302a774b841e03d3818f980ecb0c1354f7ff048ff2dc004c3003178c3d56") )
        ( 250000,   uint256("0xa7325d458200a636d20f3be182d2121acb725de486adf1f855cb72ea9203f56d") )
        ( 300000,   uint256("0x3c536e6c98d1eb54610a7133d671f560627d731aaef8a46db35335255217d2eb") )
        ( 330000,   uint256("0xbc45b022e71c2c83765009426a5a54db7e6fa4f94d3ee53e1418a54388529b95") )
        ( 360000,   uint256("0x103c1ee3cf53529a1bee0bfdff21a32bec361c668df6f7bfc3665d84cbad394d") )
        ( 423000,   uint256("0x00000000000000940d7a26bfaf12ac74bcefb22ff231560b805deac6728917fc") )
        ( 451000,   uint256("0x66e23ed10acad88fe2b81c3e31d510dd37ee351c217c5c1a2146bcab754e89cc") )
        ( 472737,   uint256("0x2b306a5c48b16fd7fd84017ef6a9df4da86bb9871bf8a015a74044d41ec84aaa") )
        ( 482666,   uint256("0x9291b42d4b06da001a471a306888c0a58329b812ed26509129e0231545d7a93a") )
        ( 499888,   uint256("0xe9c977ab38ce0d47dc222e078ad71a548c67425d563d79d8f25247eaf6457e1c") )
        ( 511111,   uint256("0xf2e9623e0efe8fe23687126cb5cb7588584407e89121fa238d7729af38366de7") )
        ( 523000,   uint256("0x0000000000000114b08260c1c94752710bdfd6bb415f6e4ff7d071e0a8c1797b") )
    ;

    // TestNet has no checkpoints
    static MapCheckpoints mapCheckpointsTestnet;

    bool CheckHardened(int nHeight, const uint256& hash)
    {
        MapCheckpoints& checkpoints = (TestNet() ? mapCheckpointsTestnet : mapCheckpoints);

        MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
        if (i == checkpoints.end()) return true;
        return hash == i->second;
    }

    int GetTotalBlocksEstimate()
    {
        MapCheckpoints& checkpoints = (TestNet() ? mapCheckpointsTestnet : mapCheckpoints);

        if (checkpoints.empty())
            return 0;
        return checkpoints.rbegin()->first;
    }

    CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
    {
        MapCheckpoints& checkpoints = (TestNet() ? mapCheckpointsTestnet : mapCheckpoints);

        BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
        {
            const uint256& hash = i.second;
            std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
            if (t != mapBlockIndex.end())
                return t->second;
        }
        return NULL;
    }

    // Automatically select a suitable sync-checkpoint
    const CBlockIndex* AutoSelectSyncCheckpoint()
    {
        const CBlockIndex *pindex = pindexBest;
        // Search backward for a block within max span and maturity window
        while (pindex->pprev && pindex->nHeight + nCheckpointSpan > pindexBest->nHeight)
            pindex = pindex->pprev;
        return pindex;
    }

    // Check against synchronized checkpoint
    bool CheckSync(int nHeight)
    {
        const CBlockIndex* pindexSync = AutoSelectSyncCheckpoint();

        if (nHeight <= pindexSync->nHeight)
            return false;
        return true;
    }
}
<commit_msg>Checkpoint at Block 525600 the POS halving block<commit_after>// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>

#include "checkpoints.h"

#include "txdb.h"
#include "main.h"
#include "uint256.h"

static const int nCheckpointSpan = 500;

namespace Checkpoints
{
    typedef std::map<int, uint256> MapCheckpoints;

    //
    // What makes a good checkpoint block?
    // + Is surrounded by blocks with reasonable timestamps
    //   (no blocks before with a timestamp after, none after with
    //    timestamp before)
    // + Contains no strange transactions
    //
    static MapCheckpoints mapCheckpoints =
        boost::assign::map_list_of
        ( 0,   uint256("0x0000095667f3c1fdbf0b9b4937be57c6401162fcfe72be373df27393f0c69d93") ) // genesis
        ( 50000,   uint256("0x38de11fd0ac1ef41a3fab6d5faac3e597c509244ad028dba20a12832f9b38e92") )
        ( 100000,   uint256("0x4d32d90e958c1060a8346dbcd72b96459bcc9ded1241d51f7b09be3eaf405901") )
        ( 150000,   uint256("0x3efea69afbdfaab1a9e2d1240a014aa7c88c66cf246107febbe0d2db147e7350") )
        ( 200000,   uint256("0xf0bb302a774b841e03d3818f980ecb0c1354f7ff048ff2dc004c3003178c3d56") )
        ( 250000,   uint256("0xa7325d458200a636d20f3be182d2121acb725de486adf1f855cb72ea9203f56d") )
        ( 300000,   uint256("0x3c536e6c98d1eb54610a7133d671f560627d731aaef8a46db35335255217d2eb") )
        ( 330000,   uint256("0xbc45b022e71c2c83765009426a5a54db7e6fa4f94d3ee53e1418a54388529b95") )
        ( 360000,   uint256("0x103c1ee3cf53529a1bee0bfdff21a32bec361c668df6f7bfc3665d84cbad394d") )
        ( 423000,   uint256("0x00000000000000940d7a26bfaf12ac74bcefb22ff231560b805deac6728917fc") )
        ( 451000,   uint256("0x66e23ed10acad88fe2b81c3e31d510dd37ee351c217c5c1a2146bcab754e89cc") )
        ( 472737,   uint256("0x2b306a5c48b16fd7fd84017ef6a9df4da86bb9871bf8a015a74044d41ec84aaa") )
        ( 482666,   uint256("0x9291b42d4b06da001a471a306888c0a58329b812ed26509129e0231545d7a93a") )
        ( 499888,   uint256("0xe9c977ab38ce0d47dc222e078ad71a548c67425d563d79d8f25247eaf6457e1c") )
        ( 511111,   uint256("0xf2e9623e0efe8fe23687126cb5cb7588584407e89121fa238d7729af38366de7") )
        ( 523000,   uint256("0x0000000000000114b08260c1c94752710bdfd6bb415f6e4ff7d071e0a8c1797b") )
        ( 525600,   uint256("0xdba6cc2f5ab9621386dbef5f9343096923f50e47536eda4cc18418a48bb5ac67") )
    ;

    // TestNet has no checkpoints
    static MapCheckpoints mapCheckpointsTestnet;

    bool CheckHardened(int nHeight, const uint256& hash)
    {
        MapCheckpoints& checkpoints = (TestNet() ? mapCheckpointsTestnet : mapCheckpoints);

        MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
        if (i == checkpoints.end()) return true;
        return hash == i->second;
    }

    int GetTotalBlocksEstimate()
    {
        MapCheckpoints& checkpoints = (TestNet() ? mapCheckpointsTestnet : mapCheckpoints);

        if (checkpoints.empty())
            return 0;
        return checkpoints.rbegin()->first;
    }

    CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
    {
        MapCheckpoints& checkpoints = (TestNet() ? mapCheckpointsTestnet : mapCheckpoints);

        BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
        {
            const uint256& hash = i.second;
            std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
            if (t != mapBlockIndex.end())
                return t->second;
        }
        return NULL;
    }

    // Automatically select a suitable sync-checkpoint
    const CBlockIndex* AutoSelectSyncCheckpoint()
    {
        const CBlockIndex *pindex = pindexBest;
        // Search backward for a block within max span and maturity window
        while (pindex->pprev && pindex->nHeight + nCheckpointSpan > pindexBest->nHeight)
            pindex = pindex->pprev;
        return pindex;
    }

    // Check against synchronized checkpoint
    bool CheckSync(int nHeight)
    {
        const CBlockIndex* pindexSync = AutoSelectSyncCheckpoint();

        if (nHeight <= pindexSync->nHeight)
            return false;
        return true;
    }
}
<|endoftext|>


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

#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>

#include "checkpoints.h"

#include "main.h"
#include "uint256.h"

namespace Checkpoints
{
    typedef std::map<int, uint256> MapCheckpoints;

    // How many times we expect transactions after the last checkpoint to
    // be slower. This number is a compromise, as it can't be accurate for
    // every system. When reindexing from a fast disk with a slow CPU, it
    // can be up to 20, while when downloading from a slow network with a
    // fast multicore CPU, it won't be much higher than 1.
    static const double fSigcheckVerificationFactor = 5.0;

    struct CCheckpointData {
        const MapCheckpoints *mapCheckpoints;
        int64 nTimeLastCheckpoint;
        int64 nTransactionsLastCheckpoint;
        double fTransactionsPerDay;
    };

    // What makes a good checkpoint block?
    // + Is surrounded by blocks with reasonable timestamps
    //   (no blocks before with a timestamp after, none after with
    //    timestamp before)
    // + Contains no strange transactions
    static MapCheckpoints mapCheckpoints =
        boost::assign::map_list_of
        ( 0, uint256("0x0000008625534e38467b29078ed2868c2ec43eb024c4a2e7ff2f6480f283656b"))
		( 21, uint256("0x0000001a8db2123f1207842e2584941894c2b5645b25769b3d3c64102abc32d4"))
        ;
    static const CCheckpointData data = {
        &mapCheckpoints,
        1395041559, // * UNIX timestamp of last checkpoint block
        22,     // * total number of transactions between genesis and last checkpoint
                    //   (the tx=... number in the SetBestChain debug.log lines)
        60000.0     // * estimated number of transactions per day after checkpoint
    };

    static MapCheckpoints mapCheckpointsTestnet =
        boost::assign::map_list_of
        ( 0, uint256("0x0000006a6b8058247f5b0edb1b34df7d34ae6c963c49da21b62a4b6558ac94dc"))
        ;
    static const CCheckpointData dataTestnet = {
        &mapCheckpointsTestnet,
        1381033532,
        0,
        60000.0
    };

    const CCheckpointData &Checkpoints() {
        if (fTestNet)
            return dataTestnet;
        else
            return data;
    }

    bool CheckBlock(int nHeight, const uint256& hash)
    {
        if (!GetBoolArg("-checkpoints", true))
            return true;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
        if (i == checkpoints.end()) return true;
        return hash == i->second;
    }

    // Guess how far we are in the verification process at the given block index
    double GuessVerificationProgress(CBlockIndex *pindex) {
        if (pindex==NULL)
            return 0.0;

        int64 nNow = time(NULL);

        double fWorkBefore = 0.0; // Amount of work done before pindex
        double fWorkAfter = 0.0;  // Amount of work left after pindex (estimated)
        // Work is defined as: 1.0 per transaction before the last checkoint, and
        // fSigcheckVerificationFactor per transaction after.

        const CCheckpointData &data = Checkpoints();

        if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) {
            double nCheapBefore = pindex->nChainTx;
            double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx;
            double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay;
            fWorkBefore = nCheapBefore;
            fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor;
        } else {
            double nCheapBefore = data.nTransactionsLastCheckpoint;
            double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint;
            double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay;
            fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor;
            fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor;
        }

        return fWorkBefore / (fWorkBefore + fWorkAfter);
    }

    int GetTotalBlocksEstimate()
    {
        if (!GetBoolArg("-checkpoints", true))
            return 0;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        return checkpoints.rbegin()->first;
    }

    CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
    {
        if (!GetBoolArg("-checkpoints", true))
            return NULL;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
        {
            const uint256& hash = i.second;
            std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
            if (t != mapBlockIndex.end())
                return t->second;
        }
        return NULL;
    }
}
<commit_msg>update checkpoints.cpp<commit_after>// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>

#include "checkpoints.h"

#include "main.h"
#include "uint256.h"

namespace Checkpoints
{
    typedef std::map<int, uint256> MapCheckpoints;

    // How many times we expect transactions after the last checkpoint to
    // be slower. This number is a compromise, as it can't be accurate for
    // every system. When reindexing from a fast disk with a slow CPU, it
    // can be up to 20, while when downloading from a slow network with a
    // fast multicore CPU, it won't be much higher than 1.
    static const double fSigcheckVerificationFactor = 5.0;

    struct CCheckpointData {
        const MapCheckpoints *mapCheckpoints;
        int64 nTimeLastCheckpoint;
        int64 nTransactionsLastCheckpoint;
        double fTransactionsPerDay;
    };

    // What makes a good checkpoint block?
    // + Is surrounded by blocks with reasonable timestamps
    //   (no blocks before with a timestamp after, none after with
    //    timestamp before)
    // + Contains no strange transactions
    static MapCheckpoints mapCheckpoints =
        boost::assign::map_list_of
        ( 0, uint256("0x0000008625534e38467b29078ed2868c2ec43eb024c4a2e7ff2f6480f283656b"))
	( 21, uint256("0x0000001a8db2123f1207842e2584941894c2b5645b25769b3d3c64102abc32d4"))
	( 21540, uint256("0x000000000052c4c211c1d40a05dd2a687536e67c26aeaaf801e7c1f37c90dd5c"))
        ;
    static const CCheckpointData data = {
        &mapCheckpoints,
        1395379942, // * UNIX timestamp of last checkpoint block
        25289,     // * total number of transactions between genesis and last checkpoint
                    //   (the tx=... number in the SetBestChain debug.log lines)
        60000.0     // * estimated number of transactions per day after checkpoint
    };

    static MapCheckpoints mapCheckpointsTestnet =
        boost::assign::map_list_of
        ( 0, uint256("0x0000006a6b8058247f5b0edb1b34df7d34ae6c963c49da21b62a4b6558ac94dc"))
        ;
    static const CCheckpointData dataTestnet = {
        &mapCheckpointsTestnet,
        1381033532,
        0,
        60000.0
    };

    const CCheckpointData &Checkpoints() {
        if (fTestNet)
            return dataTestnet;
        else
            return data;
    }

    bool CheckBlock(int nHeight, const uint256& hash)
    {
        if (!GetBoolArg("-checkpoints", true))
            return true;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
        if (i == checkpoints.end()) return true;
        return hash == i->second;
    }

    // Guess how far we are in the verification process at the given block index
    double GuessVerificationProgress(CBlockIndex *pindex) {
        if (pindex==NULL)
            return 0.0;

        int64 nNow = time(NULL);

        double fWorkBefore = 0.0; // Amount of work done before pindex
        double fWorkAfter = 0.0;  // Amount of work left after pindex (estimated)
        // Work is defined as: 1.0 per transaction before the last checkoint, and
        // fSigcheckVerificationFactor per transaction after.

        const CCheckpointData &data = Checkpoints();

        if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) {
            double nCheapBefore = pindex->nChainTx;
            double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx;
            double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay;
            fWorkBefore = nCheapBefore;
            fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor;
        } else {
            double nCheapBefore = data.nTransactionsLastCheckpoint;
            double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint;
            double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay;
            fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor;
            fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor;
        }

        return fWorkBefore / (fWorkBefore + fWorkAfter);
    }

    int GetTotalBlocksEstimate()
    {
        if (!GetBoolArg("-checkpoints", true))
            return 0;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        return checkpoints.rbegin()->first;
    }

    CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
    {
        if (!GetBoolArg("-checkpoints", true))
            return NULL;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
        {
            const uint256& hash = i.second;
            std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
            if (t != mapBlockIndex.end())
                return t->second;
        }
        return NULL;
    }
}
<|endoftext|>


<commit_before>#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <string>
#include <iostream>
#include <sstream>
#include <memory>

#include "../command.hxx"
#include "../interp.hxx"
#include "../argument.hxx"
#include "../common.hxx"
#include "basic_parsers.hxx"

using namespace std;

namespace tglng {
  template<typename Operator>
  class StringComparison: public BinaryCommand {
    Operator op;

  public:
    StringComparison(Command* left,
                     auto_ptr<Command>& l,
                     auto_ptr<Command>& r)
    : BinaryCommand(left, l, r) {}

    virtual bool exec(wstring& out, Interpreter& interp) {
      wstring lstr, rstr;
      if (!interp.exec(lstr, lhs.get()) ||
          !interp.exec(rstr, rhs.get())) return false;

      out = op(lstr,rstr)? L"1" : L"0";
      return true;
    }
  };

  template<typename Operator>
  class StringComparisonParser:
  public BinaryCommandParser<StringComparison<Operator> > {
  };

  static GlobalBinding<StringComparisonParser<equal_to<wstring> > >
  _strequParser(L"str-equ");
  static GlobalBinding<StringComparisonParser<less<wstring> > >
  _strsltParser(L"str-slt");
  static GlobalBinding<StringComparisonParser<greater<wstring> > >
  _strsgtParser(L"str-sgt");

  class StringSearch: public Command {
    auto_ptr<Command> needle, haystack;

  public:
    StringSearch(Command* left,
                 auto_ptr<Command>& n,
                 auto_ptr<Command>& h)
    : Command(left), needle(n), haystack(h)
    { }

    virtual bool exec(wstring& out, Interpreter& interp) {
      wstring ns, hs;
      if (!interp.exec(ns, needle  .get())) return false;
      if (!interp.exec(hs, haystack.get())) return false;

      size_t result = hs.find(ns);
      if (result == wstring::npos)
        //Not found
        out = L"";
      else
        out = intToStr((signed)result);

      return true;
    }
  };

  class StringSearchParser: public CommandParser {
  public:
    virtual ParseResult parse(Interpreter& interp, Command*& out,
                              const wstring& text,
                              unsigned& offset) {
      auto_ptr<Command> needle, haystack;
      ArgumentParser a(interp, text, offset, out);
      if (!a[a.h(), a.a(needle), a.a(haystack)])
        return ParseError;

      out = new StringSearch(out, needle, haystack);
      return ContinueParsing;
    }
  };

  static GlobalBinding<StringSearchParser> _stringSearchParser(L"str-str");

  class StringIndex: public Command {
    auto_ptr<Command> begin, end;
    bool treatEndAsLength;
    AutoSection string;

  public:
    StringIndex(Command* left,
                auto_ptr<Command>& begin_,
                auto_ptr<Command>& end_,
                bool treatEndAsLength_,
                Section string_)
    : Command(left),
      begin(begin_), end(end_),
      treatEndAsLength(treatEndAsLength_),
      string(string_)
    { }

    virtual bool exec(wstring& out, Interpreter& interp) {
      wstring sb, se, str, strr;
      signed ib, ie;

      //Get the parms
      if ((string.left && !interp.exec(str, string.left)) ||
          !interp.exec(sb, begin.get()) ||
          (end.get() && !interp.exec(se, end.get())) ||
          (string.right && !interp.exec(strr, string.right)))
        return false;

      //Concat section parts
      str += strr;

      //Convert integers
      if (!parseInteger(ib, sb)) {
        wcerr << L"Invalid integer: " << sb << endl;
        return false;
      }

      if (se.empty())
        //Implicitly one character
        ie = ib+1;
      else {
        if (!parseInteger(ie, se)) {
          wcerr << L"Invalid integer: " << se << endl;
          return false;
        }

        //Add ib if in length mode
        if (treatEndAsLength)
          ie += ib;
      }

      //Negative indices are relative to the end (plus one for end)
      if (ib < 0) ib += str.size();
      if (ie < 0) ie += str.size()+1;

      //Clamp indices
      if (ib < 0) ib = 0;
      if (ib > (signed)str.size()) ib = str.size();
      if (ie < ib) ie = ib;
      if (ie > (signed)str.size()) ie = str.size();

      //OK
      if (ib < (signed)str.size())
        out = str.substr(ib, ie-ib);
      else
        out.clear();
      return true;
    }
  };

  class StringIndexParser: public CommandParser {
  public:
    virtual ParseResult parse(Interpreter& interp, Command*& out,
                              const wstring& text, unsigned& offset) {
      auto_ptr<Command> begin, end;
      AutoSection string;
      bool length = false;
      ArgumentParser a(interp, text, offset, out);
      if (!a[a.h(), a.a(begin),
             (-a.x(length, L'.'), a.a(end)) -=
             a.s(string)])
        return ParseError;

      out = new StringIndex(out, begin, end, length, string);
      string.clear(); //Now owned by out
      return ContinueParsing;
    }
  };

  static GlobalBinding<StringIndexParser> _stringIndexParser(L"str-ix");

  class StringClass: public Command {
    //The function to check each character
    int (*is)(int);
    //Whether the range of is is restricted to 0..127
    bool asciiOnly;
    //Whether to negate the check
    bool negate;

    auto_ptr<Command> string;

    /* ISO C says that the char varieties are
     *   int f(int)
     * and the wchar_t are
     *   int f(wint_t).
     *
     * G++ considers the two incompatible (due to different signedness), but
     * that won't affect us. On most systems, sizeof(int) ==
     * sizeof(wint_t). Ensure that is true on this system.
     */
    void checkSizeofIntEqualsSizeofWintT() {
      switch (true) {
      case false:
      case sizeof(int) == sizeof(wint_t):;
      }
    }

  public:
    StringClass(Command* left,
                int (*is_)(int),
                bool asciiOnly_,
                bool negate_,
                auto_ptr<Command>& string_)
    : Command(left),
      is(is_), asciiOnly(asciiOnly_), negate(negate_),
      string(string_)
    { }

    virtual bool exec(wstring& out, Interpreter& interp) {
      wstring str;
      bool result;
      if (!interp.exec(str, string.get())) return false;

      if (str.empty()) {
        result = false;
        goto done;
      }

      for (unsigned i = 0; i < str.size(); ++i) {
        wchar_t curr = str[i];
        if ((!negate) ^
            ((!asciiOnly || (curr >= 0 && curr < 128)) &&
             is(curr))) {
          //Character failed
          result = false;
          goto done;
        }
      }

      //All chars passed
      result = true;

      done:
      out = (result? L"1" : L"0");
      return true;
    }
  };

  class StringClassParser: public CommandParser {
  public:
    virtual ParseResult parse(Interpreter& interp, Command*& out,
                              const wstring& text, unsigned& offset) {
      wchar_t clazzch;
      unsigned clazzOffset;
      //The wchar_t functions take a wint_t. An assertion in StringClass
      //ensures that the functions are compatible.
      union {
        int (*a)(int);
        int (*u)(wint_t);
      } clazz;
      bool negate, asciiOnly;
      auto_ptr<Command> string;
      ArgumentParser a(interp, text, offset, out);
      if (!a[a.h(), a.h(clazzch) >> clazzOffset, a.a(string)])
        return ParseError;

      switch (clazzch) {
      case L'l': clazz.u = iswlower, negate = false, asciiOnly = false; break;
      case L'L': clazz.u = iswlower, negate = true , asciiOnly = false; break;
      case L'o': clazz.a = islower , negate = false, asciiOnly = true ; break;
      case L'O': clazz.a = islower , negate = true , asciiOnly = true ; break;
      case L'u': clazz.u = iswupper, negate = false, asciiOnly = false; break;
      case L'U': clazz.u = iswupper, negate = true , asciiOnly = false; break;
      case L'v': clazz.a = isupper , negate = false, asciiOnly = true ; break;
      case L'V': clazz.a = isupper , negate = true , asciiOnly = true ; break;
      case L'a': clazz.u = iswalpha, negate = false, asciiOnly = false; break;
      case L'A': clazz.u = iswalpha, negate = true , asciiOnly = false; break;
      case L'b': clazz.a = isalpha , negate = false, asciiOnly = true ; break;
      case L'B': clazz.a = isalpha , negate = true , asciiOnly = true ; break;
      case L'n': clazz.u = iswalnum, negate = false, asciiOnly = false; break;
      case L'N': clazz.u = iswalnum, negate = true , asciiOnly = false; break;
      case L'm': clazz.a = isalnum , negate = false, asciiOnly = true ; break;
      case L'M': clazz.a = isalnum , negate = true , asciiOnly = true ; break;
      case L'\\':clazz.a = iscntrl , negate = false, asciiOnly = true ; break;
      case L'~': clazz.a = iscntrl , negate = true , asciiOnly = true ; break;
      case L'0': clazz.a = isdigit , negate = false, asciiOnly = true ; break;
      case L'9': clazz.a = isdigit , negate = true , asciiOnly = true ; break;
      case L'x': clazz.a = isxdigit, negate = false, asciiOnly = true ; break;
      case L'X': clazz.a = isxdigit, negate = true , asciiOnly = true ; break;
      case L'.':
      case L'p': clazz.u = iswpunct, negate = false, asciiOnly = false; break;
      case L':':
      case L'P': clazz.u = iswpunct, negate = true , asciiOnly = false; break;
      case L',':
      case L'q': clazz.a = ispunct , negate = false, asciiOnly = true ; break;
      case L';':
      case L'Q': clazz.a = ispunct , negate = true , asciiOnly = true ; break;
      case L's':
      case L'_': clazz.u = iswspace, negate = false, asciiOnly = false; break;
      case L'S':
      case L'#': clazz.u = iswspace, negate = true , asciiOnly = false; break;
      case L'g': clazz.u = iswgraph, negate = false, asciiOnly = false; break;
      case L'G': clazz.u = iswgraph, negate = true , asciiOnly = false; break;
      case L'h': clazz.a = isgraph , negate = false, asciiOnly = true ; break;
      case L'H': clazz.a = isgraph , negate = true , asciiOnly = true ; break;
      case L'r': clazz.u = iswprint, negate = false, asciiOnly = false; break;
      case L'R': clazz.u = iswprint, negate = true , asciiOnly = false; break;
      /* Not 's' since people might expect it to be space. */
      case L't': clazz.a = isprint , negate = false, asciiOnly = true ; break;
      case L'T': clazz.a = isprint , negate = true , asciiOnly = true ; break;

      default:
        interp.error(wstring(L"Unknown character class: ") + clazzch,
                     text, clazzOffset);
        return ParseError;
      }

      //OK
      out = new StringClass(out, clazz.a, asciiOnly, negate, string);
      return ContinueParsing;
    }
  };

  static GlobalBinding<StringClassParser> _stringClassParser(L"str-is");

  class StringLength: public UnaryCommand {
  public:
    StringLength(Command* left, auto_ptr<Command>& sub)
    : UnaryCommand(left, sub) {}

    virtual bool exec(wstring& dst, Interpreter& interp) {
      wstring s;
      if (!interp.exec(s, sub.get())) return false;

      dst = intToStr(s.size());
      return true;
    }
  };

  static GlobalBinding<UnaryCommandParser<StringLength> >
  _stringLengthParser(L"str-len");
}
<commit_msg>Fix str-ix handling of lengths with negative start indices.<commit_after>#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <string>
#include <iostream>
#include <sstream>
#include <memory>

#include "../command.hxx"
#include "../interp.hxx"
#include "../argument.hxx"
#include "../common.hxx"
#include "basic_parsers.hxx"

using namespace std;

namespace tglng {
  template<typename Operator>
  class StringComparison: public BinaryCommand {
    Operator op;

  public:
    StringComparison(Command* left,
                     auto_ptr<Command>& l,
                     auto_ptr<Command>& r)
    : BinaryCommand(left, l, r) {}

    virtual bool exec(wstring& out, Interpreter& interp) {
      wstring lstr, rstr;
      if (!interp.exec(lstr, lhs.get()) ||
          !interp.exec(rstr, rhs.get())) return false;

      out = op(lstr,rstr)? L"1" : L"0";
      return true;
    }
  };

  template<typename Operator>
  class StringComparisonParser:
  public BinaryCommandParser<StringComparison<Operator> > {
  };

  static GlobalBinding<StringComparisonParser<equal_to<wstring> > >
  _strequParser(L"str-equ");
  static GlobalBinding<StringComparisonParser<less<wstring> > >
  _strsltParser(L"str-slt");
  static GlobalBinding<StringComparisonParser<greater<wstring> > >
  _strsgtParser(L"str-sgt");

  class StringSearch: public Command {
    auto_ptr<Command> needle, haystack;

  public:
    StringSearch(Command* left,
                 auto_ptr<Command>& n,
                 auto_ptr<Command>& h)
    : Command(left), needle(n), haystack(h)
    { }

    virtual bool exec(wstring& out, Interpreter& interp) {
      wstring ns, hs;
      if (!interp.exec(ns, needle  .get())) return false;
      if (!interp.exec(hs, haystack.get())) return false;

      size_t result = hs.find(ns);
      if (result == wstring::npos)
        //Not found
        out = L"";
      else
        out = intToStr((signed)result);

      return true;
    }
  };

  class StringSearchParser: public CommandParser {
  public:
    virtual ParseResult parse(Interpreter& interp, Command*& out,
                              const wstring& text,
                              unsigned& offset) {
      auto_ptr<Command> needle, haystack;
      ArgumentParser a(interp, text, offset, out);
      if (!a[a.h(), a.a(needle), a.a(haystack)])
        return ParseError;

      out = new StringSearch(out, needle, haystack);
      return ContinueParsing;
    }
  };

  static GlobalBinding<StringSearchParser> _stringSearchParser(L"str-str");

  class StringIndex: public Command {
    auto_ptr<Command> begin, end;
    bool treatEndAsLength;
    AutoSection string;

  public:
    StringIndex(Command* left,
                auto_ptr<Command>& begin_,
                auto_ptr<Command>& end_,
                bool treatEndAsLength_,
                Section string_)
    : Command(left),
      begin(begin_), end(end_),
      treatEndAsLength(treatEndAsLength_),
      string(string_)
    { }

    virtual bool exec(wstring& out, Interpreter& interp) {
      wstring sb, se, str, strr;
      signed ib, ie;

      //Get the parms
      if ((string.left && !interp.exec(str, string.left)) ||
          !interp.exec(sb, begin.get()) ||
          (end.get() && !interp.exec(se, end.get())) ||
          (string.right && !interp.exec(strr, string.right)))
        return false;

      //Concat section parts
      str += strr;

      //Convert integers
      if (!parseInteger(ib, sb)) {
        wcerr << L"Invalid integer: " << sb << endl;
        return false;
      }

      if (!se.empty()) {
        if (!parseInteger(ie, se)) {
          wcerr << L"Invalid integer: " << se << endl;
          return false;
        }
      }

      //Negative indices are relative to the end (plus one for end)
      if (ib < 0) ib += str.size();
      if (se.empty())
        //Implicitly one character
        ie = ib+1;
      else if (treatEndAsLength)
        ie = ie+ib;
      else if (ie < 0)
        ie += str.size()+1;

      //Clamp indices
      if (ib < 0) ib = 0;
      if (ib > (signed)str.size()) ib = str.size();
      if (ie < ib) ie = ib;
      if (ie > (signed)str.size()) ie = str.size();

      //OK
      if (ib < (signed)str.size())
        out = str.substr(ib, ie-ib);
      else
        out.clear();
      return true;
    }
  };

  class StringIndexParser: public CommandParser {
  public:
    virtual ParseResult parse(Interpreter& interp, Command*& out,
                              const wstring& text, unsigned& offset) {
      auto_ptr<Command> begin, end;
      AutoSection string;
      bool length = false;
      ArgumentParser a(interp, text, offset, out);
      if (!a[a.h(), a.a(begin),
             (-a.x(length, L'.'), a.a(end)) -=
             a.s(string)])
        return ParseError;

      out = new StringIndex(out, begin, end, length, string);
      string.clear(); //Now owned by out
      return ContinueParsing;
    }
  };

  static GlobalBinding<StringIndexParser> _stringIndexParser(L"str-ix");

  class StringClass: public Command {
    //The function to check each character
    int (*is)(int);
    //Whether the range of is is restricted to 0..127
    bool asciiOnly;
    //Whether to negate the check
    bool negate;

    auto_ptr<Command> string;

    /* ISO C says that the char varieties are
     *   int f(int)
     * and the wchar_t are
     *   int f(wint_t).
     *
     * G++ considers the two incompatible (due to different signedness), but
     * that won't affect us. On most systems, sizeof(int) ==
     * sizeof(wint_t). Ensure that is true on this system.
     */
    void checkSizeofIntEqualsSizeofWintT() {
      switch (true) {
      case false:
      case sizeof(int) == sizeof(wint_t):;
      }
    }

  public:
    StringClass(Command* left,
                int (*is_)(int),
                bool asciiOnly_,
                bool negate_,
                auto_ptr<Command>& string_)
    : Command(left),
      is(is_), asciiOnly(asciiOnly_), negate(negate_),
      string(string_)
    { }

    virtual bool exec(wstring& out, Interpreter& interp) {
      wstring str;
      bool result;
      if (!interp.exec(str, string.get())) return false;

      if (str.empty()) {
        result = false;
        goto done;
      }

      for (unsigned i = 0; i < str.size(); ++i) {
        wchar_t curr = str[i];
        if ((!negate) ^
            ((!asciiOnly || (curr >= 0 && curr < 128)) &&
             is(curr))) {
          //Character failed
          result = false;
          goto done;
        }
      }

      //All chars passed
      result = true;

      done:
      out = (result? L"1" : L"0");
      return true;
    }
  };

  class StringClassParser: public CommandParser {
  public:
    virtual ParseResult parse(Interpreter& interp, Command*& out,
                              const wstring& text, unsigned& offset) {
      wchar_t clazzch;
      unsigned clazzOffset;
      //The wchar_t functions take a wint_t. An assertion in StringClass
      //ensures that the functions are compatible.
      union {
        int (*a)(int);
        int (*u)(wint_t);
      } clazz;
      bool negate, asciiOnly;
      auto_ptr<Command> string;
      ArgumentParser a(interp, text, offset, out);
      if (!a[a.h(), a.h(clazzch) >> clazzOffset, a.a(string)])
        return ParseError;

      switch (clazzch) {
      case L'l': clazz.u = iswlower, negate = false, asciiOnly = false; break;
      case L'L': clazz.u = iswlower, negate = true , asciiOnly = false; break;
      case L'o': clazz.a = islower , negate = false, asciiOnly = true ; break;
      case L'O': clazz.a = islower , negate = true , asciiOnly = true ; break;
      case L'u': clazz.u = iswupper, negate = false, asciiOnly = false; break;
      case L'U': clazz.u = iswupper, negate = true , asciiOnly = false; break;
      case L'v': clazz.a = isupper , negate = false, asciiOnly = true ; break;
      case L'V': clazz.a = isupper , negate = true , asciiOnly = true ; break;
      case L'a': clazz.u = iswalpha, negate = false, asciiOnly = false; break;
      case L'A': clazz.u = iswalpha, negate = true , asciiOnly = false; break;
      case L'b': clazz.a = isalpha , negate = false, asciiOnly = true ; break;
      case L'B': clazz.a = isalpha , negate = true , asciiOnly = true ; break;
      case L'n': clazz.u = iswalnum, negate = false, asciiOnly = false; break;
      case L'N': clazz.u = iswalnum, negate = true , asciiOnly = false; break;
      case L'm': clazz.a = isalnum , negate = false, asciiOnly = true ; break;
      case L'M': clazz.a = isalnum , negate = true , asciiOnly = true ; break;
      case L'\\':clazz.a = iscntrl , negate = false, asciiOnly = true ; break;
      case L'~': clazz.a = iscntrl , negate = true , asciiOnly = true ; break;
      case L'0': clazz.a = isdigit , negate = false, asciiOnly = true ; break;
      case L'9': clazz.a = isdigit , negate = true , asciiOnly = true ; break;
      case L'x': clazz.a = isxdigit, negate = false, asciiOnly = true ; break;
      case L'X': clazz.a = isxdigit, negate = true , asciiOnly = true ; break;
      case L'.':
      case L'p': clazz.u = iswpunct, negate = false, asciiOnly = false; break;
      case L':':
      case L'P': clazz.u = iswpunct, negate = true , asciiOnly = false; break;
      case L',':
      case L'q': clazz.a = ispunct , negate = false, asciiOnly = true ; break;
      case L';':
      case L'Q': clazz.a = ispunct , negate = true , asciiOnly = true ; break;
      case L's':
      case L'_': clazz.u = iswspace, negate = false, asciiOnly = false; break;
      case L'S':
      case L'#': clazz.u = iswspace, negate = true , asciiOnly = false; break;
      case L'g': clazz.u = iswgraph, negate = false, asciiOnly = false; break;
      case L'G': clazz.u = iswgraph, negate = true , asciiOnly = false; break;
      case L'h': clazz.a = isgraph , negate = false, asciiOnly = true ; break;
      case L'H': clazz.a = isgraph , negate = true , asciiOnly = true ; break;
      case L'r': clazz.u = iswprint, negate = false, asciiOnly = false; break;
      case L'R': clazz.u = iswprint, negate = true , asciiOnly = false; break;
      /* Not 's' since people might expect it to be space. */
      case L't': clazz.a = isprint , negate = false, asciiOnly = true ; break;
      case L'T': clazz.a = isprint , negate = true , asciiOnly = true ; break;

      default:
        interp.error(wstring(L"Unknown character class: ") + clazzch,
                     text, clazzOffset);
        return ParseError;
      }

      //OK
      out = new StringClass(out, clazz.a, asciiOnly, negate, string);
      return ContinueParsing;
    }
  };

  static GlobalBinding<StringClassParser> _stringClassParser(L"str-is");

  class StringLength: public UnaryCommand {
  public:
    StringLength(Command* left, auto_ptr<Command>& sub)
    : UnaryCommand(left, sub) {}

    virtual bool exec(wstring& dst, Interpreter& interp) {
      wstring s;
      if (!interp.exec(s, sub.get())) return false;

      dst = intToStr(s.size());
      return true;
    }
  };

  static GlobalBinding<UnaryCommandParser<StringLength> >
  _stringLengthParser(L"str-len");
}
<|endoftext|>


<commit_before>// Copyright 2010-2012 RethinkDB, all rights reserved.
#ifndef CONFIG_ARGS_HPP_
#define CONFIG_ARGS_HPP_

#define KILOBYTE 1024LL
#define MEGABYTE (KILOBYTE * 1024LL)
#define GIGABYTE (MEGABYTE * 1024LL)
#define TERABYTE (GIGABYTE * 1024LL)

#define THOUSAND 1000LL
#define MILLION (THOUSAND * THOUSAND)
#define BILLION (THOUSAND * MILLION)

/*!
 * Version strings
 */

#define SOFTWARE_NAME_STRING "RethinkDB"
#define SERIALIZER_VERSION_STRING "1.8"

/**
 * Basic configuration parameters.
 */

// Defines the maximum size of the batch of IO events to process on
// each loop iteration. A larger number will increase throughput but
// decrease concurrency
#define MAX_IO_EVENT_PROCESSING_BATCH_SIZE        50

// The io batch factor ensures a minimum number of i/o operations
// which are picked from any specific i/o account consecutively.
// A higher value might be advantageous for throughput if seek times
// matter on the underlying i/o system. A low value improves latency.
// The advantage only holds as long as each account has a tendentially
// sequential set of i/o operations though. If access patterns are random
// for all accounts, a low io batch factor does just as well (as bad) when it comes
// to the number of random seeks, but might still provide a lower latency
// than a high batch factor. Our serializer writes usually generate a sequential
// access pattern and therefore take considerable advantage from a high io batch
// factor.
#define DEFAULT_IO_BATCH_FACTOR                   8

// Currently, each cache uses two IO accounts:
// one account for writes, and one account for reads.
// By adjusting the priorities of these accounts, reads
// can be prioritized over writes or the other way around.
//
// This is a one-per-serializer/file priority.
// The per-cache priorities are dynamically derived by dividing these priorities
// by the number of slices on a specific file.
#define CACHE_READS_IO_PRIORITY                   512
#define CACHE_WRITES_IO_PRIORITY                  64

// Garbage Colletion uses its own two IO accounts.
// There is one low-priority account that is meant to guarantee
// (performance-wise) unintrusive garbage collection.
// If the garbage ratio keeps growing,
// GC starts using the high priority account instead, which
// might have a negative influence on database performance
// under i/o heavy workloads but guarantees that the database
// doesn't grow indefinitely.
//
// This is a one-per-serializer/file priority.
#define GC_IO_PRIORITY_NICE                       8
#define GC_IO_PRIORITY_HIGH                       (4 * CACHE_WRITES_IO_PRIORITY)

// Size of the buffer used to perform IO operations (in bytes).
#define IO_BUFFER_SIZE                            (4 * KILOBYTE)

// Size of the device block size (in bytes)
#define DEVICE_BLOCK_SIZE                         512

// Size of each btree node (in bytes) on disk
#define DEFAULT_BTREE_BLOCK_SIZE                  (4 * KILOBYTE)

// Size of each extent (in bytes)
#define DEFAULT_EXTENT_SIZE                       (512 * KILOBYTE)

// Ratio of free ram to use for the cache by default
// TODO: DEFAULT_MAX_CACHE_RATIO is unused. Should it be deleted?
#define DEFAULT_MAX_CACHE_RATIO                   0.5

// Maximum number of threads we support
// TODO: make this dynamic where possible
#define MAX_THREADS                               128

// Ticks (in milliseconds) the internal timed tasks are performed at
#define TIMER_TICKS_IN_MS                         5

// How many milliseconds to allow changes to sit in memory before flushing to disk
#define DEFAULT_FLUSH_TIMER_MS                    1000

// If non-null disk_ack_signals are present, concurrent flushing can be used to reduce the
// latency of each single flush. max_concurrent_flushes controls how many flushes can be active
// on a specific slice at any given time.
#define DEFAULT_MAX_CONCURRENT_FLUSHES            1

// If more than this many bytes of dirty data accumulate in the cache, then write
// transactions will be throttled.  A value of 0 means that it will automatically be
// set to MAX_UNSAVED_DATA_LIMIT_FRACTION times the max cache size
#define DEFAULT_UNSAVED_DATA_LIMIT                (4096 * MEGABYTE)

// The unsaved data limit cannot exceed this fraction of the max cache size
#define MAX_UNSAVED_DATA_LIMIT_FRACTION           0.9

// We start flushing dirty pages as soon as we hit this fraction of the unsaved data limit
#define FLUSH_AT_FRACTION_OF_UNSAVED_DATA_LIMIT   0.2

// How many times the page replacement algorithm tries to find an eligible page before giving up.
// Note that (MAX_UNSAVED_DATA_LIMIT_FRACTION ** PAGE_REPL_NUM_TRIES) is the probability that the
// page replacement algorithm will succeed on a given try, and if that probability is less than 1/2
// then the page replacement algorithm will on average be unable to evict pages from the cache.
#define PAGE_REPL_NUM_TRIES                       10

// How large can the key be, in bytes?  This value needs to fit in a byte.
#define MAX_KEY_SIZE                              250

// Any values of this size or less will be directly stored in btree leaf nodes.
// Values greater than this size will be stored in overflow blocks. This value
// needs to fit in a byte.
#define MAX_IN_NODE_VALUE_SIZE                    250

// memcached specifies the maximum value size to be 1MB, but customers asked this to be much higher
#define MAX_VALUE_SIZE                            (10 * MEGABYTE)

// Values larger than this will be streamed in a get operation
#define MAX_BUFFERED_GET_SIZE                     MAX_VALUE_SIZE // streaming is too slow for now, so we disable it completely

// If a single connection sends this many 'noreply' commands, the next command will
// have to wait until the first one finishes
#define MAX_CONCURRENT_QUERIES_PER_CONNECTION     500

// The number of concurrent queries when loading memcached operations from a file.
#define MAX_CONCURRENT_QUEURIES_ON_IMPORT         1000

// How many timestamps we store in a leaf node.  We store the
// NUM_LEAF_NODE_EARLIER_TIMES+1 most-recent timestamps.
#define NUM_LEAF_NODE_EARLIER_TIMES               4

// Special block IDs.  These don't really belong here because they're
// more magic constants than tunable parameters.

// The btree superblock, which has a reference to the root node block
// id.
#define SUPERBLOCK_ID                             0

// The ratio at which we should start GCing.  (HEY: What's the extra
// 0.000001 in MAX_GC_HIGH_RATIO for?  Is it because we told the user
// that 0.99 was too high?)
#define DEFAULT_GC_HIGH_RATIO                     0.20
// TODO: MAX_GC_HIGH_RATIO is unused.  Use it!
// TODO: Probably this value is way too high.
//  - Keeping this around because if it becomes configurable again, we
//    should have these limits.  Before then at least rassert it.
#define MAX_GC_HIGH_RATIO                         0.990001

// The ratio at which we don't want to keep GC'ing.
#define DEFAULT_GC_LOW_RATIO                      0.15
// TODO: MIN_GC_LOW_RATIO is unused.  Use it!
//  - Keeping this around because if it becomes configurable again, we
//    should have these limits.  Before then at least rassert it.
#define MIN_GC_LOW_RATIO                          0.099999

// What's the maximum number of "young" extents we can have?
#define GC_YOUNG_EXTENT_MAX_SIZE                  50
// What's the definition of a "young" extent in microseconds?
#define GC_YOUNG_EXTENT_TIMELIMIT_MICROS          50000

// If the size of the LBA on a given disk exceeds LBA_MIN_SIZE_FOR_GC, then the fraction of the
// entries that are live and not garbage should be at least LBA_MIN_UNGARBAGE_FRACTION.
// TODO: Maybe change this back to 20 megabytes?
#define LBA_MIN_SIZE_FOR_GC                       (MEGABYTE * 1)
// TODO: This used to be 0.15 but we figured why not do the opposite of our well-tested parameter?
#define LBA_MIN_UNGARBAGE_FRACTION                0.85

// How many LBA structures to have for each file
// TODO: LBA_SHARD_FACTOR used to be 16.
#define LBA_SHARD_FACTOR                          4

// How many bytes of buffering space we can use per disk when reading the LBA. If it's set
// too high, then RethinkDB will eat a lot of memory at startup. This is bad because tcmalloc
// doesn't return memory to the OS. If it's set too low, startup will take a longer time.
#define LBA_READ_BUFFER_SIZE                      GIGABYTE

#define COROUTINE_STACK_SIZE                      131072

#define MAX_COROS_PER_THREAD                      10000

// Size of a cache line (used in cache_line_padded_t).
#define CACHE_LINE_SIZE                           64

#endif  // CONFIG_ARGS_HPP_

<commit_msg>Bump serializer version to 1.9<commit_after>// Copyright 2010-2012 RethinkDB, all rights reserved.
#ifndef CONFIG_ARGS_HPP_
#define CONFIG_ARGS_HPP_

#define KILOBYTE 1024LL
#define MEGABYTE (KILOBYTE * 1024LL)
#define GIGABYTE (MEGABYTE * 1024LL)
#define TERABYTE (GIGABYTE * 1024LL)

#define THOUSAND 1000LL
#define MILLION (THOUSAND * THOUSAND)
#define BILLION (THOUSAND * MILLION)

/*!
 * Version strings
 */

#define SOFTWARE_NAME_STRING "RethinkDB"
#define SERIALIZER_VERSION_STRING "1.9"

/**
 * Basic configuration parameters.
 */

// Defines the maximum size of the batch of IO events to process on
// each loop iteration. A larger number will increase throughput but
// decrease concurrency
#define MAX_IO_EVENT_PROCESSING_BATCH_SIZE        50

// The io batch factor ensures a minimum number of i/o operations
// which are picked from any specific i/o account consecutively.
// A higher value might be advantageous for throughput if seek times
// matter on the underlying i/o system. A low value improves latency.
// The advantage only holds as long as each account has a tendentially
// sequential set of i/o operations though. If access patterns are random
// for all accounts, a low io batch factor does just as well (as bad) when it comes
// to the number of random seeks, but might still provide a lower latency
// than a high batch factor. Our serializer writes usually generate a sequential
// access pattern and therefore take considerable advantage from a high io batch
// factor.
#define DEFAULT_IO_BATCH_FACTOR                   8

// Currently, each cache uses two IO accounts:
// one account for writes, and one account for reads.
// By adjusting the priorities of these accounts, reads
// can be prioritized over writes or the other way around.
//
// This is a one-per-serializer/file priority.
// The per-cache priorities are dynamically derived by dividing these priorities
// by the number of slices on a specific file.
#define CACHE_READS_IO_PRIORITY                   512
#define CACHE_WRITES_IO_PRIORITY                  64

// Garbage Colletion uses its own two IO accounts.
// There is one low-priority account that is meant to guarantee
// (performance-wise) unintrusive garbage collection.
// If the garbage ratio keeps growing,
// GC starts using the high priority account instead, which
// might have a negative influence on database performance
// under i/o heavy workloads but guarantees that the database
// doesn't grow indefinitely.
//
// This is a one-per-serializer/file priority.
#define GC_IO_PRIORITY_NICE                       8
#define GC_IO_PRIORITY_HIGH                       (4 * CACHE_WRITES_IO_PRIORITY)

// Size of the buffer used to perform IO operations (in bytes).
#define IO_BUFFER_SIZE                            (4 * KILOBYTE)

// Size of the device block size (in bytes)
#define DEVICE_BLOCK_SIZE                         512

// Size of each btree node (in bytes) on disk
#define DEFAULT_BTREE_BLOCK_SIZE                  (4 * KILOBYTE)

// Size of each extent (in bytes)
#define DEFAULT_EXTENT_SIZE                       (512 * KILOBYTE)

// Ratio of free ram to use for the cache by default
// TODO: DEFAULT_MAX_CACHE_RATIO is unused. Should it be deleted?
#define DEFAULT_MAX_CACHE_RATIO                   0.5

// Maximum number of threads we support
// TODO: make this dynamic where possible
#define MAX_THREADS                               128

// Ticks (in milliseconds) the internal timed tasks are performed at
#define TIMER_TICKS_IN_MS                         5

// How many milliseconds to allow changes to sit in memory before flushing to disk
#define DEFAULT_FLUSH_TIMER_MS                    1000

// If non-null disk_ack_signals are present, concurrent flushing can be used to reduce the
// latency of each single flush. max_concurrent_flushes controls how many flushes can be active
// on a specific slice at any given time.
#define DEFAULT_MAX_CONCURRENT_FLUSHES            1

// If more than this many bytes of dirty data accumulate in the cache, then write
// transactions will be throttled.  A value of 0 means that it will automatically be
// set to MAX_UNSAVED_DATA_LIMIT_FRACTION times the max cache size
#define DEFAULT_UNSAVED_DATA_LIMIT                (4096 * MEGABYTE)

// The unsaved data limit cannot exceed this fraction of the max cache size
#define MAX_UNSAVED_DATA_LIMIT_FRACTION           0.9

// We start flushing dirty pages as soon as we hit this fraction of the unsaved data limit
#define FLUSH_AT_FRACTION_OF_UNSAVED_DATA_LIMIT   0.2

// How many times the page replacement algorithm tries to find an eligible page before giving up.
// Note that (MAX_UNSAVED_DATA_LIMIT_FRACTION ** PAGE_REPL_NUM_TRIES) is the probability that the
// page replacement algorithm will succeed on a given try, and if that probability is less than 1/2
// then the page replacement algorithm will on average be unable to evict pages from the cache.
#define PAGE_REPL_NUM_TRIES                       10

// How large can the key be, in bytes?  This value needs to fit in a byte.
#define MAX_KEY_SIZE                              250

// Any values of this size or less will be directly stored in btree leaf nodes.
// Values greater than this size will be stored in overflow blocks. This value
// needs to fit in a byte.
#define MAX_IN_NODE_VALUE_SIZE                    250

// memcached specifies the maximum value size to be 1MB, but customers asked this to be much higher
#define MAX_VALUE_SIZE                            (10 * MEGABYTE)

// Values larger than this will be streamed in a get operation
#define MAX_BUFFERED_GET_SIZE                     MAX_VALUE_SIZE // streaming is too slow for now, so we disable it completely

// If a single connection sends this many 'noreply' commands, the next command will
// have to wait until the first one finishes
#define MAX_CONCURRENT_QUERIES_PER_CONNECTION     500

// The number of concurrent queries when loading memcached operations from a file.
#define MAX_CONCURRENT_QUEURIES_ON_IMPORT         1000

// How many timestamps we store in a leaf node.  We store the
// NUM_LEAF_NODE_EARLIER_TIMES+1 most-recent timestamps.
#define NUM_LEAF_NODE_EARLIER_TIMES               4

// Special block IDs.  These don't really belong here because they're
// more magic constants than tunable parameters.

// The btree superblock, which has a reference to the root node block
// id.
#define SUPERBLOCK_ID                             0

// The ratio at which we should start GCing.  (HEY: What's the extra
// 0.000001 in MAX_GC_HIGH_RATIO for?  Is it because we told the user
// that 0.99 was too high?)
#define DEFAULT_GC_HIGH_RATIO                     0.20
// TODO: MAX_GC_HIGH_RATIO is unused.  Use it!
// TODO: Probably this value is way too high.
//  - Keeping this around because if it becomes configurable again, we
//    should have these limits.  Before then at least rassert it.
#define MAX_GC_HIGH_RATIO                         0.990001

// The ratio at which we don't want to keep GC'ing.
#define DEFAULT_GC_LOW_RATIO                      0.15
// TODO: MIN_GC_LOW_RATIO is unused.  Use it!
//  - Keeping this around because if it becomes configurable again, we
//    should have these limits.  Before then at least rassert it.
#define MIN_GC_LOW_RATIO                          0.099999

// What's the maximum number of "young" extents we can have?
#define GC_YOUNG_EXTENT_MAX_SIZE                  50
// What's the definition of a "young" extent in microseconds?
#define GC_YOUNG_EXTENT_TIMELIMIT_MICROS          50000

// If the size of the LBA on a given disk exceeds LBA_MIN_SIZE_FOR_GC, then the fraction of the
// entries that are live and not garbage should be at least LBA_MIN_UNGARBAGE_FRACTION.
// TODO: Maybe change this back to 20 megabytes?
#define LBA_MIN_SIZE_FOR_GC                       (MEGABYTE * 1)
// TODO: This used to be 0.15 but we figured why not do the opposite of our well-tested parameter?
#define LBA_MIN_UNGARBAGE_FRACTION                0.85

// How many LBA structures to have for each file
// TODO: LBA_SHARD_FACTOR used to be 16.
#define LBA_SHARD_FACTOR                          4

// How many bytes of buffering space we can use per disk when reading the LBA. If it's set
// too high, then RethinkDB will eat a lot of memory at startup. This is bad because tcmalloc
// doesn't return memory to the OS. If it's set too low, startup will take a longer time.
#define LBA_READ_BUFFER_SIZE                      GIGABYTE

#define COROUTINE_STACK_SIZE                      131072

#define MAX_COROS_PER_THREAD                      10000

// Size of a cache line (used in cache_line_padded_t).
#define CACHE_LINE_SIZE                           64

#endif  // CONFIG_ARGS_HPP_

<|endoftext|>