<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
        (  2, uint256("0x10d4802af87f85f14b3b7a7e5e020b81a0ed6e4b5e0116896c56eeeaf41b51d5"))
        (  175, uint256("0x73f761da8b931b94cf859b2d92735d21a24b37ec38726f2b3a84a69912321f7d"))
        (  2514, uint256("0x65b27d0776f3b4e0ee7f0c2aebbbe2e4fde76562055020b52b83f57b65852993"))
        (  10000, uint256("0xdc3f0a0a92234b0cc8b4f119d7c66361c26f21e32b34acb985e377fd34177845"))
        (  14000, uint256("0xf212c722a182163fdfcc8574450d70701ad97cd3023784b7d599bc5bfe2a617d"))
        ;
    static const CCheckpointData data = {
        &mapCheckpoints,
        1392932604, // * UNIX timestamp of last checkpoint block
        500,        // * total number of transactions between genesis and last checkpoint
                    //   (the tx=... number in the SetBestChain debug.log lines)
        8000.0      // * estimated number of transactions per day after checkpoint
    };

    static MapCheckpoints mapCheckpointsTestnet =
        boost::assign::map_list_of
        (   546, uint256("000000002a936ca763904c3c35fce2f3556c559c0214345d31b1bcebf76acb70"))
        ( 35000, uint256("2af959ab4f12111ce947479bfcef16702485f04afd95210aa90fde7d1e4a64ad"))
        ;
    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>checkpoint update after coin destruction<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
        (  2, uint256("0x10d4802af87f85f14b3b7a7e5e020b81a0ed6e4b5e0116896c56eeeaf41b51d5"))
        (  175, uint256("0x73f761da8b931b94cf859b2d92735d21a24b37ec38726f2b3a84a69912321f7d"))
        (  2514, uint256("0x65b27d0776f3b4e0ee7f0c2aebbbe2e4fde76562055020b52b83f57b65852993"))
        (  10000, uint256("0xdc3f0a0a92234b0cc8b4f119d7c66361c26f21e32b34acb985e377fd34177845"))
        (  14000, uint256("0xf212c722a182163fdfcc8574450d70701ad97cd3023784b7d599bc5bfe2a617d"))
        (  30000, uint256("0x095d507ae4c069e568f8718cc4202ca5aab5fa6e9429b9495e3b17bb32c12374"))
        (  39500, uint256("0x650be7fe1a4c0fd4f308e58c2ca784ec19ba3b25fde9b040fa6356984aea1295"))
        ;
    static const CCheckpointData data = {
        &mapCheckpoints,
        1401745601, // * UNIX timestamp of last checkpoint block
        500,        // * total number of transactions between genesis and last checkpoint
                    //   (the tx=... number in the SetBestChain debug.log lines)
        8000.0      // * estimated number of transactions per day after checkpoint
    };

    static MapCheckpoints mapCheckpointsTestnet =
        boost::assign::map_list_of
        (   546, uint256("000000002a936ca763904c3c35fce2f3556c559c0214345d31b1bcebf76acb70"))
        ( 35000, uint256("2af959ab4f12111ce947479bfcef16702485f04afd95210aa90fde7d1e4a64ad"))
        ;
    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;
    }
}
<|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;

    //
    // 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("0x00000000804bbc6a621a9dbb564ce469f492e1ccf2d70f8a6b241e26a277afa2"))
        (    1, uint256("0x000000000fbc1c60a7610c894f98d102390e9e00cc18caced4eb4198ec0c3645"))
        (   31, uint256("0x00000000045341e3ebdfa180e4a0f1e4da23829609517a3673b4a796714a7593"))
        (  104, uint256("0x000000006afe30806352f2015829527dd91f19fbc2d28f799c3ad61c37746fdb"))
        (  355, uint256("0x0000000000c0e178ddd6a8f15724f37470428c233883c302267299b21fb5d237"))
        (  721, uint256("0x00000000027671a417f3d3eafac6d150f0b2ccba37f0b63f75bc657ec25950ed"))
        ( 2000, uint256("0x000000000283ecd683fe30d4542929a78873df7818029793f84e9c65dc337d94"))
        ( 3000, uint256("0x0000000000317b69ff2a56284442fede7ffa66f75d000f1cf34171ad671db4b6"))
        ( 4000, uint256("0x00000000001190cad5d66d028b6afcf22db58d2b5c17abf2bf2e1353be13097d"))
        ( 4255, uint256("0x000000000018b3ba5b241f3e88b4a88e580f9e7dd0fc7fc786ff22c586e53dd9"))
        ( 5631, uint256("0x00000000001243509866938e344c0010bd88b156da27ef9d707cb1f1698f2a32"))
        ( 6000, uint256("0x00000000000c1abfd7c29d07e23ef52631c6874e42e6a240a4d3678d9c716d81"))
        ( 7395, uint256("0x0000000000005d8e1281d6b28fe6b504ab81e7e3ec561e97b7a98973e449f7fb"))
        ( 8001, uint256("0x00000000001ca63707536b6dfc8ba4c5aa7fce19b6295ef73e195554cdb92d44"))
        ( 8157, uint256("0x00000000001303998da2714abf02159f1421103e77fee3b876d69c0fa7b108d9"))
        (12311, uint256("0x00000000002b5708fefdceb5db42cd2135eaf23f23a95c285e8f310262f8d639"))
        (13224, uint256("0x00000000000765c69f777ccbc44fab23edab9126f1b4ec5078450aebc3809c36"))
        (14401, uint256("0x0000000000388541b88c57883a480fd6cfa7b93f68e0c71538b08b2c4d875fa2"))
        (15238, uint256("0x000000000000ae09d46bc1a9c5ca4c7b5e51bf23d3108926daa140d64355d390"))
        (18426, uint256("0x00000000001fb1c075dbfa27f7ba83928a2d35152ccae59c742f698fb8cb8108"))
        (19114, uint256("0x000000000022224f57adecffdc8f5cffb3b932838310aefdd12aaabcc6122259"))
        (20124, uint256("0x00000000002374e0e1fcee28b520dff3f3e86cb7ff7afdea112aaf2002101900"))
        (21711, uint256("0x00000000002189b0ae139b8c449bbcb99d520b8a798b7e0f0ff8ab8539e9bcb4"))
        (22100, uint256("0x0000000000142ace7d8db003da69191896986c5564e604e3100d14c17daaf90f"))
        ;

    static MapCheckpoints mapCheckpointsTestnet =
        boost::assign::map_list_of
        ( 546, uint256("000000002a936ca763904c3c35fce2f3556c559c0214345d31b1bcebf76acb70"))
        ;

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

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

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

        return checkpoints.rbegin()->first;
    }

    CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
    {
        MapCheckpoints& checkpoints = (fTestNet ? 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;
    }
}
<commit_msg>[checkpoints] minor: 22566 checkpoint added.<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;

    //
    // 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("0x00000000804bbc6a621a9dbb564ce469f492e1ccf2d70f8a6b241e26a277afa2"))
        (    1, uint256("0x000000000fbc1c60a7610c894f98d102390e9e00cc18caced4eb4198ec0c3645"))
        (   31, uint256("0x00000000045341e3ebdfa180e4a0f1e4da23829609517a3673b4a796714a7593"))
        (  104, uint256("0x000000006afe30806352f2015829527dd91f19fbc2d28f799c3ad61c37746fdb"))
        (  355, uint256("0x0000000000c0e178ddd6a8f15724f37470428c233883c302267299b21fb5d237"))
        (  721, uint256("0x00000000027671a417f3d3eafac6d150f0b2ccba37f0b63f75bc657ec25950ed"))
        ( 2000, uint256("0x000000000283ecd683fe30d4542929a78873df7818029793f84e9c65dc337d94"))
        ( 3000, uint256("0x0000000000317b69ff2a56284442fede7ffa66f75d000f1cf34171ad671db4b6"))
        ( 4000, uint256("0x00000000001190cad5d66d028b6afcf22db58d2b5c17abf2bf2e1353be13097d"))
        ( 4255, uint256("0x000000000018b3ba5b241f3e88b4a88e580f9e7dd0fc7fc786ff22c586e53dd9"))
        ( 5631, uint256("0x00000000001243509866938e344c0010bd88b156da27ef9d707cb1f1698f2a32"))
        ( 6000, uint256("0x00000000000c1abfd7c29d07e23ef52631c6874e42e6a240a4d3678d9c716d81"))
        ( 7395, uint256("0x0000000000005d8e1281d6b28fe6b504ab81e7e3ec561e97b7a98973e449f7fb"))
        ( 8001, uint256("0x00000000001ca63707536b6dfc8ba4c5aa7fce19b6295ef73e195554cdb92d44"))
        ( 8157, uint256("0x00000000001303998da2714abf02159f1421103e77fee3b876d69c0fa7b108d9"))
        (12311, uint256("0x00000000002b5708fefdceb5db42cd2135eaf23f23a95c285e8f310262f8d639"))
        (13224, uint256("0x00000000000765c69f777ccbc44fab23edab9126f1b4ec5078450aebc3809c36"))
        (14401, uint256("0x0000000000388541b88c57883a480fd6cfa7b93f68e0c71538b08b2c4d875fa2"))
        (15238, uint256("0x000000000000ae09d46bc1a9c5ca4c7b5e51bf23d3108926daa140d64355d390"))
        (18426, uint256("0x00000000001fb1c075dbfa27f7ba83928a2d35152ccae59c742f698fb8cb8108"))
        (19114, uint256("0x000000000022224f57adecffdc8f5cffb3b932838310aefdd12aaabcc6122259"))
        (20124, uint256("0x00000000002374e0e1fcee28b520dff3f3e86cb7ff7afdea112aaf2002101900"))
        (21711, uint256("0x00000000002189b0ae139b8c449bbcb99d520b8a798b7e0f0ff8ab8539e9bcb4"))
        (22100, uint256("0x0000000000142ace7d8db003da69191896986c5564e604e3100d14c17daaf90f"))
        (22566, uint256("0x00000000000c28dc052d277d18e104e4e63c53e4018273b3af49f772af205d43"))
        ;

    static MapCheckpoints mapCheckpointsTestnet =
        boost::assign::map_list_of
        ( 546, uint256("000000002a936ca763904c3c35fce2f3556c559c0214345d31b1bcebf76acb70"))
        ;

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

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

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

        return checkpoints.rbegin()->first;
    }

    CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
    {
        MapCheckpoints& checkpoints = (fTestNet ? 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;
    }
}
<|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;

    //
    // 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
        ( 11111, uint256("0x0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d"))
        ( 33333, uint256("0x000000002dd5588a74784eaa7ab0507a18ad16a236e7b1ce69f00d7ddfb5d0a6"))
        ( 74000, uint256("0x0000000000573993a3c9e41ce34471c079dcf5f52a0e824a81e7f953b8661a20"))
        (105000, uint256("0x00000000000291ce28027faea320c8d2b054b2e0fe44a773f3eefb151d6bdc97"))
        (134444, uint256("0x00000000000005b12ffd4cd315cd34ffd4a594f430ac814c91184a0d42d2b0fe"))
        (168000, uint256("0x000000000000099e61ea72015e79632f216fe6cb33d7899acb35b75c8303b763"))
        (185333, uint256("0x00000000000002334c71b8706940c20348af897a9cfc0f1a6dab0d14d4ceb815"))
        ;

    static MapCheckpoints mapCheckpointsTestnet =
        boost::assign::map_list_of
        ( 546, uint256("000000002a936ca763904c3c35fce2f3556c559c0214345d31b1bcebf76acb70"))
        ;

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

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

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

        return checkpoints.rbegin()->first;
    }

    CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
    {
        MapCheckpoints& checkpoints = (fTestNet ? 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;
    }
}
<commit_msg>Checkpoint at block 193,000<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;

    //
    // 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
        ( 11111, uint256("0x0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d"))
        ( 33333, uint256("0x000000002dd5588a74784eaa7ab0507a18ad16a236e7b1ce69f00d7ddfb5d0a6"))
        ( 74000, uint256("0x0000000000573993a3c9e41ce34471c079dcf5f52a0e824a81e7f953b8661a20"))
        (105000, uint256("0x00000000000291ce28027faea320c8d2b054b2e0fe44a773f3eefb151d6bdc97"))
        (134444, uint256("0x00000000000005b12ffd4cd315cd34ffd4a594f430ac814c91184a0d42d2b0fe"))
        (168000, uint256("0x000000000000099e61ea72015e79632f216fe6cb33d7899acb35b75c8303b763"))
        (193000, uint256("0x000000000000059f452a5f7340de6682a977387c17010ff6e6c3bd83ca8b1317"))
        ;

    static MapCheckpoints mapCheckpointsTestnet =
        boost::assign::map_list_of
        ( 546, uint256("000000002a936ca763904c3c35fce2f3556c559c0214345d31b1bcebf76acb70"))
        ;

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

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

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

        return checkpoints.rbegin()->first;
    }

    CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
    {
        MapCheckpoints& checkpoints = (fTestNet ? 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;
    }
}
<|endoftext|>


<commit_before>// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2011-2012 Litecoin Developers
// Copyright (c) 2013 Bells 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
    //

	// no checkpoint now, can be added in later releases
    static MapCheckpoints mapCheckpoints =
            boost::assign::map_list_of
            (  0, uint256("0xe5be24df57c43a82d15c2f06bda961296948f8f8eb48501bed1efb929afe0698"))
			;

    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;
		// return true;
    }

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

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

    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;
        }
        return NULL;
    }
}
<commit_msg>Update checkpoints.cpp<commit_after>// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2011-2012 Litecoin Developers
// Copyright (c) 2013 Bells 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
    //

	// no checkpoint now, can be added in later releases
    static MapCheckpoints mapCheckpoints =
            boost::assign::map_list_of
            (  0, uint256("0xe5be24df57c43a82d15c2f06bda961296948f8f8eb48501bed1efb929afe0698"))
            (  1000, uint256("0xbda6660ca8dedd6205bf1afd68b1ee0479c293899d308325bbf921adaeafc459"))
            (  10000, uint256("0x6672369ac18c1597d9d062b10847cc92d6fba6218a63291f258450bae789f774"))
            (  25000, uint256("0x2910fc9061c1d458b3104fc7cb3fa3c23dbc8370af203c683a5d09e2f062c0cd"))
            (  50000, uint256("0xee8a74953afdae365ec3d2bc003590b594bd51b2f10e25be5d1960f1e12c6609"))
            (  75000, uint256("0x133b93343f032c06dcbd4b2607f0427fca1a1940279b9d1f9ef1475a37862f9e"))
            (  100000, uint256("0x707c4d80b012f540d1ee4021ad4214a187e7197504f5a0b67b4ae87e2491ff4c"))
            (  110000, uint256("0x4e903f691d8434af6a81091e2ddd832fd74aefd5acc79837bc605b183ddffdb3"))
            (  125000, uint256("0xddc37d2f69cc22dd3ffe482442821cee466b899fa706081bc7f425ab66761f26"))
            (  134000, uint256("0x951580c3396b2058eb8f38cde780dc57cf2ec511b954a18f54beb8f4652df35f"))
			;

    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;
		// return true;
    }

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

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

    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;
        }
        return NULL;
    }
}
<|endoftext|>


<commit_before>// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2013-2014 The Dogecoin developers
// Copyright (c)      2014 The Inutoshi 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<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 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
        (     0, uint256("0x1a91e3dace36e2be3bf030a65679fe821aa1d6ef92e7c9902eb318182c355691"))
        ( 42279, uint256("0x8444c3ef39a46222e87584ef956ad2c9ef401578bd8b51e8e4b9a86ec3134d3a"))
        ( 42400, uint256("0x557bb7c17ed9e6d4a6f9361cfddf7c1fc0bdc394af7019167442b41f507252b4"))
        ( 104679, uint256("0x35eb87ae90d44b98898fec8c39577b76cb1eb08e1261cfc10706c8ce9a1d01cf"))
        ( 128370, uint256("0x3f9265c94cab7dc3bd6a2ad2fb26c8845cb41cff437e0a75ae006997b4974be6"))
        ( 145000, uint256("0xcc47cae70d7c5c92828d3214a266331dde59087d4a39071fa76ddfff9b7bde72"))
        ( 165393, uint256("0x7154efb4009e18c1c6a6a79fc6015f48502bcd0a1edd9c20e44cd7cbbe2eeef1"))
        ( 186774, uint256("0x3c712c49b34a5f34d4b963750d6ba02b73e8a938d2ee415dcda141d89f5cb23a"))
        ( 199992, uint256("0x3408ff829b7104eebaf61fd2ba2203ef2a43af38b95b353e992ef48f00ebb190"))
        ( 225000, uint256("be148d9c5eab4a33392a6367198796784479720d06bfdd07bd547fe934eea15a"))
        ( 250000, uint256("0e4bcfe8d970979f7e30e2809ab51908d435677998cf759169407824d4f36460"))
        ( 270639, uint256("c587a36dd4f60725b9dd01d99694799bef111fc584d659f6756ab06d2a90d911"))
        ( 299742, uint256("1cc89c0c8a58046bf0222fe131c099852bd9af25a80e07922918ef5fb39d6742"))
        ( 323141, uint256("60c9f919f9b271add6ef5671e9538bad296d79f7fdc6487ba702bf2ba131d31d"))
        ( 339202, uint256("8c29048df5ae9df38a67ea9470fdd404d281a3a5c6f33080cd5bf14aa496ab03"))
        ;
    static const CCheckpointData data = {
        &mapCheckpoints,
        1408192466, // * UNIX timestamp of last checkpoint block
        11177651,   // * total number of transactions between genesis and last checkpoint
                    //   (the tx=... number in the SetBestChain debug.log lines)
        20000.0     // * estimated number of transactions per day after checkpoint
    };

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

    static MapCheckpoints mapCheckpointsRegtest =
        boost::assign::map_list_of
        ( 0, uint256("3d2160a3b5dc4a9d62e7e66a295f70313ac808440ef7400d6c0772171ce973a5"))
        ;
    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(int nHeight, const uint256& 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)/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 (!fEnabled)
            return 0;

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

        return checkpoints.rbegin()->first;
    }

    CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
    {
        if (!fEnabled)
            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>Add checkpoints for 371,337 and 400,000 blocks, as well as intermediary blocks.<commit_after>// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2013-2014 The Dogecoin developers
// Copyright (c)      2014 The Inutoshi 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<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 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
        (     0, uint256("0x1a91e3dace36e2be3bf030a65679fe821aa1d6ef92e7c9902eb318182c355691"))
        ( 42279, uint256("0x8444c3ef39a46222e87584ef956ad2c9ef401578bd8b51e8e4b9a86ec3134d3a"))
        ( 42400, uint256("0x557bb7c17ed9e6d4a6f9361cfddf7c1fc0bdc394af7019167442b41f507252b4"))
        ( 104679, uint256("0x35eb87ae90d44b98898fec8c39577b76cb1eb08e1261cfc10706c8ce9a1d01cf"))
        ( 128370, uint256("0x3f9265c94cab7dc3bd6a2ad2fb26c8845cb41cff437e0a75ae006997b4974be6"))
        ( 145000, uint256("0xcc47cae70d7c5c92828d3214a266331dde59087d4a39071fa76ddfff9b7bde72"))
        ( 165393, uint256("0x7154efb4009e18c1c6a6a79fc6015f48502bcd0a1edd9c20e44cd7cbbe2eeef1"))
        ( 186774, uint256("0x3c712c49b34a5f34d4b963750d6ba02b73e8a938d2ee415dcda141d89f5cb23a"))
        ( 199992, uint256("0x3408ff829b7104eebaf61fd2ba2203ef2a43af38b95b353e992ef48f00ebb190"))
        ( 225000, uint256("be148d9c5eab4a33392a6367198796784479720d06bfdd07bd547fe934eea15a"))
        ( 250000, uint256("0e4bcfe8d970979f7e30e2809ab51908d435677998cf759169407824d4f36460"))
        ( 270639, uint256("c587a36dd4f60725b9dd01d99694799bef111fc584d659f6756ab06d2a90d911"))
        ( 299742, uint256("1cc89c0c8a58046bf0222fe131c099852bd9af25a80e07922918ef5fb39d6742"))
        ( 323141, uint256("60c9f919f9b271add6ef5671e9538bad296d79f7fdc6487ba702bf2ba131d31d"))
        ( 339202, uint256("8c29048df5ae9df38a67ea9470fdd404d281a3a5c6f33080cd5bf14aa496ab03"))
        ( 350000, uint256("2bdcba23a47049e69c4fec4c425462e30f3d21d25223bde0ed36be4ea59a7075"))
	( 370005, uint256("7be5af2c5bdcb79047dcd691ef613b82d4f1c20835677daed936de37a4782e15"))
	( 371337, uint256("60323982f9c5ff1b5a954eac9dc1269352835f47c2c5222691d80f0d50dcf053"))
	( 400002, uint256("a5021d69a83f39aef10f3f24f932068d6ff322c654d20562def3fac5703ce3aa"))
        ;
    static const CCheckpointData data = {
        &mapCheckpoints,
        1412259032, // * UNIX timestamp of last checkpoint block
        12371456,   // * total number of transactions between genesis and last checkpoint
                    //   (the tx=... number in the SetBestChain debug.log lines)
        29000.0     // * estimated number of transactions per day after checkpoint
    };

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

    static MapCheckpoints mapCheckpointsRegtest =
        boost::assign::map_list_of
        ( 0, uint256("3d2160a3b5dc4a9d62e7e66a295f70313ac808440ef7400d6c0772171ce973a5"))
        ;
    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(int nHeight, const uint256& 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)/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 (!fEnabled)
            return 0;

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

        return checkpoints.rbegin()->first;
    }

    CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
    {
        if (!fEnabled)
            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
// Copyright (c) 2011-2012 Litecoin Developers
// Copyright (c) 2013 realcoin 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("0xd6b2bcbb7ce7d97f531c7e9b8cd4360b9d0e552c21ba82862cfe6bb28acd0809"))
            (     1, uint256("0x9f4cb7a5e5b91c948306ad84e2a604fe328fb744c2e802eaa84344a61ee0ba00"))
            (     20, uint256("0xb9c6a17a8a97c2f35add8167ebdec555eae5a066ccab284bfe1e629d6f1aada9"))
            (     100, uint256("0x8715ab51d8d22997f07277c5f6a3cb60ea63ccd70e017b7c1d7c5180520e56c3"))
            (     1080, uint256("0x3ac628565248bbddfb98dcc71e710f7cf634c150ca87c35a99ef42f9a58235d4"))
            (     5000, uint256("0xdfb3f4b4b115b4408df4e1b6b625eb99f83ec050e526248c3fdc978da3b2bca6"))
            (     10000, uint256("0xdc751be1cc08013f1d418095e6a853e1c51bdc7b3c2fec4bea788532bd07903e"))
            (     20000, uint256("0x0ae3e8b453eb3fda766d8fb542d815f45a717dc0c7ab1974d61882413ed429d8"))
            (     30000, uint256("0x595bdfadfba6a96bc8daedad3fdfa0c58b95d73a0203c9600277b87ee614a803"))
            (     38628, uint256("0x297b187c764214c6bf6208941b9a5a7d0f2f8b2730f660800c02a366637db9bd"))
            ;

    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;
        //return true;
    }

    int GetTotalBlocksEstimate()
    {
        if (fTestNet) return 0;
        return mapCheckpoints.rbegin()->first;
        //return 0;
    }

    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;
        }
        return NULL;
    }
}
<commit_msg>1.0.0.2<commit_after>// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2011-2012 Litecoin Developers
// Copyright (c) 2013 realcoin 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("0xd6b2bcbb7ce7d97f531c7e9b8cd4360b9d0e552c21ba82862cfe6bb28acd0809"))
            (     1, uint256("0x9f4cb7a5e5b91c948306ad84e2a604fe328fb744c2e802eaa84344a61ee0ba00"))
            (     20, uint256("0xb9c6a17a8a97c2f35add8167ebdec555eae5a066ccab284bfe1e629d6f1aada9"))
            (     100, uint256("0x8715ab51d8d22997f07277c5f6a3cb60ea63ccd70e017b7c1d7c5180520e56c3"))
            (     1080, uint256("0x3ac628565248bbddfb98dcc71e710f7cf634c150ca87c35a99ef42f9a58235d4"))
            (     5000, uint256("0xdfb3f4b4b115b4408df4e1b6b625eb99f83ec050e526248c3fdc978da3b2bca6"))
            (     10000, uint256("0xdc751be1cc08013f1d418095e6a853e1c51bdc7b3c2fec4bea788532bd07903e"))
            (     20000, uint256("0x0ae3e8b453eb3fda766d8fb542d815f45a717dc0c7ab1974d61882413ed429d8"))
            (     30000, uint256("0x595bdfadfba6a96bc8daedad3fdfa0c58b95d73a0203c9600277b87ee614a803"))
            (     38628, uint256("0x297b187c764214c6bf6208941b9a5a7d0f2f8b2730f660800c02a366637db9bd"))
            ;

    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;
        //return true;
    }

    int GetTotalBlocksEstimate()
    {
        if (fTestNet) return 0;
        //return mapCheckpoints.rbegin()->first;
        return 0;
    }

    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;
        }
        return NULL;
    }
}
<|endoftext|>


<commit_before>#define BOOST_TEST_MODULE metrics test
#include <boost/test/unit_test.hpp>
#include "ten/metrics.hh"
#include "ten/task.hh"
#include <thread>
#include <atomic>

#include "ten/ewma.hh"

using namespace ten;

void my_thread() {
#if 1
    metrics::record()
        //.incr<metrics::counter>("thing")
        .counter("thing").incr();
        ;
#else
    metrics::record([](metrics::group &g) {
        get<metrics::counter>(g, "thing").incr();
    });
#endif
}

static const int nthreads = 100;

BOOST_AUTO_TEST_CASE(ten_init) {
    kernel::boot(); // init logging etc
}

BOOST_AUTO_TEST_CASE(thread_local_test) {
    using namespace metrics;

    std::vector<std::thread> threads(nthreads);
    for (auto &i : threads) {
        i = std::thread(my_thread);
    }

    {
        auto mg = global.aggregate();
        for (auto kv : mg)
            DVLOG(1) << "metric: " << kv.first << " = " << boost::apply_visitor(json_visitor(), kv.second);
    }

    for (auto &i : threads) {
        i.join();
    }

    auto mg = global.aggregate();

    BOOST_CHECK_EQUAL(nthreads, value<counter>(mg, "thing"));
    for (auto kv : mg) {
        DVLOG(1) << "metric: " << kv.first << " = " << boost::apply_visitor(json_visitor(), kv.second);
    }
}

BOOST_AUTO_TEST_CASE(timer_test) {
    using namespace metrics;
    using namespace std::chrono;
    time_op to("timer1");
    usleep(5*1000);
    to.stop();
    auto mg = global.aggregate();
    auto v = value<timer>(mg, "timer1");
    // value type is a duration of unspecified resolution
    BOOST_CHECK(duration_cast<seconds     >(v).count() == 0);
    BOOST_CHECK(duration_cast<milliseconds>(v).count() >= 5);
    BOOST_CHECK(duration_cast<microseconds>(v).count() >= 5000);
}

BOOST_AUTO_TEST_CASE(ewma_test) {
    using namespace std::chrono;
    ewma<seconds> m1(seconds{1});
    ewma<seconds> m5(seconds{5});
    ewma<seconds> m60(seconds{60});

    for (unsigned i=0; i<60*5; ++i) {
        m1.update(10);
        m1.tick();
        m5.update(10);
        m5.tick();
        m60.update(10);
        m60.tick();
    }
    LOG(INFO) << "rate1: "  << m1.rate()  << "/s, " << m1.rate<minutes>()  << "/m";
    LOG(INFO) << "rate5: "  << m5.rate()  << "/s, " << m5.rate<minutes>()  << "/m";
    LOG(INFO) << "rate60: " << m60.rate() << "/s, " << m60.rate<minutes>() << "/m";

    BOOST_CHECK_CLOSE(10.0, m1.rate(), 60.0);
    BOOST_CHECK_CLOSE(10.0, m5.rate(), 11.0);
    BOOST_CHECK_CLOSE(10.0, m60.rate(), 2.0);

    for (unsigned i=0; i<60; ++i) {
        m1.tick();
        m5.tick();
        m60.tick();
    }

    LOG(INFO) << "rate1: "  << m1.rate()  << "/s, " << m1.rate<minutes>()  << "/m";
    LOG(INFO) << "rate5: "  << m5.rate()  << "/s, " << m5.rate<minutes>()  << "/m";
    LOG(INFO) << "rate60: " << m60.rate() << "/s, " << m60.rate<minutes>() << "/m";

    BOOST_CHECK_CLOSE(0.0, std::round(m1.rate()), 1.0);
    BOOST_CHECK_CLOSE(0.0, std::round(m5.rate()), 1.0);
    BOOST_CHECK_CLOSE(4.0, std::round(m60.rate()), 1.0);
}

BOOST_AUTO_TEST_CASE(interval_test) {
    task::main([] {
        using namespace metrics;
        using namespace std::chrono;

        // TODO: intervals internals are in seconds, else we could use e.g. 50ms here.
        constexpr seconds tick{1};
        intervals iv(tick, 2);

        // put all test events into the middle of the collection window
        this_task::sleep_for(duration_cast<milliseconds>(tick) / 2);

        std::thread bg([] {
            for (auto n : { 1, 1 }) {
                std::this_thread::sleep_for(tick);
                BOOST_MESSAGE("* " << n << " event(s)");
                record().counter("t").incr(n);
            }
        });

        BOOST_CHECK(!iv.last(tick));

        seconds span{};
        for (auto n : { 0, 1, 2, 1, 0 }) {
            this_task::sleep_for(tick);

            BOOST_MESSAGE("interval expects " << n << " event(s) over " << span.count() << " sec");

            // asking for more than has been collected fails
            BOOST_CHECK(!iv.last(span + tick));

            // first request is too soon, so returns nullopt
            auto im = iv.last(span);
            if (span == seconds::zero())
                BOOST_CHECK(!im);
            else  {
                BOOST_CHECK_EQUAL(span.count(), im->first.count());
                BOOST_CHECK_EQUAL(n, value<counter>(im->second, "t"));
            }

            // do not allow span to exceed collection max
            if (span < iv.duration())
                span += tick;
        }

        bg.join();
    });
}
<commit_msg>boost unit test isn't thread safe. don't use it from threads.<commit_after>#define BOOST_TEST_MODULE metrics test
#include <boost/test/unit_test.hpp>
#include "ten/metrics.hh"
#include "ten/task.hh"
#include <thread>
#include <atomic>

#include "ten/ewma.hh"

using namespace ten;

void my_thread() {
#if 1
    metrics::record()
        //.incr<metrics::counter>("thing")
        .counter("thing").incr();
        ;
#else
    metrics::record([](metrics::group &g) {
        get<metrics::counter>(g, "thing").incr();
    });
#endif
}

static const int nthreads = 100;

BOOST_AUTO_TEST_CASE(ten_init) {
    kernel::boot(); // init logging etc
}

BOOST_AUTO_TEST_CASE(thread_local_test) {
    using namespace metrics;

    std::vector<std::thread> threads(nthreads);
    for (auto &i : threads) {
        i = std::thread(my_thread);
    }

    {
        auto mg = global.aggregate();
        for (auto kv : mg)
            DVLOG(1) << "metric: " << kv.first << " = " << boost::apply_visitor(json_visitor(), kv.second);
    }

    for (auto &i : threads) {
        i.join();
    }

    auto mg = global.aggregate();

    BOOST_CHECK_EQUAL(nthreads, value<counter>(mg, "thing"));
    for (auto kv : mg) {
        DVLOG(1) << "metric: " << kv.first << " = " << boost::apply_visitor(json_visitor(), kv.second);
    }
}

BOOST_AUTO_TEST_CASE(timer_test) {
    using namespace metrics;
    using namespace std::chrono;
    time_op to("timer1");
    usleep(5*1000);
    to.stop();
    auto mg = global.aggregate();
    auto v = value<timer>(mg, "timer1");
    // value type is a duration of unspecified resolution
    BOOST_CHECK(duration_cast<seconds     >(v).count() == 0);
    BOOST_CHECK(duration_cast<milliseconds>(v).count() >= 5);
    BOOST_CHECK(duration_cast<microseconds>(v).count() >= 5000);
}

BOOST_AUTO_TEST_CASE(ewma_test) {
    using namespace std::chrono;
    ewma<seconds> m1(seconds{1});
    ewma<seconds> m5(seconds{5});
    ewma<seconds> m60(seconds{60});

    for (unsigned i=0; i<60*5; ++i) {
        m1.update(10);
        m1.tick();
        m5.update(10);
        m5.tick();
        m60.update(10);
        m60.tick();
    }
    LOG(INFO) << "rate1: "  << m1.rate()  << "/s, " << m1.rate<minutes>()  << "/m";
    LOG(INFO) << "rate5: "  << m5.rate()  << "/s, " << m5.rate<minutes>()  << "/m";
    LOG(INFO) << "rate60: " << m60.rate() << "/s, " << m60.rate<minutes>() << "/m";

    BOOST_CHECK_CLOSE(10.0, m1.rate(), 60.0);
    BOOST_CHECK_CLOSE(10.0, m5.rate(), 11.0);
    BOOST_CHECK_CLOSE(10.0, m60.rate(), 2.0);

    for (unsigned i=0; i<60; ++i) {
        m1.tick();
        m5.tick();
        m60.tick();
    }

    LOG(INFO) << "rate1: "  << m1.rate()  << "/s, " << m1.rate<minutes>()  << "/m";
    LOG(INFO) << "rate5: "  << m5.rate()  << "/s, " << m5.rate<minutes>()  << "/m";
    LOG(INFO) << "rate60: " << m60.rate() << "/s, " << m60.rate<minutes>() << "/m";

    BOOST_CHECK_CLOSE(0.0, std::round(m1.rate()), 1.0);
    BOOST_CHECK_CLOSE(0.0, std::round(m5.rate()), 1.0);
    BOOST_CHECK_CLOSE(4.0, std::round(m60.rate()), 1.0);
}

BOOST_AUTO_TEST_CASE(interval_test) {
    task::main([] {
        using namespace metrics;
        using namespace std::chrono;

        // TODO: intervals internals are in seconds, else we could use e.g. 50ms here.
        constexpr seconds tick{1};
        intervals iv(tick, 2);

        // put all test events into the middle of the collection window
        this_task::sleep_for(duration_cast<milliseconds>(tick) / 2);

        std::thread bg([] {
            for (auto n : { 1, 1 }) {
                std::this_thread::sleep_for(tick);
                VLOG(1) << "* " << n << " event(s)";
                record().counter("t").incr(n);
            }
        });

        BOOST_CHECK(!iv.last(tick));

        seconds span{};
        for (auto n : { 0, 1, 2, 1, 0 }) {
            this_task::sleep_for(tick);

            BOOST_MESSAGE("interval expects " << n << " event(s) over " << span.count() << " sec");

            // asking for more than has been collected fails
            BOOST_CHECK(!iv.last(span + tick));

            // first request is too soon, so returns nullopt
            auto im = iv.last(span);
            if (span == seconds::zero())
                BOOST_CHECK(!im);
            else  {
                BOOST_CHECK_EQUAL(span.count(), im->first.count());
                BOOST_CHECK_EQUAL(n, value<counter>(im->second, "t"));
            }

            // do not allow span to exceed collection max
            if (span < iv.duration())
                span += tick;
        }

        bg.join();
    });
}
<|endoftext|>


<commit_before>/////////////////////////////////////////
//
//             OpenLieroX
//
// code under LGPL, based on JasonBs work,
// enhanced by Dark Charlie and Albert Zeyer
//
//
/////////////////////////////////////////

// CBar source file
// Created 22/6/07
// Dark Charlie

#include "GfxPrimitives.h"
#include "CBar.h"
#include "StringUtils.h"

//////////////
// Constructor
CBar::CBar(SDL_Surface *bmp, int x, int y, int label_x, int label_y, int dir)  {
	bmpBar = bmp;
	X = x;
	Y = y;
	LabelX = label_x;
	LabelY = label_y;
	Direction = dir;
	Position = 100;
	LabelVisible = true;

	// Default colors
	bgColor = MakeColour(128, 128, 128);
	foreColor = MakeColour(0, 255, 0);
}

//////////////
// Draw the bar
void CBar::Draw(SDL_Surface *dst)  {
	static std::string progress;
	progress = itoa(Position) + " %";
	int pos = MIN(MAX(Position, 0), 100);

	if (bmpBar)  {  // We got a bitmap - many options and possibilities for drawing

		int bar_h = (bmpBar->h - 1)/2;
		int bar_w = (bmpBar->w - 1)/2;

		// Background
		DrawImageAdv(dst,bmpBar, 0, bar_h, X, Y, bmpBar->w, bar_h);

		Uint32 clLabel = tLX->clWhite;

		// Draw the progress bitmap over the background depending on progress direction
		switch (Direction)  {
		case BAR_LEFTTORIGHT:
			DrawImageAdv(dst,bmpBar, 0, 0, X, Y, (bmpBar->w*pos)/100, bar_h);  // Progress
			clLabel = GetPixel(bmpBar, MAX(0, (bmpBar->w*pos)/100 - 1), bmpBar->h - 1);
			break;
		case BAR_RIGHTTOLEFT: {
			int w = (bmpBar->w * pos) / 100;
			DrawImageAdv(dst, bmpBar, bmpBar->w - w, 0, X + bmpBar->w - w, Y, w, bar_h);  // Progress
			clLabel = GetPixel(bmpBar, MIN(bmpBar->w - 1, bmpBar->w - w + 1), bmpBar->h - 1);
			}
			break;
		case BAR_TOPTOBOTTOM:
			DrawImageAdv(dst, bmpBar, 0, 0, X, Y, bar_w, (bmpBar->h/100)*pos); // Progress
			clLabel = GetPixel(bmpBar, bmpBar->w - 1, MAX(0, (bmpBar->h*pos)/100 - 1));
			break;
		case BAR_BOTTOMTOTOP:  {
			int h = (bmpBar->w * pos) / 100;
			DrawImageAdv(dst, bmpBar, 0, bmpBar->h - h, X, Y + bmpBar->h - h, bar_w, h);  // Progress
			clLabel = GetPixel(bmpBar, bmpBar->w - 1, MIN(bmpBar->h - 1, bmpBar->h - h - 1));
			}
			break;
		default:
			printf("Bad bar type in CBar::Draw");
			return;
		}

		// bmpBar is an alpha surface so we need to convert the color from GetPixel
		static Uint8 r, g, b;
		GetColour3(clLabel, bmpBar, &r, &g, &b);
		clLabel = MakeColour(r, g, b);

		if (LabelVisible)
			tLX->cFont.Draw(dst, LabelX, LabelY, clLabel, progress); // Label

	} else {  // No bitmap, just draw the simplest bar without any options
		int width = 100;
		int height = 10;

		DrawRectFill(dst, X, Y, (X + width + 1), Y+height, bgColor);
		DrawRectFill(dst, X+1, Y+1, X + (width / 100) * pos + 1, Y+height-1, foreColor);
	}

}
<commit_msg>cleanups<commit_after>/////////////////////////////////////////
//
//             OpenLieroX
//
// code under LGPL, based on JasonBs work,
// enhanced by Dark Charlie and Albert Zeyer
//
//
/////////////////////////////////////////

// CBar source file
// Created 22/6/07
// Dark Charlie

#include "GfxPrimitives.h"
#include "CBar.h"
#include "StringUtils.h"

//////////////
// Constructor
CBar::CBar(SDL_Surface *bmp, int x, int y, int label_x, int label_y, int dir)  {
	bmpBar = bmp;
	X = x;
	Y = y;
	LabelX = label_x;
	LabelY = label_y;
	Direction = dir;
	Position = 100;
	LabelVisible = true;

	// Default colors
	bgColor = MakeColour(128, 128, 128);
	foreColor = MakeColour(0, 255, 0);
}

//////////////
// Draw the bar
void CBar::Draw(SDL_Surface *dst)  {
	static std::string progress;
	progress = itoa(Position) + " %";
	int pos = MIN(MAX(Position, 0), 100);

	if (bmpBar)  {  // We got a bitmap - many options and possibilities for drawing

		int bar_h = (bmpBar->h - 1) / 2;
		int bar_w = (bmpBar->w - 1) / 2;

		// Background
		DrawImageAdv(dst, bmpBar, 0, bar_h, X, Y, bmpBar->w, bar_h);

		Uint32 clLabel = tLX->clWhite;

		// Draw the progress bitmap over the background depending on progress direction
		int w, h;
		switch (Direction)  {
		case BAR_LEFTTORIGHT:
			DrawImageAdv(dst, bmpBar, 0, 0, X, Y, (bmpBar->w * pos) / 100, bar_h);  // Progress
			clLabel = GetPixel(bmpBar, MAX(0, (bmpBar->w*pos)/100 - 1), bmpBar->h - 1);
			break;
		case BAR_RIGHTTOLEFT:
			w = (bmpBar->w * pos) / 100;
			DrawImageAdv(dst, bmpBar, bmpBar->w - w, 0, X + bmpBar->w - w, Y, w, bar_h);  // Progress
			clLabel = GetPixel(bmpBar, MIN(bmpBar->w - 1, bmpBar->w - w + 1), bmpBar->h - 1);
			break;
		case BAR_TOPTOBOTTOM:
			DrawImageAdv(dst, bmpBar, 0, 0, X, Y, bar_w, (bmpBar->h / 100) * pos); // Progress
			clLabel = GetPixel(bmpBar, bmpBar->w - 1, MAX(0, (bmpBar->h * pos)/100 - 1));
			break;
		case BAR_BOTTOMTOTOP:
			h = (bmpBar->w * pos) / 100;
			DrawImageAdv(dst, bmpBar, 0, bmpBar->h - h, X, Y + bmpBar->h - h, bar_w, h);  // Progress
			clLabel = GetPixel(bmpBar, bmpBar->w - 1, MIN(bmpBar->h - 1, bmpBar->h - h - 1));
			break;
		default:
			printf("Bad bar type in CBar::Draw");
			return;
		}

		// bmpBar is an alpha surface so we need to convert the color from GetPixel
		Uint8 r, g, b;
		GetColour3(clLabel, bmpBar, &r, &g, &b);
		clLabel = MakeColour(r, g, b);

		if (LabelVisible)
			tLX->cFont.Draw(dst, LabelX, LabelY, clLabel, progress); // Label

	} else {  // No bitmap, just draw the simplest bar without any options
		int width = 100;
		int height = 10;

		DrawRectFill(dst, X, Y, (X + width + 1), Y + height, bgColor);
		DrawRectFill(dst, X + 1, Y + 1, X + (width / 100) * pos + 1, Y + height - 1, foreColor);
	}

}
<|endoftext|>


<commit_before>#include <iostream>
#include <stxxl.h>

using stxxl::LOG2;
using stxxl::unsigned_type;

template <unsigned_type i>
void log_i()
{
    std::cout << i << "\t" << (i < 1000000 ? "\t" : "")
        << stxxl::LOG2_floor<i>::value << "\t"
        << stxxl::LOG2<i>::floor << "\t"
        << stxxl::LOG2<i>::ceil << std::endl;
}

template <unsigned_type i>
void log_ipm1()
{
    log_i<i-1>();
    log_i<i>();
    log_i<i+1>();
    std::cout << std::endl;
}

int main()
{
    std::cout << "i\t\tLOG2<i>\tLOG2<i>\tLOG2<i>" << std::endl;
    std::cout << "\t\t\tfloor\tceil" << std::endl;
    log_ipm1<1 << 0>();
    log_ipm1<1 << 1>();
    log_ipm1<1 << 2>();
    log_ipm1<1 << 3>();
    log_ipm1<1 << 4>();
    log_ipm1<1 << 5>();
    log_ipm1<1 << 6>();
    log_ipm1<1 << 7>();
    log_ipm1<1 << 8>();
    log_ipm1<1 << 9>();
    log_ipm1<1 << 10>();
    log_ipm1<1 << 11>();
    log_ipm1<1 << 12>();
    log_ipm1<1 << 16>();
    log_ipm1<1 << 24>();
    log_ipm1<1 << 30>();
    log_ipm1<1L << 31>();
#if __WORDSIZE == 64
    log_ipm1<1L << 32>();
    log_ipm1<1L << 33>();
    log_ipm1<1L << 48>();
    log_ipm1<1L << 63>();
#endif
}

<commit_msg>better use 1UL than 1L<commit_after>#include <iostream>
#include <stxxl.h>

using stxxl::LOG2;
using stxxl::unsigned_type;

template <unsigned_type i>
void log_i()
{
    std::cout << i << "\t" << (i < 1000000 ? "\t" : "")
        << stxxl::LOG2_floor<i>::value << "\t"
        << stxxl::LOG2<i>::floor << "\t"
        << stxxl::LOG2<i>::ceil << std::endl;
}

template <unsigned_type i>
void log_ipm1()
{
    log_i<i-1>();
    log_i<i>();
    log_i<i+1>();
    std::cout << std::endl;
}

int main()
{
    std::cout << "i\t\tLOG2<i>\tLOG2<i>\tLOG2<i>" << std::endl;
    std::cout << "\t\t\tfloor\tceil" << std::endl;
    log_ipm1<1 << 0>();
    log_ipm1<1 << 1>();
    log_ipm1<1 << 2>();
    log_ipm1<1 << 3>();
    log_ipm1<1 << 4>();
    log_ipm1<1 << 5>();
    log_ipm1<1 << 6>();
    log_ipm1<1 << 7>();
    log_ipm1<1 << 8>();
    log_ipm1<1 << 9>();
    log_ipm1<1 << 10>();
    log_ipm1<1 << 11>();
    log_ipm1<1 << 12>();
    log_ipm1<1 << 16>();
    log_ipm1<1 << 24>();
    log_ipm1<1 << 30>();
    log_ipm1<1UL << 31>();
#if __WORDSIZE == 64
    log_ipm1<1UL << 32>();
    log_ipm1<1UL << 33>();
    log_ipm1<1UL << 48>();
    log_ipm1<1UL << 63>();
#endif
}

<|endoftext|>


<commit_before>#include "matrix_all.h"

using namespace std;
using namespace matrix_hao_lib;

#ifdef USE_MAGMA
namespace matrix_hao_lib
{
    void bl_cpu_magma_timing();
}
#endif

int main(int argc, char** argv)
{
    int rank=0;

#ifdef MPI_HAO
    MPI_Init(&argc,&argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
#endif

    if(rank==0)
    {
        cout<<"\n\nThis timing program require large memory and long computational time!"<<endl;
        cout<<"Please submit the job if you are using a cluster, it takes ~10 minutes."<<endl;
        cout<<"\n=======Start timing======="<<endl;

    }

#ifdef USE_MAGMA
    magma_init();

    if(rank==0)
    {
        bl_cpu_magma_timing();
    }

    magma_finalize();
#endif

#ifdef MPI_HAO
    MPI_Finalize();
#endif

    return 0;
}
<commit_msg>Update timg_all.cpp.<commit_after>#include "matrix_all.h"

using namespace std;
using namespace matrix_hao_lib;

#ifdef USE_MAGMA
namespace matrix_hao_lib
{
    void bl_cpu_magma_timing();
}
#endif

int main(int argc, char** argv)
{
    int rank=0;

#ifdef MPI_HAO
    MPI_Init(&argc,&argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
#endif

    if(rank==0)
    {
        cout<<"\n\nThis timing program compares the time cost between CPU lapack and MAGMA lapack."<<endl;
        cout<<"It requires large memory and long computational time if USE_MAGMA=on, else does nothing."<<endl;
        cout<<"Please submit the job if you are using a cluster, it takes ~10 minutes."<<endl;
        cout<<"\n=======Start timing======="<<endl;

    }

#ifdef USE_MAGMA
    magma_init();

    if(rank==0)
    {
        bl_cpu_magma_timing();
    }

    magma_finalize();
#endif

#ifdef MPI_HAO
    MPI_Finalize();
#endif

    return 0;
}
<|endoftext|>


<commit_before>/*
 *  This file is part of Poedit (http://poedit.net)
 *
 *  Copyright (C) 2010-2015 Vaclav Slavik
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a
 *  copy of this software and associated documentation files (the "Software"),
 *  to deal in the Software without restriction, including without limitation
 *  the rights to use, copy, modify, merge, publish, distribute, sublicense,
 *  and/or sell copies of the Software, and to permit persons to whom the
 *  Software is furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 *  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 *  DEALINGS IN THE SOFTWARE.
 *
 */

#include "concurrency.h"

#if defined(HAVE_DISPATCH)

#include <dispatch/dispatch.h>

void call_on_main_thread_impl(std::function<void()>&& f)
{
    std::function<void()> func(std::move(f));
    dispatch_async(dispatch_get_main_queue(), [func]{ func(); });
}

void concurrency_queue::enqueue(std::function<void()>&& f)
{
    std::function<void()> func(std::move(f));
    dispatch_queue_t q = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(q, [func]{ func(); });
}

void concurrency_queue::cleanup()
{
}

#elif !defined(HAVE_PPL) // generic implementation

#include "ThreadPool.h"

#include <thread>

namespace
{

std::unique_ptr<ThreadPool> gs_pool;
static std::once_flag initializationFlag;

ThreadPool& pool()
{
    std::call_once(initializationFlag, []{
        gs_pool.reset(new ThreadPool(std::thread::hardware_concurrency() + 1));
    });
    return *gs_pool;
}

} // anonymous namespace

void concurrency_queue::enqueue(std::function<void()>&& f)
{
    pool().enqueue_func(std::move(f));
}

void concurrency_queue::cleanup()
{
    gs_pool.reset();
}

#endif // !HAVE_DISPATCH
<commit_msg>OS X: Don't terminate if a concurrent task throws<commit_after>/*
 *  This file is part of Poedit (http://poedit.net)
 *
 *  Copyright (C) 2010-2015 Vaclav Slavik
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a
 *  copy of this software and associated documentation files (the "Software"),
 *  to deal in the Software without restriction, including without limitation
 *  the rights to use, copy, modify, merge, publish, distribute, sublicense,
 *  and/or sell copies of the Software, and to permit persons to whom the
 *  Software is furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 *  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 *  DEALINGS IN THE SOFTWARE.
 *
 */

#include "concurrency.h"

#include "errors.h"
#include <wx/log.h>

#if defined(HAVE_DISPATCH)

#include <dispatch/dispatch.h>

void call_on_main_thread_impl(std::function<void()>&& f)
{
    std::function<void()> func(std::move(f));
    dispatch_async(dispatch_get_main_queue(), [func]{
        try
        {
            func();
        }
        catch (...)
        {
            // FIXME: This is gross. Should be reported better and properly, but this
            //        is consistent with pplx/ConcurrencyRT/futures, so do it for now.
            wxLogDebug("uncaught exception: %s", DescribeCurrentException());
        }
    });
}

void concurrency_queue::enqueue(std::function<void()>&& f)
{
    std::function<void()> func(std::move(f));
    dispatch_queue_t q = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(q, [func]{
        try
        {
            func();
        }
        catch (...)
        {
            // FIXME: This is gross. Should be reported better and properly, but this
            //        is consistent with pplx/ConcurrencyRT/futures, so do it for now.
            wxLogDebug("uncaught exception: %s", DescribeCurrentException());
        }
    });
}

void concurrency_queue::cleanup()
{
}

#elif !defined(HAVE_PPL) // generic implementation

#include "ThreadPool.h"

#include <thread>

namespace
{

std::unique_ptr<ThreadPool> gs_pool;
static std::once_flag initializationFlag;

ThreadPool& pool()
{
    std::call_once(initializationFlag, []{
        gs_pool.reset(new ThreadPool(std::thread::hardware_concurrency() + 1));
    });
    return *gs_pool;
}

} // anonymous namespace

void concurrency_queue::enqueue(std::function<void()>&& f)
{
    pool().enqueue_func(std::move(f));
}

void concurrency_queue::cleanup()
{
    gs_pool.reset();
}

#endif // !HAVE_DISPATCH
<|endoftext|>


<commit_before>// Kernel.cpp (Oclgrind)
// Copyright (c) 2013-2016, James Price and Simon McIntosh-Smith,
// University of Bristol. All rights reserved.
//
// This program is provided under a three-clause BSD license. For full
// license terms please see the LICENSE file distributed with this
// source code.

#include "config.h"
#include "common.h"

#include <sstream>

#include "llvm/IR/Constants.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/raw_os_ostream.h"

#include "Kernel.h"
#include "Program.h"
#include "Memory.h"

using namespace oclgrind;
using namespace std;

Kernel::Kernel(const Program *program,
               const llvm::Function *function, const llvm::Module *module)
 : m_program(program), m_function(function), m_name(function->getName())
{
  // Set-up global variables
  llvm::Module::const_global_iterator itr;
  for (itr = module->global_begin(); itr != module->global_end(); itr++)
  {
    llvm::PointerType *type = itr->getType();
    switch (type->getPointerAddressSpace())
    {
    case AddrSpacePrivate:
    {
      // Get initializer data
      const llvm::Constant *init = itr->getInitializer();
      unsigned size = getTypeSize(init->getType());
      TypedValue value = {size, 1, new uint8_t[size]};
      getConstantData(value.data, init);
      m_values[&*itr] = value;

      break;
    }
    case AddrSpaceConstant:
      m_constants.push_back(&*itr);
      break;
    case AddrSpaceLocal:
    {
      // Get size of allocation
      TypedValue allocSize = {
        getTypeSize(itr->getInitializer()->getType()), 1, NULL
      };
      m_values[&*itr] = allocSize;

      break;
    }
    default:
      FATAL_ERROR("Unsupported GlobalVariable address space: %d",
                  type->getPointerAddressSpace());
    }
  }

  // Get metadata node containing kernel arg info
  m_metadata = NULL;
  llvm::NamedMDNode *md = module->getNamedMetadata("opencl.kernels");
  if (md)
  {
    for (unsigned i = 0; i < md->getNumOperands(); i++)
    {
      llvm::MDNode *node = md->getOperand(i);

      llvm::ConstantAsMetadata *cam =
        llvm::dyn_cast<llvm::ConstantAsMetadata>(node->getOperand(0).get());
      if (!cam)
        continue;

      llvm::Function *function = ((llvm::Function*)cam->getValue());
      if (function->getName() == m_name)
      {
        m_metadata = node;
        break;
      }
    }
  }
}

Kernel::Kernel(const Kernel& kernel)
 : m_program(kernel.m_program)
{
  m_function = kernel.m_function;
  m_constants = kernel.m_constants;
  m_constantBuffers = kernel.m_constantBuffers;
  m_name = kernel.m_name;
  m_metadata = kernel.m_metadata;

  for (auto itr = kernel.m_values.begin(); itr != kernel.m_values.end(); itr++)
  {
    m_values[itr->first] = itr->second.clone();
  }
}

Kernel::~Kernel()
{
  TypedValueMap::iterator itr;
  for (itr = m_values.begin(); itr != m_values.end(); itr++)
  {
    delete[] itr->second.data;
  }
}

bool Kernel::allArgumentsSet() const
{
  llvm::Function::const_arg_iterator itr;
  for (itr = m_function->arg_begin(); itr != m_function->arg_end(); itr++)
  {
    if (!m_values.count(&*itr))
    {
      return false;
    }
  }
  return true;
}

void Kernel::allocateConstants(Memory *memory)
{
  list<const llvm::GlobalVariable*>::const_iterator itr;
  for (itr = m_constants.begin(); itr != m_constants.end(); itr++)
  {
    const llvm::Constant *initializer = (*itr)->getInitializer();
    const llvm::Type *type = initializer->getType();

    // Deallocate existing pointer
    if (m_values.count(*itr))
    {
      delete[] m_values[*itr].data;
    }

    // Get initializer data
    unsigned size = getTypeSize(type);
    unsigned char *data = new unsigned char[size];
    getConstantData(data, (const llvm::Constant*)initializer);

    // Allocate buffer
    TypedValue address = {
      sizeof(size_t),
      1,
      new unsigned char[sizeof(size_t)]
    };
    size_t ptr = memory->allocateBuffer(size, 0, data);
    address.setPointer(ptr);

    m_values[*itr] = address;
    m_constantBuffers.push_back(ptr);

    delete[] data;
  }
}

void Kernel::deallocateConstants(Memory *memory)
{
  list<size_t>::const_iterator itr;
  for (itr = m_constantBuffers.begin(); itr != m_constantBuffers.end(); itr++)
  {
    memory->deallocateBuffer(*itr);
  }
  m_constantBuffers.clear();
}

const llvm::Argument* Kernel::getArgument(unsigned int index) const
{
  assert(index < getNumArguments());

  llvm::Function::const_arg_iterator argItr = m_function->arg_begin();
  for (unsigned i = 0; i < index; i++)
  {
    argItr++;
  }
  return &*argItr;
}

unsigned int Kernel::getArgumentAccessQualifier(unsigned int index) const
{
  assert(index < getNumArguments());

  // Get metadata
  const llvm::Metadata *md =
    getArgumentMetadata("kernel_arg_access_qual", index);
  if (!md)
  {
    return -1;
  }

  // Get qualifier string
  const llvm::MDString *str = llvm::dyn_cast<llvm::MDString>(md);
  string access = str->getString();
  if (access == "read_only")
  {
    return CL_KERNEL_ARG_ACCESS_READ_ONLY;
  }
  else if (access == "write_only")
  {
    return CL_KERNEL_ARG_ACCESS_WRITE_ONLY;
  }
  else if (access == "read_write")
  {
    return CL_KERNEL_ARG_ACCESS_READ_WRITE;
  }
  return CL_KERNEL_ARG_ACCESS_NONE;
}

unsigned int Kernel::getArgumentAddressQualifier(unsigned int index) const
{
  assert(index < getNumArguments());

  // Get metadata
  const llvm::Metadata *md =
    getArgumentMetadata("kernel_arg_addr_space", index);
  if (!md)
  {
    return -1;
  }

  switch(getMDAsConstInt(md)->getZExtValue())
  {
    case AddrSpacePrivate:
      return CL_KERNEL_ARG_ADDRESS_PRIVATE;
    case AddrSpaceGlobal:
      return CL_KERNEL_ARG_ADDRESS_GLOBAL;
    case AddrSpaceConstant:
      return CL_KERNEL_ARG_ADDRESS_CONSTANT;
    case AddrSpaceLocal:
      return CL_KERNEL_ARG_ADDRESS_LOCAL;
    default:
      return -1;
  }
}

const llvm::Metadata* Kernel::getArgumentMetadata(string name,
                                                  unsigned int index) const
{
#if LLVM_VERSION < 39
  if (!m_metadata)
  {
    return NULL;
  }

  // Loop over all metadata nodes for this kernel
  for (unsigned i = 0; i < m_metadata->getNumOperands(); i++)
  {
    const llvm::MDOperand& op = m_metadata->getOperand(i);
    if (llvm::MDNode *node = llvm::dyn_cast<llvm::MDNode>(op.get()))
    {
      // Check if node matches target name
      if (node->getNumOperands() > 0 &&
          ((llvm::MDString*)(node->getOperand(0).get()))->getString() == name)
      {
        return node->getOperand(index+1).get();
      }
    }
  }
  return NULL;
#else
  llvm::MDNode *node = m_function->getMetadata(name);
  if (!node)
    return NULL;
  return node->getOperand(index);
#endif
}

const llvm::StringRef Kernel::getArgumentName(unsigned int index) const
{
  return getArgument(index)->getName();
}

const llvm::StringRef Kernel::getArgumentTypeName(unsigned int index) const
{
  assert(index < getNumArguments());

  // Get metadata
  const llvm::Metadata *md = getArgumentMetadata("kernel_arg_type", index);
  if (!md)
  {
    return "";
  }

  llvm::StringRef name = llvm::dyn_cast<llvm::MDString>(md)->getString();
#if LLVM_VERSION >= 39
  size_t imgStart = name.find(" image");
  if (imgStart != llvm::StringRef::npos)
  {
    name = name.substr(imgStart+1);
  }
#endif
  return name;
}

unsigned int Kernel::getArgumentTypeQualifier(unsigned int index) const
{
  assert(index < getNumArguments());

  // Get metadata
  const llvm::Metadata *md = getArgumentMetadata("kernel_arg_type_qual", index);
  if (!md)
  {
    return -1;
  }

  // Get qualifiers
  const llvm::MDString *str = llvm::dyn_cast<llvm::MDString>(md);
  istringstream iss(str->getString().str());

  unsigned int result = CL_KERNEL_ARG_TYPE_NONE;
  while (!iss.eof())
  {
    string tok;
    iss >> tok;
    if (tok == "const")
    {
      result |= CL_KERNEL_ARG_TYPE_CONST;
    }
    else if (tok == "restrict")
    {
      result |= CL_KERNEL_ARG_TYPE_RESTRICT;
    }
    else if (tok == "volatile")
    {
      result |= CL_KERNEL_ARG_TYPE_VOLATILE;
    }
  }

  return result;
}

size_t Kernel::getArgumentSize(unsigned int index) const
{
  const llvm::Argument *argument = getArgument(index);
  const llvm::Type *type = argument->getType();

  // Check if pointer argument
  if (type->isPointerTy() && argument->hasByValAttr())
  {
    return getTypeSize(type->getPointerElementType());
  }

  return getTypeSize(type);
}

string Kernel::getAttributes() const
{
  ostringstream attributes("");
  for (unsigned i = 0; i < m_metadata->getNumOperands(); i++)
  {
    llvm::MDNode *op = llvm::dyn_cast<llvm::MDNode>(m_metadata->getOperand(i));
    if (op)
    {
      llvm::MDNode *val = ((llvm::MDNode*)op);
      llvm::MDString *str =
        llvm::dyn_cast<llvm::MDString>(val->getOperand(0).get());
      string name = str->getString().str();

      if (name == "reqd_work_group_size" ||
          name == "work_group_size_hint")
      {
        attributes << name << "("
                   <<        getMDAsConstInt(val->getOperand(1))->getZExtValue()
                   << "," << getMDAsConstInt(val->getOperand(2))->getZExtValue()
                   << "," << getMDAsConstInt(val->getOperand(3))->getZExtValue()
                   << ") ";
      }
      else if (name == "vec_type_hint")
      {
        // Get type hint
        size_t n = 1;
        llvm::Metadata *md = val->getOperand(1).get();
        llvm::ValueAsMetadata *vam = llvm::dyn_cast<llvm::ValueAsMetadata>(md);
        const llvm::Type *type = vam->getType();
        if (type->isVectorTy())
        {
          n = type->getVectorNumElements();
          type = type->getVectorElementType();
        }

        // Generate attribute string
        attributes << name << "(" << flush;
        llvm::raw_os_ostream out(attributes);
        type->print(out);
        out.flush();
        attributes << n << ") ";
      }
    }
  }
  return attributes.str();
}

const llvm::Function* Kernel::getFunction() const
{
  return m_function;
}

size_t Kernel::getLocalMemorySize() const
{
  size_t sz = 0;
  for (auto value = m_values.begin(); value != m_values.end(); value++)
  {
    const llvm::Type *type = value->first->getType();
    if (type->isPointerTy() && type->getPointerAddressSpace() == AddrSpaceLocal)
    {
      sz += value->second.size;
    }
  }
  return sz;
}

const std::string& Kernel::getName() const
{
  return m_name;
}

unsigned int Kernel::getNumArguments() const
{
  return m_function->arg_size();
}

const Program* Kernel::getProgram() const
{
  return m_program;
}

void Kernel::getRequiredWorkGroupSize(size_t reqdWorkGroupSize[3]) const
{
  memset(reqdWorkGroupSize, 0, 3*sizeof(size_t));
  for (int j = 0; j < 3; j++)
  {
    const llvm::Metadata *md = getArgumentMetadata("reqd_work_group_size", j);
    if (md)
      reqdWorkGroupSize[j] = getMDAsConstInt(md)->getZExtValue();
  }
}

void Kernel::setArgument(unsigned int index, TypedValue value)
{
  assert(index < m_function->arg_size());

  const llvm::Value *argument = getArgument(index);

  // Deallocate existing argument
  if (m_values.count(argument))
  {
    delete[] m_values[argument].data;
  }

#if LLVM_VERSION >= 40
  if (getArgumentTypeName(index).str() == "sampler_t")
  {
    // We store the actual sampler i32 value after the pointer value
    TypedValue sampler;
    sampler.size = sizeof(size_t);
    sampler.num = 1;
    sampler.data = new unsigned char[sizeof(size_t) + 4];
    sampler.setPointer((size_t)(sampler.data + sizeof(size_t)));
    memcpy(sampler.data+sizeof(size_t), value.data, 4);

    m_values[argument] = sampler;
  }
  else
#endif
  {
    m_values[argument] = value.clone();
  }
}

TypedValueMap::const_iterator Kernel::values_begin() const
{
  return m_values.begin();
}

TypedValueMap::const_iterator Kernel::values_end() const
{
  return m_values.end();
}
<commit_msg>Use opencl.kernels metadata if no function metadata available<commit_after>// Kernel.cpp (Oclgrind)
// Copyright (c) 2013-2016, James Price and Simon McIntosh-Smith,
// University of Bristol. All rights reserved.
//
// This program is provided under a three-clause BSD license. For full
// license terms please see the LICENSE file distributed with this
// source code.

#include "config.h"
#include "common.h"

#include <sstream>

#include "llvm/IR/Constants.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/raw_os_ostream.h"

#include "Kernel.h"
#include "Program.h"
#include "Memory.h"

using namespace oclgrind;
using namespace std;

Kernel::Kernel(const Program *program,
               const llvm::Function *function, const llvm::Module *module)
 : m_program(program), m_function(function), m_name(function->getName())
{
  // Set-up global variables
  llvm::Module::const_global_iterator itr;
  for (itr = module->global_begin(); itr != module->global_end(); itr++)
  {
    llvm::PointerType *type = itr->getType();
    switch (type->getPointerAddressSpace())
    {
    case AddrSpacePrivate:
    {
      // Get initializer data
      const llvm::Constant *init = itr->getInitializer();
      unsigned size = getTypeSize(init->getType());
      TypedValue value = {size, 1, new uint8_t[size]};
      getConstantData(value.data, init);
      m_values[&*itr] = value;

      break;
    }
    case AddrSpaceConstant:
      m_constants.push_back(&*itr);
      break;
    case AddrSpaceLocal:
    {
      // Get size of allocation
      TypedValue allocSize = {
        getTypeSize(itr->getInitializer()->getType()), 1, NULL
      };
      m_values[&*itr] = allocSize;

      break;
    }
    default:
      FATAL_ERROR("Unsupported GlobalVariable address space: %d",
                  type->getPointerAddressSpace());
    }
  }

  // Get metadata node containing kernel arg info
  m_metadata = NULL;
  llvm::NamedMDNode *md = module->getNamedMetadata("opencl.kernels");
  if (md)
  {
    for (unsigned i = 0; i < md->getNumOperands(); i++)
    {
      llvm::MDNode *node = md->getOperand(i);

      llvm::ConstantAsMetadata *cam =
        llvm::dyn_cast<llvm::ConstantAsMetadata>(node->getOperand(0).get());
      if (!cam)
        continue;

      llvm::Function *function = ((llvm::Function*)cam->getValue());
      if (function->getName() == m_name)
      {
        m_metadata = node;
        break;
      }
    }
  }
}

Kernel::Kernel(const Kernel& kernel)
 : m_program(kernel.m_program)
{
  m_function = kernel.m_function;
  m_constants = kernel.m_constants;
  m_constantBuffers = kernel.m_constantBuffers;
  m_name = kernel.m_name;
  m_metadata = kernel.m_metadata;

  for (auto itr = kernel.m_values.begin(); itr != kernel.m_values.end(); itr++)
  {
    m_values[itr->first] = itr->second.clone();
  }
}

Kernel::~Kernel()
{
  TypedValueMap::iterator itr;
  for (itr = m_values.begin(); itr != m_values.end(); itr++)
  {
    delete[] itr->second.data;
  }
}

bool Kernel::allArgumentsSet() const
{
  llvm::Function::const_arg_iterator itr;
  for (itr = m_function->arg_begin(); itr != m_function->arg_end(); itr++)
  {
    if (!m_values.count(&*itr))
    {
      return false;
    }
  }
  return true;
}

void Kernel::allocateConstants(Memory *memory)
{
  list<const llvm::GlobalVariable*>::const_iterator itr;
  for (itr = m_constants.begin(); itr != m_constants.end(); itr++)
  {
    const llvm::Constant *initializer = (*itr)->getInitializer();
    const llvm::Type *type = initializer->getType();

    // Deallocate existing pointer
    if (m_values.count(*itr))
    {
      delete[] m_values[*itr].data;
    }

    // Get initializer data
    unsigned size = getTypeSize(type);
    unsigned char *data = new unsigned char[size];
    getConstantData(data, (const llvm::Constant*)initializer);

    // Allocate buffer
    TypedValue address = {
      sizeof(size_t),
      1,
      new unsigned char[sizeof(size_t)]
    };
    size_t ptr = memory->allocateBuffer(size, 0, data);
    address.setPointer(ptr);

    m_values[*itr] = address;
    m_constantBuffers.push_back(ptr);

    delete[] data;
  }
}

void Kernel::deallocateConstants(Memory *memory)
{
  list<size_t>::const_iterator itr;
  for (itr = m_constantBuffers.begin(); itr != m_constantBuffers.end(); itr++)
  {
    memory->deallocateBuffer(*itr);
  }
  m_constantBuffers.clear();
}

const llvm::Argument* Kernel::getArgument(unsigned int index) const
{
  assert(index < getNumArguments());

  llvm::Function::const_arg_iterator argItr = m_function->arg_begin();
  for (unsigned i = 0; i < index; i++)
  {
    argItr++;
  }
  return &*argItr;
}

unsigned int Kernel::getArgumentAccessQualifier(unsigned int index) const
{
  assert(index < getNumArguments());

  // Get metadata
  const llvm::Metadata *md =
    getArgumentMetadata("kernel_arg_access_qual", index);
  if (!md)
  {
    return -1;
  }

  // Get qualifier string
  const llvm::MDString *str = llvm::dyn_cast<llvm::MDString>(md);
  string access = str->getString();
  if (access == "read_only")
  {
    return CL_KERNEL_ARG_ACCESS_READ_ONLY;
  }
  else if (access == "write_only")
  {
    return CL_KERNEL_ARG_ACCESS_WRITE_ONLY;
  }
  else if (access == "read_write")
  {
    return CL_KERNEL_ARG_ACCESS_READ_WRITE;
  }
  return CL_KERNEL_ARG_ACCESS_NONE;
}

unsigned int Kernel::getArgumentAddressQualifier(unsigned int index) const
{
  assert(index < getNumArguments());

  // Get metadata
  const llvm::Metadata *md =
    getArgumentMetadata("kernel_arg_addr_space", index);
  if (!md)
  {
    return -1;
  }

  switch(getMDAsConstInt(md)->getZExtValue())
  {
    case AddrSpacePrivate:
      return CL_KERNEL_ARG_ADDRESS_PRIVATE;
    case AddrSpaceGlobal:
      return CL_KERNEL_ARG_ADDRESS_GLOBAL;
    case AddrSpaceConstant:
      return CL_KERNEL_ARG_ADDRESS_CONSTANT;
    case AddrSpaceLocal:
      return CL_KERNEL_ARG_ADDRESS_LOCAL;
    default:
      return -1;
  }
}

const llvm::Metadata* Kernel::getArgumentMetadata(string name,
                                                  unsigned int index) const
{
  llvm::MDNode *node = m_function->getMetadata(name);
  if (node)
    return node->getOperand(index);

  if (!m_metadata)
  {
    return NULL;
  }

  // Loop over all metadata nodes for this kernel
  for (unsigned i = 0; i < m_metadata->getNumOperands(); i++)
  {
    const llvm::MDOperand& op = m_metadata->getOperand(i);
    if (llvm::MDNode *node = llvm::dyn_cast<llvm::MDNode>(op.get()))
    {
      // Check if node matches target name
      if (node->getNumOperands() > 0 &&
          ((llvm::MDString*)(node->getOperand(0).get()))->getString() == name)
      {
        return node->getOperand(index+1).get();
      }
    }
  }
  return NULL;
}

const llvm::StringRef Kernel::getArgumentName(unsigned int index) const
{
  return getArgument(index)->getName();
}

const llvm::StringRef Kernel::getArgumentTypeName(unsigned int index) const
{
  assert(index < getNumArguments());

  // Get metadata
  const llvm::Metadata *md = getArgumentMetadata("kernel_arg_type", index);
  if (!md)
  {
    return "";
  }

  llvm::StringRef name = llvm::dyn_cast<llvm::MDString>(md)->getString();
#if LLVM_VERSION >= 39
  size_t imgStart = name.find(" image");
  if (imgStart != llvm::StringRef::npos)
  {
    name = name.substr(imgStart+1);
  }
#endif
  return name;
}

unsigned int Kernel::getArgumentTypeQualifier(unsigned int index) const
{
  assert(index < getNumArguments());

  // Get metadata
  const llvm::Metadata *md = getArgumentMetadata("kernel_arg_type_qual", index);
  if (!md)
  {
    return -1;
  }

  // Get qualifiers
  const llvm::MDString *str = llvm::dyn_cast<llvm::MDString>(md);
  istringstream iss(str->getString().str());

  unsigned int result = CL_KERNEL_ARG_TYPE_NONE;
  while (!iss.eof())
  {
    string tok;
    iss >> tok;
    if (tok == "const")
    {
      result |= CL_KERNEL_ARG_TYPE_CONST;
    }
    else if (tok == "restrict")
    {
      result |= CL_KERNEL_ARG_TYPE_RESTRICT;
    }
    else if (tok == "volatile")
    {
      result |= CL_KERNEL_ARG_TYPE_VOLATILE;
    }
  }

  return result;
}

size_t Kernel::getArgumentSize(unsigned int index) const
{
  const llvm::Argument *argument = getArgument(index);
  const llvm::Type *type = argument->getType();

  // Check if pointer argument
  if (type->isPointerTy() && argument->hasByValAttr())
  {
    return getTypeSize(type->getPointerElementType());
  }

  return getTypeSize(type);
}

string Kernel::getAttributes() const
{
  ostringstream attributes("");
  for (unsigned i = 0; i < m_metadata->getNumOperands(); i++)
  {
    llvm::MDNode *op = llvm::dyn_cast<llvm::MDNode>(m_metadata->getOperand(i));
    if (op)
    {
      llvm::MDNode *val = ((llvm::MDNode*)op);
      llvm::MDString *str =
        llvm::dyn_cast<llvm::MDString>(val->getOperand(0).get());
      string name = str->getString().str();

      if (name == "reqd_work_group_size" ||
          name == "work_group_size_hint")
      {
        attributes << name << "("
                   <<        getMDAsConstInt(val->getOperand(1))->getZExtValue()
                   << "," << getMDAsConstInt(val->getOperand(2))->getZExtValue()
                   << "," << getMDAsConstInt(val->getOperand(3))->getZExtValue()
                   << ") ";
      }
      else if (name == "vec_type_hint")
      {
        // Get type hint
        size_t n = 1;
        llvm::Metadata *md = val->getOperand(1).get();
        llvm::ValueAsMetadata *vam = llvm::dyn_cast<llvm::ValueAsMetadata>(md);
        const llvm::Type *type = vam->getType();
        if (type->isVectorTy())
        {
          n = type->getVectorNumElements();
          type = type->getVectorElementType();
        }

        // Generate attribute string
        attributes << name << "(" << flush;
        llvm::raw_os_ostream out(attributes);
        type->print(out);
        out.flush();
        attributes << n << ") ";
      }
    }
  }
  return attributes.str();
}

const llvm::Function* Kernel::getFunction() const
{
  return m_function;
}

size_t Kernel::getLocalMemorySize() const
{
  size_t sz = 0;
  for (auto value = m_values.begin(); value != m_values.end(); value++)
  {
    const llvm::Type *type = value->first->getType();
    if (type->isPointerTy() && type->getPointerAddressSpace() == AddrSpaceLocal)
    {
      sz += value->second.size;
    }
  }
  return sz;
}

const std::string& Kernel::getName() const
{
  return m_name;
}

unsigned int Kernel::getNumArguments() const
{
  return m_function->arg_size();
}

const Program* Kernel::getProgram() const
{
  return m_program;
}

void Kernel::getRequiredWorkGroupSize(size_t reqdWorkGroupSize[3]) const
{
  memset(reqdWorkGroupSize, 0, 3*sizeof(size_t));
  for (int j = 0; j < 3; j++)
  {
    const llvm::Metadata *md = getArgumentMetadata("reqd_work_group_size", j);
    if (md)
      reqdWorkGroupSize[j] = getMDAsConstInt(md)->getZExtValue();
  }
}

void Kernel::setArgument(unsigned int index, TypedValue value)
{
  assert(index < m_function->arg_size());

  const llvm::Value *argument = getArgument(index);

  // Deallocate existing argument
  if (m_values.count(argument))
  {
    delete[] m_values[argument].data;
  }

#if LLVM_VERSION >= 40
  if (getArgumentTypeName(index).str() == "sampler_t")
  {
    // We store the actual sampler i32 value after the pointer value
    TypedValue sampler;
    sampler.size = sizeof(size_t);
    sampler.num = 1;
    sampler.data = new unsigned char[sizeof(size_t) + 4];
    sampler.setPointer((size_t)(sampler.data + sizeof(size_t)));
    memcpy(sampler.data+sizeof(size_t), value.data, 4);

    m_values[argument] = sampler;
  }
  else
#endif
  {
    m_values[argument] = value.clone();
  }
}

TypedValueMap::const_iterator Kernel::values_begin() const
{
  return m_values.begin();
}

TypedValueMap::const_iterator Kernel::values_end() const
{
  return m_values.end();
}
<|endoftext|>