text:
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Original code was distributed under the MIT software license.
// Copyright (c) 2014-2017 Coin Sciences Ltd
// MultiChain code distributed under the GPLv3 license, see COPYING file.

#include "miner/miner.h"

#include "structs/amount.h"
#include "primitives/block.h"
#include "primitives/transaction.h"
#include "structs/hash.h"
#include "core/main.h"
#include "net/net.h"
#include "structs/base58.h"
#include "chain/pow.h"
#include "utils/timedata.h"
#include "utils/util.h"
#include "utils/utilmoneystr.h"
#ifdef ENABLE_WALLET
#include "wallet/wallet.h"
#endif

#include "multichain/multichain.h"

#include <boost/thread.hpp>
#include <boost/tuple/tuple.hpp>

using namespace std;

bool CanMineWithLockedBlock();
bool IsTxBanned(uint256 txid);
int LastForkedHeight();

//////////////////////////////////////////////////////////////////////////////
//
// BitcoinMiner
//

//
// Unconfirmed transactions in the memory pool often depend on other
// transactions in the memory pool. When we select transactions from the
// pool, we select by highest priority or fee rate, so we might consider
// transactions that depend on transactions that aren't yet in the block.
// The COrphan class keeps track of these 'temporary orphans' while
// CreateBlock is figuring out which transactions to include.
//
class COrphan
{
public:
    const CTransaction* ptx;
    set<uint256> setDependsOn;
    CFeeRate feeRate;
    double dPriority;

    COrphan(const CTransaction* ptxIn) : ptx(ptxIn), feeRate(0), dPriority(0)
    {
    }
};

uint64_t nLastBlockTx = 0;
uint64_t nLastBlockSize = 0;

// We want to sort transactions by priority and fee rate, so:
typedef boost::tuple<double, CFeeRate, const CTransaction*> TxPriority;
class TxPriorityCompare
{
    bool byFee;

public:
    TxPriorityCompare(bool _byFee) : byFee(_byFee) { }

    bool operator()(const TxPriority& a, const TxPriority& b)
    {
        if (byFee)
        {
            if (a.get<1>() == b.get<1>())
                return a.get<0>() < b.get<0>();
            return a.get<1>() < b.get<1>();
        }
        else
        {
            if (a.get<0>() == b.get<0>())
                return a.get<1>() < b.get<1>();
            return a.get<0>() < b.get<0>();
        }
    }
};

bool UpdateTime(CBlockHeader* pblock, const CBlockIndex* pindexPrev)
{
/* MCHN START */
    uint32_t original_nTime=pblock->nTime;
    uint32_t original_nBits=pblock->nBits;
/* MCHN END */
    pblock->nTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());

    // Updating time can change work required on testnet:
    if (Params().AllowMinDifficultyBlocks())
        pblock->nBits = GetNextWorkRequired(pindexPrev, pblock);
/* MCHN START */
    if((original_nTime != pblock->nTime) || (original_nBits != pblock->nBits))
    {
        return true;
    }
    return false;
/* MCHN END */
}

/* MCHN START */

bool CreateBlockSignature(CBlock *block,uint32_t hash_type,CWallet *pwallet)
{
    int coinbase_tx,op_return_output;
    uint256 hash_to_verify;
    uint256 original_merkle_root;
    std::vector<unsigned char> vchSigOut;
    std::vector<unsigned char> vchPubKey;

    block->nMerkleTreeType=MERKLETREE_FULL;
    block->nSigHashType=BLOCKSIGHASH_NONE;

    if(!mc_gState->m_NetworkParams->IsProtocolMultichain())
    {
        block->hashMerkleRoot=block->BuildMerkleTree();
        return true;
    }

    if(block->vSigner[0] == 0)
    {
        return false;
    }

    coinbase_tx=-1;
    op_return_output=-1;
    for (unsigned int i = 0; i < block->vtx.size(); i++)
    {
        if(coinbase_tx<0)
        {
            const CTransaction &tx = block->vtx[i];
            if (block->vtx[i].IsCoinBase())
            {
                coinbase_tx=i;
                for (unsigned int j = 0; j < tx.vout.size(); j++)
                {

                    const CScript& script1 = tx.vout[j].scriptPubKey;
                    if(script1.IsUnspendable())
                    {
                        op_return_output=j;
                    }
                }
            }
        }
    }

    if(coinbase_tx<0)
    {
        block->nSigHashType=BLOCKSIGHASH_INVALID;
        return false;
    }

    if((hash_type == BLOCKSIGHASH_HEADER) && (op_return_output >= 0))
    {
        block->nSigHashType=BLOCKSIGHASH_INVALID;
        return false;
    }
//    if(op_return_output >= 0)
    {
        CMutableTransaction tx=block->vtx[coinbase_tx];
        tx.vout.clear();
        for(int i=0;i<(int)block->vtx[coinbase_tx].vout.size();i++)
        {
            if((i != op_return_output) &&
               ((block->vtx[coinbase_tx].vout[i].nValue != 0) || (mc_gState->m_Permissions->m_Block == 0)))
            {
                tx.vout.push_back(block->vtx[coinbase_tx].vout[i]);
            }
        }
        block->vtx[coinbase_tx]=tx;
    }

    switch(hash_type)
    {
        case BLOCKSIGHASH_HEADER:
            block->nMerkleTreeType=MERKLETREE_NO_COINBASE_OP_RETURN;
            block->nSigHashType=BLOCKSIGHASH_HEADER;
            hash_to_verify=block->GetHash();
            break;
        case BLOCKSIGHASH_NO_SIGNATURE_AND_NONCE:
            block->nMerkleTreeType=MERKLETREE_NO_COINBASE_OP_RETURN;
            block->hashMerkleRoot=block->BuildMerkleTree();
            block->nNonce=0;
            hash_to_verify=block->GetHash();
            block->nMerkleTreeType=MERKLETREE_FULL;
            break;
        default:
            block->nSigHashType=BLOCKSIGHASH_INVALID;
            return false;
    }

    CMutableTransaction tx=block->vtx[coinbase_tx];
    tx.vout.clear();
    for(int i=0;i<(int)block->vtx[coinbase_tx].vout.size();i++)
    {
        tx.vout.push_back(block->vtx[coinbase_tx].vout[i]);
    }

    CTxOut txOut;

    txOut.nValue = 0;
    txOut.scriptPubKey = CScript() << OP_RETURN;

    size_t elem_size;
    const unsigned char *elem;

    vchPubKey=std::vector<unsigned char> (block->vSigner+1, block->vSigner+1+block->vSigner[0]);

    CPubKey pubKeyOut(vchPubKey);
    CKey key;
    if(!pwallet->GetKey(pubKeyOut.GetID(), key))
    {
        return false;
    }

    vector<unsigned char> vchSig;
    key.Sign(hash_to_verify, vchSig);

    mc_Script *lpScript;
    lpScript=new mc_Script;

    lpScript->SetBlockSignature(vchSig.data(),vchSig.size(),hash_type,block->vSigner+1,block->vSigner[0]);

    for(int element=0;element < lpScript->GetNumElements();element++)
    {
        elem = lpScript->GetData(element,&elem_size);
        if(elem)
        {
            txOut.scriptPubKey << vector<unsigned char>(elem, elem + elem_size);
        }
    }
    delete lpScript;

    tx.vout.push_back(txOut);

    block->vtx[coinbase_tx]=tx;

    switch(hash_type)
    {
        case BLOCKSIGHASH_NO_SIGNATURE_AND_NONCE:
            block->hashMerkleRoot=block->BuildMerkleTree();
            break;
    }

    return true;
}

/* MCHN END */

/* MCHN START */
//CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn)
CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn,CWallet *pwallet,CPubKey *ppubkey,int *canMine,CBlockIndex** ppPrev)
/* MCHN END */
{
    // Create new block
    auto_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate());
    if(!pblocktemplate.get())
        return NULL;
    CBlock *pblock = &pblocktemplate->block; // pointer for convenience
    // -regtest only: allow overriding block.nVersion with
    // -blockversion=N to test forking scenarios
    if (Params().MineBlocksOnDemand())
        pblock->nVersion = GetArg("-blockversion", pblock->nVersion);

    // Create coinbase tx
    CMutableTransaction txNew;
    txNew.vin.resize(1);
    txNew.vin[0].prevout.SetNull();

/* MCHN START */

    txNew.vout.resize(1);

    int prevCanMine=MC_PTP_MINE;
    if(canMine)
    {
        prevCanMine=*canMine;
    }

/* MCHN END */

    txNew.vout[0].scriptPubKey = scriptPubKeyIn;

    // Add dummy coinbase tx as first transaction
    pblock->vtx.push_back(CTransaction());
    pblocktemplate->vTxFees.push_back(-1); // updated at end
    pblocktemplate->vTxSigOps.push_back(-1); // updated at end

    // Largest block you're willing to create:
    unsigned int nBlockMaxSize = GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE);
    // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
    nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));

    // How much of the block should be dedicated to high-priority transactions,
    // included regardless of the fees they pay
    // unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", DEFAULT_BLOCK_PRIORITY_SIZE);
    // nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);

    // Minimum block size you want to create; block will be filled with free transactions
    // until there are no more or the block reaches this size:
    unsigned int nBlockMinSize = GetArg("-blockminsize", DEFAULT_BLOCK_MIN_SIZE);
    nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);

    // Collect memory pool transactions into the block
    CAmount nFees = 0;
    bool fPreservedMempoolOrder=true;

    {
        LOCK2(cs_main, mempool.cs);

        CBlockIndex* pindexPrev = chainActive.Tip();
        const int nHeight = pindexPrev->nHeight + 1;
        if(ppPrev)
        {
            *ppPrev=pindexPrev;
        }
        CCoinsViewCache view(pcoinsTip);

        // Priority order to process transactions
        list<COrphan> vOrphan; // list memory doesn't move
        map<uint256, vector<COrphan*> > mapDependers;
        bool fPrintPriority = GetBoolArg("-printpriority", false);

        // This vector will be sorted into a priority queue:
        vector<TxPriority> vecPriority;
        vecPriority.reserve(mempool.mapTx.size());
/* MCHN START */
// mempool records are processed in the order they were accepted

        set <uint256> setAdded;
/*
        for (map<uint256, CTxMemPoolEntry>::iterator mi = mempool.mapTx.begin();
             mi != mempool.mapTx.end(); ++mi)
        {
            const CTransaction& tx = mi->second.GetTx();
  */

        double orderPriority=mempool.mapTx.size();

        mempool.defragmentHashList();
        for(int pos=0;pos<mempool.hashList->m_Count;pos++)
        {
            uint256 hash;
            hash=*(uint256*)mempool.hashList->GetRow(pos);

            if(!mempool.exists(hash))
            {
                LogPrint("mchn","mchn-miner: Tx not found in the mempool: %s\n",hash.GetHex().c_str());
                fPreservedMempoolOrder=false;
                continue;
            }
            if(IsTxBanned(hash))
            {
                LogPrint("mchn","mchn-miner: Banned Tx: %s\n",hash.GetHex().c_str());
                fPreservedMempoolOrder=false;
                continue;
            }

            const CTransaction& tx = mempool.mapTx[hash].GetTx();
/* MCHN END */

            if (tx.IsCoinBase() || !IsFinalTx(tx, nHeight))
            {
                LogPrint("mchn","mchn-miner: Coinbase or not final tx found: %s\n",tx.GetHash().GetHex().c_str());
                fPreservedMempoolOrder=false;
                continue;
            }

            COrphan* porphan = NULL;
            double dPriority = 0;
            CAmount nTotalIn = 0;
            bool fMissingInputs = false;
            BOOST_FOREACH(const CTxIn& txin, tx.vin)
            {
                // Read prev transaction
                if (!view.HaveCoins(txin.prevout.hash))
                {
                    // This should never happen; all transactions in the memory
                    // pool should connect to either transactions in the chain
                    // or other transactions in the memory pool.
                    if (!mempool.mapTx.count(txin.prevout.hash))
                    {
                        LogPrintf("ERROR: mempool transaction missing input\n");
                        if (fDebug) assert("mempool transaction missing input" == 0);
                        fMissingInputs = true;
                        if (porphan)
                            vOrphan.pop_back();
                        break;
                    }

                    // Has to wait for dependencies
/* MCHN START */
                    if(setAdded.count(txin.prevout.hash) == 0)
                    {
/* MCHN END */
                        if (!porphan)
                        {
                            // Use list for automatic deletion
                            vOrphan.push_back(COrphan(&tx));
                            porphan = &vOrphan.back();
                        }
                        mapDependers[txin.prevout.hash].push_back(porphan);
                        porphan->setDependsOn.insert(txin.prevout.hash);
/* MCHN START */
                    }
/* MCHN END */
                    nTotalIn += mempool.mapTx[txin.prevout.hash].GetTx().vout[txin.prevout.n].nValue;
                    continue;
                }
                const CCoins* coins = view.AccessCoins(txin.prevout.hash);
                assert(coins);

                CAmount nValueIn = coins->vout[txin.prevout.n].nValue;
                nTotalIn += nValueIn;

                int nConf = nHeight - coins->nHeight;

                dPriority += (double)nValueIn * nConf;
            }
            if (fMissingInputs)
            {
                LogPrint("mchn","mchn-miner: Missing inputs for %s\n",tx.GetHash().GetHex().c_str());
                fPreservedMempoolOrder=false;
                continue;
            }

            // Priority is sum(valuein * age) / modified_txsize
            unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
            dPriority = tx.ComputePriority(dPriority, nTxSize);

/* MCHN START */
// Priority ignored - txs are processed in the order they were accepted
            dPriority=orderPriority;
            orderPriority-=1.;

//            uint256 hash = tx.GetHash();
/* MCHN END */
            mempool.ApplyDeltas(hash, dPriority, nTotalIn);

            CFeeRate feeRate(nTotalIn-tx.GetValueOut(), nTxSize);
/* MCHN START */

/* MCHN END */
            if (porphan)
            {
                LogPrint("mchn","mchn-miner: Orphan %s\n",tx.GetHash().GetHex().c_str());
                porphan->dPriority = dPriority;
                porphan->feeRate = feeRate;
                fPreservedMempoolOrder=false;
            }
            else
/* MCHN START */
            {
                setAdded.insert(tx.GetHash());
                vecPriority.push_back(TxPriority(dPriority, feeRate, &tx));
            }
//                vecPriority.push_back(TxPriority(dPriority, feeRate, &mi->second.GetTx()));
/* MCHN END */
        }

        // Collect transactions into block
        uint64_t nBlockSize = 1000;
        uint64_t nBlockTx = 0;
        int nBlockSigOps = 40;
//        bool fSortedByFee = (nBlockPrioritySize <= 0);

/* MCHN START */
        TxPriorityCompare comparer(false);
//        TxPriorityCompare comparer(fSortedByFee);
        bool overblocksize_logged=false;
/* MCHN END */
        std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);

        while (!vecPriority.empty())
        {
            // Take highest priority transaction off the priority queue:
            double dPriority = vecPriority.front().get<0>();
            CFeeRate feeRate = vecPriority.front().get<1>();
            const CTransaction& tx = *(vecPriority.front().get<2>());

            std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
            vecPriority.pop_back();

            // Size limits
            unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
            if (nBlockSize + nTxSize >= nBlockMaxSize)
            {
                if(!overblocksize_logged)
                {
                    overblocksize_logged=true;
                    LogPrint("mchn","mchn-miner: Over block size: %s\n",tx.GetHash().GetHex().c_str());
                }
                continue;
            }
            // Legacy limits on sigOps:
            unsigned int nTxSigOps = GetLegacySigOpCount(tx);
            if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
            {
                LogPrint("mchn","mchn-miner: Over sigop count 1: %s\n",tx.GetHash().GetHex().c_str());
                continue;
            }

            // Skip free transactions if we're past the minimum block size:
            const uint256& hash = tx.GetHash();
            double dPriorityDelta = 0;
            CAmount nFeeDelta = 0;
            mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);
/* MCHN
            if (fSortedByFee && (dPriorityDelta <= 0) && (nFeeDelta <= 0) && (feeRate < ::minRelayTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
                continue;

            // Prioritise by fee once past the priority size or we run out of high-priority
            // transactions:
            if (!fSortedByFee &&
                ((nBlockSize + nTxSize >= nBlockPrioritySize) || !AllowFree(dPriority)))
            {
                fSortedByFee = true;
                comparer = TxPriorityCompare(fSortedByFee);
                std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
            }
*/
            if (!view.HaveInputs(tx))
            {
                LogPrint("mchn","mchn-miner: No inputs for %s\n",tx.GetHash().GetHex().c_str());
                continue;
            }

            CAmount nTxFees = view.GetValueIn(tx)-tx.GetValueOut();

            nTxSigOps += GetP2SHSigOpCount(tx, view);
            if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
            {
                LogPrint("mchn","mchn-miner: Over sigop count 2: %s\n",tx.GetHash().GetHex().c_str());
                continue;
            }

            // Note that flags: we don't want to set mempool/IsStandard()
            // policy here, but we still have to ensure that the block we
            // create only contains transactions that are valid in new blocks.
            CValidationState state;

            if(!fPreservedMempoolOrder)
            {
/* MCHN START */
    //            if (!CheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true))// May fail if send permission was lost
                if (!CheckInputs(tx, state, view, false, 0, true))
/* MCHN END */
                {
                    LogPrint("mchn","mchn-miner: CheckInput failure %s\n",tx.GetHash().GetHex().c_str());
                    continue;
                }

            }
            CTxUndo txundo;
            UpdateCoins(tx, state, view, txundo, nHeight);

            // Added
            pblock->vtx.push_back(tx);
            pblocktemplate->vTxFees.push_back(nTxFees);
            pblocktemplate->vTxSigOps.push_back(nTxSigOps);
            nBlockSize += nTxSize;
            ++nBlockTx;
            nBlockSigOps += nTxSigOps;
            nFees += nTxFees;

            if (fPrintPriority)
            {
                LogPrintf("priority %.1f fee %s txid %s\n",
                    dPriority, feeRate.ToString(), tx.GetHash().ToString());
            }

            // Add transactions that depend on this one to the priority queue
            if (mapDependers.count(hash))
            {
                BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
                {
                    if (!porphan->setDependsOn.empty())
                    {
                        porphan->setDependsOn.erase(hash);
                        if (porphan->setDependsOn.empty())
                        {
                            vecPriority.push_back(TxPriority(porphan->dPriority, porphan->feeRate, porphan->ptx));
                            std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
                        }
                    }
                }
            }
        }

        nLastBlockTx = nBlockTx;
        nLastBlockSize = nBlockSize;

/* MCHN START */
// If block was dropped, this happens too many times
//        LogPrintf("CreateNewBlock(): total size %u\n", nBlockSize);
/* MCHN END */

        // Compute final coinbase transaction.
        txNew.vout[0].nValue = GetBlockValue(nHeight, nFees);
        txNew.vin[0].scriptSig = CScript() << nHeight << OP_0;

        pblock->vSigner[0]=ppubkey->size();
        memcpy(pblock->vSigner+1,ppubkey->begin(),pblock->vSigner[0]);

        pblock->vtx[0] = txNew;
        pblocktemplate->vTxFees[0] = -nFees;

        // Fill in header
        pblock->hashPrevBlock  = pindexPrev->GetBlockHash();
        UpdateTime(pblock, pindexPrev);
        pblock->nBits          = GetNextWorkRequired(pindexPrev, pblock);
        pblock->nNonce         = 0;
        pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]);

/* MCHN START */
        bool testValidity=true;

// If this node cannot mine for some reason (permission or diversity, block is not tested for validity to avoid exception
        if(mc_gState->m_NetworkParams->IsProtocolMultichain())
        {
            if(canMine)
            {
                const unsigned char *pubkey_hash=(unsigned char *)Hash160(ppubkey->begin(),ppubkey->end()).begin();
                *canMine=mc_gState->m_Permissions->CanMine(NULL,pubkey_hash);
                if((*canMine & MC_PTP_MINE) == 0)
                {
                    if(prevCanMine & MC_PTP_MINE)
                    {
                        LogPrintf("mchn: MultiChainMiner: cannot mine now, waiting...\n");
                    }
                    testValidity=false;
                }
                else
                {
                    if((prevCanMine & MC_PTP_MINE) == 0)
                    {
                        LogPrintf("CreateNewBlock(): total size %u\n", nBlockSize);
                        LogPrintf("mchn: MultiChainMiner: Starting mining...\n");
                    }
                }
            }
        }
        else
        {
            LogPrintf("CreateNewBlock(): total size %u\n", nBlockSize);
        }

        if(GetBoolArg("-avoidtestingblockvalidity",true))
        {
            testValidity=false;
        }

        if(testValidity)
        {
/* MCHN END */

        CValidationState state;
        if (!TestBlockValidity(state, *pblock, pindexPrev, false, false))
            throw std::runtime_error("CreateNewBlock() : TestBlockValidity failed");

/* MCHN START */
        }
/* MCHN END */
    }

    return pblocktemplate.release();
}

/* MCHN START */
CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn)
{
    return CreateNewBlock(scriptPubKeyIn,NULL,NULL,NULL,NULL);
}
/* MCHN END */

void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce,CWallet *pwallet)
{
    // Update nExtraNonce
    static uint256 hashPrevBlock;
    if (hashPrevBlock != pblock->hashPrevBlock)
    {
        nExtraNonce = 0;
        hashPrevBlock = pblock->hashPrevBlock;
    }
    ++nExtraNonce;
    unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
    CMutableTransaction txCoinbase(pblock->vtx[0]);
    txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS;
    assert(txCoinbase.vin[0].scriptSig.size() <= 100);

    pblock->vtx[0] = txCoinbase;

/* MCHN START */
    CreateBlockSignature(pblock,BLOCKSIGHASH_NO_SIGNATURE_AND_NONCE,pwallet);
    pblock->hashMerkleRoot = pblock->BuildMerkleTree();
/* MCHN END */
}

#ifdef ENABLE_WALLET
//////////////////////////////////////////////////////////////////////////////
//
// Internal miner
//
double dHashesPerSec = 0.0;
int64_t nHPSTimerStart = 0;

//
// ScanHash scans nonces looking for a hash with at least some zero bits.
// The nonce is usually preserved between calls, but periodically or if the
// nonce is 0xffff0000 or above, the block is rebuilt and nNonce starts over at
// zero.
//
bool static ScanHash(const CBlockHeader *pblock, uint32_t& nNonce, uint256 *phash,uint16_t success_and_mask)
{
    // Write the first 76 bytes of the block header to a double-SHA256 state.
    CHash256 hasher;
    CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
    ss << *pblock;
    assert(ss.size() == 80);
    hasher.Write((unsigned char*)&ss[0], 76);
    while (true) {
        nNonce++;

        // Write the last 4 bytes of the block header (the nonce) to a copy of
        // the double-SHA256 state, and compute the result.
        CHash256(hasher).Write((unsigned char*)&nNonce, 4).Finalize((unsigned char*)phash);

        // Return the nonce if the hash has at least some zero bits,
        // caller will check if it has enough to reach the target
/*
        if (((uint16_t*)phash)[15] == 0)
            return true;
*/
        if( (((uint16_t*)phash)[15] & success_and_mask) == 0)
        {
            return true;
        }

        // If nothing found after trying for a while, return -1
        if ((nNonce & 0xffff) == 0)
//        if ((nNonce & 0xff) == 0)
            return false;
        if ((nNonce & 0xfff) == 0)
            boost::this_thread::interruption_point();
    }
}

CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey)
{
    CPubKey pubkey;
    if (!reservekey.GetReservedKey(pubkey))
        return NULL;

    CScript scriptPubKey = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
    return CreateNewBlock(scriptPubKey);
}

/* MCHN START */
// Block should be mined for specific keys, not just any from pool

CBlockTemplate* CreateNewBlockWithDefaultKey(CWallet *pwallet,int *canMine,const set<CTxDestination>* addresses,CBlockIndex** ppPrev)
{
    CPubKey pubkey;
    bool key_found;

    {
        LOCK(cs_main);
        key_found=pwallet->GetKeyFromAddressBook(pubkey,MC_PTP_MINE,addresses);
    }
    if(!key_found)
    {
        if(canMine)
        {
            if(*canMine & MC_PTP_MINE)
            {
                *canMine=0;
                LogPrintf("mchn: Cannot find address having mining permission\n");
            }
        }
        return NULL;
    }

    const unsigned char *pubkey_hash=(unsigned char *)Hash160(pubkey.begin(),pubkey.end()).begin();

    CScript scriptPubKey = CScript() << OP_DUP << OP_HASH160 << vector<unsigned char>(pubkey_hash, pubkey_hash + 20) << OP_EQUALVERIFY << OP_CHECKSIG;

    return CreateNewBlock(scriptPubKey,pwallet,&pubkey,canMine,ppPrev);
}

/* MCHN END */

bool ProcessBlockFound(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
{
    if(fDebug)LogPrint("mchnminor","%s\n", pblock->ToString());
    if(fDebug)LogPrint("mcminer","mchn-miner: generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue));

    // Found a solution
    {
        LOCK(cs_main);
        if(mc_gState->m_NodePausedState & MC_NPS_MINING)
        {
            return error("MultiChainMiner : mining is paused, generated block is dropped");
        }
        if (pblock->hashPrevBlock != chainActive.Tip()->GetBlockHash())
        {
            return error("MultiChainMiner : generated block is stale");
        }
    }

    // Remove key from key pool
    reservekey.KeepKey();

    // Track how many getdata requests this block gets
    {
        LOCK(wallet.cs_wallet);
        wallet.mapRequestCount[pblock->GetHash()] = 0;
    }

    // Process this block the same as if we had received it from another node
    CValidationState state;
    if (!ProcessNewBlock(state, NULL, pblock))
        return error("MultiChainMiner : ProcessNewBlock, block not accepted");

    return true;
}

set <CTxDestination> LastActiveMiners(CBlockIndex* pindexTip, CPubKey *kLastMiner, int nMinerPoolSize)
{
    int nRelativeWindowSize=5;

    int nTotalMiners=mc_gState->m_Permissions->GetMinerCount();
    int nActiveMiners=mc_gState->m_Permissions->GetActiveMinerCount();
    int nDiversityMiners=0;
    int nWindowSize;
    CBlockIndex* pindex;
    set <CTxDestination> sMiners;

    if(mc_gState->m_NetworkParams->IsProtocolMultichain() == 0)
    {
        return sMiners;
    }

    if(MCP_ANYONE_CAN_MINE == 0)
    {
       nDiversityMiners=nTotalMiners-nActiveMiners;
    }

    nWindowSize=nRelativeWindowSize*nMinerPoolSize+nDiversityMiners;

    pindex=pindexTip;
    for(int i=0;i<nWindowSize;i++)
    {
        if((int)sMiners.size() < nMinerPoolSize)
        {
            if(pindex)
            {
                if(!pindex->kMiner.IsValid())
                {
                    CBlock block;
                    if(ReadBlockFromDisk(block,pindex))
                    {
                        if(block.vSigner[0])
                        {
                            pindex->kMiner.Set(block.vSigner+1, block.vSigner+1+block.vSigner[0]);
                        }
                    }
                }
                if(pindex->kMiner.IsValid())
                {
                    CKeyID addr=pindex->kMiner.GetID();
                    if(mc_gState->m_Permissions->CanMine(NULL,addr.begin()))
                    {
                        if(sMiners.find(addr) == sMiners.end())
                        {
                            sMiners.insert(addr);
                        }
                    }
                }
                if(pindex == pindexTip)
                {
                    *kLastMiner=pindex->kMiner;
                }
                pindex=pindex->pprev;
            }
        }
    }

    return sMiners;
}

int GetMaxActiveMinersCount()
{
    if(mc_gState->m_NetworkParams->IsProtocolMultichain())
    {
        if(MCP_ANYONE_CAN_MINE)
        {
            return 1048576;
        }
        else
        {
            return mc_gState->m_Permissions->GetActiveMinerCount();
        }
    }
    else
    {
        return 1024;
    }
}

double GetMinerAndExpectedMiningStartTime(CWallet *pwallet,CPubKey *lpkMiner,set <CTxDestination> *lpsMinerPool,double *lpdMiningStartTime,double *lpdActiveMiners,uint256 *lphLastBlockHash,int *lpnMemPoolSize)
{
    int nMinerPoolSizeMin=4;
    int nMinerPoolSizeMax=16;
    double dRelativeSpread=1.;
    double dRelativeMinerPoolSize=0.25;
    double dAverageCreateBlockTime=2;
    double dMinerDriftMin=mc_gState->m_NetworkParams->ParamAccuracy();
    double dEmergencyMinersConvergenceRate=2.;
    int nPastBlocks=12;

    set <CTxDestination> sPrevMinerPool;
    set <CTxDestination> sThisMinerPool;
    CBlockIndex* pindex;
    CBlockIndex* pindexTip;
    CPubKey kLastMiner;
    CPubKey kThisMiner;

    bool fNewBlock=false;
    bool fWaitingForMiner=false;
    bool fInMinerPool;
    int nMinerPoolSize,nStdMinerPoolSize,nWindowSize;
    double dTargetSpacing,dSpread,dExpectedTimeByLast,dExpectedTimeByPast,dEmergencyMiners,dExpectedTime,dExpectedTimeMin,dExpectedTimeMax,dAverageGap;
    double dMinerDrift,dActualMinerDrift;

    pindexTip = chainActive.Tip();

    if(*lpdMiningStartTime >= 0)
    {
        if(*lphLastBlockHash == pindexTip->GetBlockHash())
        {
            if( (*lpnMemPoolSize > 0) || (mempool.hashList->m_Count == 0) )
            {
                if(lpkMiner->IsValid())
                {
                    return *lpdMiningStartTime;
                }
                else
                {
                    fWaitingForMiner=true;
                    fNewBlock=true;
                }
            }
        }
        else
        {
            fNewBlock=true;
        }
    }
    else
    {
        fNewBlock=true;
    }

    *lphLastBlockHash=pindexTip->GetBlockHash();
    *lpnMemPoolSize=mempool.hashList->m_Count;

    if( (Params().Interval() > 0) ||                                            // POW
        (mc_gState->m_Permissions->m_Block <= 1) )
    {
        pwallet->GetKeyFromAddressBook(kThisMiner,MC_PTP_MINE);
        *lpkMiner=kThisMiner;
        *lpdMiningStartTime=mc_TimeNowAsDouble();                               // start mining immediately
        return *lpdMiningStartTime;
    }

    dMinerDrift=Params().MiningTurnover();
    if(dMinerDrift > 1.0)
    {
        dMinerDrift=1.0;
    }
    dMinerDrift-=dMinerDriftMin;
    if(dMinerDrift < 0)
    {
        dMinerDrift=0.;
    }

    dTargetSpacing=Params().TargetSpacing();
    dSpread=dRelativeSpread*dTargetSpacing;

    *lpdMiningStartTime=mc_TimeNowAsDouble() + 0.5 * dTargetSpacing;
    dExpectedTimeByLast=pindexTip->dTimeReceived+dTargetSpacing;
    if(dExpectedTimeByLast < mc_TimeNowAsDouble() + dTargetSpacing - 0.5 * dSpread) // Can happen while in reorg or if dTimeReceived is not set
    {
        dExpectedTimeByLast=mc_TimeNowAsDouble() + dTargetSpacing;
        *lpdMiningStartTime=dExpectedTimeByLast;
        fNewBlock=false;
    }
    dExpectedTimeMin=dExpectedTimeByLast - 0.5 * dSpread;
    dExpectedTimeMax=dExpectedTimeByLast + 0.5 * dSpread;

    dAverageGap=0;
    nWindowSize=0;
    if(fNewBlock)
    {
        pindex=pindexTip;
        dExpectedTimeByPast=0;
        for(int i=0;i<nPastBlocks;i++)
        {
            if(pindex && (pindex->dTimeReceived > 0.5))
            {
                dExpectedTimeByPast+=pindex->dTimeReceived;
                nWindowSize++;
                dAverageGap=pindex->dTimeReceived;
                pindex=pindex->pprev;
            }
        }

        dAverageGap=(dExpectedTimeByLast-dAverageGap) / nWindowSize;

        dExpectedTimeByPast /= nWindowSize;
        dExpectedTimeByPast += (nWindowSize + 1) * 0.5 * dTargetSpacing;

        if(dAverageGap < 0.5*dTargetSpacing)                                    // Catching up
        {
            dExpectedTime=mc_TimeNowAsDouble() + dTargetSpacing;
            nWindowSize=0;
        }
        else
        {
            if(nWindowSize < nPastBlocks)
            {
                dExpectedTime=dExpectedTimeByLast;
            }
            else
            {
                dExpectedTime=dExpectedTimeByPast;
                if(dExpectedTime > dExpectedTimeMax)
                {
                    dExpectedTime = dExpectedTimeMax;
                }
                if(dExpectedTime < dExpectedTimeMin)
                {
                    dExpectedTime = dExpectedTimeMin;
                }
            }
        }

        *lpdMiningStartTime=dExpectedTime;
    }

    fInMinerPool=false;
    if(mc_gState->m_NetworkParams->IsProtocolMultichain())
    {
        sPrevMinerPool=*lpsMinerPool;
        nStdMinerPoolSize=(int)(dRelativeMinerPoolSize * dSpread / dAverageCreateBlockTime);
        if(nStdMinerPoolSize < nMinerPoolSizeMin)
        {
            nStdMinerPoolSize=nMinerPoolSizeMin;
        }
        if(nStdMinerPoolSize > nMinerPoolSizeMax)
        {
            nStdMinerPoolSize=nMinerPoolSizeMax;
        }
        nMinerPoolSize=nStdMinerPoolSize;
        nStdMinerPoolSize=(int)(dMinerDrift * nStdMinerPoolSize) + 1;

        dActualMinerDrift=dMinerDrift;
        if(dActualMinerDrift < dMinerDriftMin)
        {
            dActualMinerDrift=dMinerDriftMin;
        }

        sThisMinerPool=LastActiveMiners(pindexTip,&kLastMiner,nStdMinerPoolSize);
        nMinerPoolSize=sThisMinerPool.size();
        *lpsMinerPool=sThisMinerPool;

        fInMinerPool=false;
        if(!pwallet->GetKeyFromAddressBook(kThisMiner,MC_PTP_MINE,&sThisMinerPool))
        {
            pwallet->GetKeyFromAddressBook(kThisMiner,MC_PTP_MINE);
        }
        else
        {
            fInMinerPool=true;
        }

        if( fInMinerPool ||
            (sPrevMinerPool.find(kLastMiner.GetID()) == sPrevMinerPool.end()) ||
            (*lpdActiveMiners < -0.5) )
        {
            *lpdActiveMiners=(double)GetMaxActiveMinersCount() - nMinerPoolSize;
            *lpdActiveMiners/=dActualMinerDrift;
        }
        *lpdActiveMiners *= (1. - dActualMinerDrift);
        if(*lpdActiveMiners < 1.0)
        {
            *lpdActiveMiners=1;
        }
        if(dMinerDrift >= dMinerDriftMin)
        {
            if(!fInMinerPool)
            {
                if( (*lpdActiveMiners < 0.5) || ( mc_RandomDouble() < dMinerDrift /(*lpdActiveMiners)))
                {
                    fInMinerPool=true;
                    nMinerPoolSize++;
                }
            }
        }
        if(fInMinerPool)
        {
            *lpdActiveMiners=(double)GetMaxActiveMinersCount() - nMinerPoolSize;
            *lpdActiveMiners/=dActualMinerDrift;
        }

        if(fInMinerPool)
        {
            *lpdMiningStartTime += mc_RandomDouble() * dSpread;
            *lpdMiningStartTime -= dSpread / (nMinerPoolSize + 1);
        }
        else
        {
            dEmergencyMiners=(double)GetMaxActiveMinersCount();
            *lpdMiningStartTime=dExpectedTimeMax;
            *lpdMiningStartTime += dSpread;
            *lpdMiningStartTime -= dSpread / (nMinerPoolSize + 1);
            *lpdMiningStartTime += dAverageCreateBlockTime + mc_RandomDouble() * dAverageCreateBlockTime;
            while( (dEmergencyMiners > 0.5) && (mc_RandomDouble() > 1./(dEmergencyMiners)))
            {
                *lpdMiningStartTime += dAverageCreateBlockTime;
                dEmergencyMiners /= dEmergencyMinersConvergenceRate;
            }
        }
    }
    else
    {
        pwallet->GetKeyFromAddressBook(kThisMiner,MC_PTP_MINE);
        dEmergencyMiners=(double)GetMaxActiveMinersCount();
        while(dEmergencyMiners > 0.5)
        {
            *lpdMiningStartTime -= dAverageCreateBlockTime / 2;
            dEmergencyMiners /= dEmergencyMinersConvergenceRate;
        }
        if(*lpdMiningStartTime < dExpectedTimeMin)
        {
            *lpdMiningStartTime = dExpectedTimeMin;
        }
        dEmergencyMiners=(double)GetMaxActiveMinersCount();
        while( (dEmergencyMiners > 0.5) && (mc_RandomDouble() > 1./(dEmergencyMiners)))
        {
            *lpdMiningStartTime += dAverageCreateBlockTime;
            dEmergencyMiners /= dEmergencyMinersConvergenceRate;
        }
    }

    if(!fWaitingForMiner)
    {
        if(kThisMiner.IsValid())
        {
            CBitcoinAddress addr=CBitcoinAddress(kThisMiner.GetID());
            LogPrint("mcminer","mchn-miner: delay: %8.3fs, miner: %s, height: %d, gap: %8.3fs, miners: (tot: %d, max: %d, pool: %d)%s\n",
                             *lpdMiningStartTime-mc_TimeNowAsDouble(),addr.ToString().c_str(),
                             chainActive.Tip()->nHeight,dAverageGap,
                             mc_gState->m_Permissions->GetMinerCount(),GetMaxActiveMinersCount(),
                             nMinerPoolSize,fInMinerPool ? ( (nMinerPoolSize > (int)lpsMinerPool->size()) ? " In Pool New" : " In Pool Old" )  : " Not In Pool");
        }
        else
        {
            LogPrint("mcminer","mchn-miner: miner not found, height: %d, gap: %8.3fs, miners: (tot: %d, max: %d, pool: %d)\n",
                             chainActive.Tip()->nHeight,dAverageGap,
                             mc_gState->m_Permissions->GetMinerCount(),GetMaxActiveMinersCount(),
                             nMinerPoolSize);
        }
    }
    *lpkMiner=kThisMiner;
    return *lpdMiningStartTime;
}

void static BitcoinMiner(CWallet *pwallet)
{
    LogPrintf("MultiChainMiner started\n");
    SetThreadPriority(THREAD_PRIORITY_LOWEST);
    RenameThread("bitcoin-miner");

    // Each thread has its own key and counter
    CReserveKey reservekey(pwallet);
    unsigned int nExtraNonce = 0;

/* MCHN START */
    int canMine;
    int prevCanMine;
    canMine=MC_PTP_MINE;
    prevCanMine=canMine;

    double dActiveMiners=-1;
    double dMiningStartTime=-1.;
    uint256 hLastBlockHash=0;
    int nMemPoolSize=0;
    set <CTxDestination> sMinerPool;
    CPubKey kMiner;

    int wSize=10;
    int wPos=0;
    int EmptyBlockToMine;
    uint64_t wCount[10];
    double wTime[10];
    memset(wCount,0,wSize*sizeof(uint64_t));
    memset(wTime,0,wSize*sizeof(uint64_t));

    uint16_t success_and_mask=0xffff;
    int min_bits;

    if(Params().Interval() <= 0)
    {
        min_bits=(int)mc_gState->m_NetworkParams->GetInt64Param("powminimumbits");
        if(min_bits < 16)
        {
            success_and_mask = success_and_mask << (16 - min_bits);
        }
    }

/* MCHN END */

    try {
        while (true) {
/* MCHN START */
            bool not_setup_period=true;

            if(mc_gState->m_NodePausedState & MC_NPS_MINING)
            {
                __US_Sleep(1000);
                boost::this_thread::interruption_point();
            }

            if(mc_gState->m_NetworkParams->IsProtocolMultichain())
            {
                if((canMine & MC_PTP_MINE) == 0)
                {
                    if(mc_gState->m_Permissions->m_Block > 1)
                    {
                        __US_Sleep(1000);
                    }
                    boost::this_thread::interruption_point();
                }
                if(mc_gState->m_Permissions->IsSetupPeriod())
                {
                    not_setup_period=false;
                }
                if(mc_gState->m_Permissions->m_Block <= 1)
                {
                    not_setup_period=false;
                }
            }

            if (Params().MiningRequiresPeers()
                    && not_setup_period
                    && ( (mc_gState->m_Permissions->GetMinerCount() > 1)
                    || (MCP_ANYONE_CAN_MINE != 0)
                    || (mc_gState->m_NetworkParams->IsProtocolMultichain() == 0)
                    )
                    ) {

                // Busy-wait for the network to come online so we don't waste time mining
                // on an obsolete chain. In regtest mode we expect to fly solo.

                bool wait_for_peers=true;
                if(wait_for_peers)
                {
                    int active_nodes=0;
                    while ((active_nodes == 0) &&
                           ( (mc_gState->m_Permissions->GetMinerCount() > 1)
                          || (MCP_ANYONE_CAN_MINE != 0)
                          || (mc_gState->m_NetworkParams->IsProtocolMultichain() == 0)
                           ) && Params().MiningRequiresPeers())
                    {
                        vector<CNode*> vNodesCopy = vNodes;
                        BOOST_FOREACH(CNode* pnode, vNodesCopy)
                        {
                            if(pnode->fSuccessfullyConnected)
                            {
                                active_nodes++;
                            }
                        }

                        if(active_nodes == 0)
                        {
                            MilliSleep(1000);
                            boost::this_thread::interruption_point();
                        }
                    }
                }
            }

            //
            // Create new block
            //
            unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
            CBlockIndex* pindexPrev = chainActive.Tip();
            EmptyBlockToMine=0;

            bool fMineEmptyBlocks=true;
            if(Params().MineEmptyRounds()+mc_gState->m_NetworkParams->ParamAccuracy()>= 0)
            {
                fMineEmptyBlocks=false;
                CBlockIndex* pindex=pindexPrev;
                int nMaxEmptyBlocks,nEmptyBlocks,nMinerCount;

                nMaxEmptyBlocks=0;
                nEmptyBlocks=0;
                if(mc_gState->m_NetworkParams->IsProtocolMultichain())
                {
                    nMinerCount=1;
                    if(MCP_ANYONE_CAN_MINE == 0)
                    {
                        nMinerCount=mc_gState->m_Permissions->GetMinerCount()-mc_gState->m_Permissions->GetActiveMinerCount()+1;
                    }
                    double d=Params().MineEmptyRounds()*nMinerCount-mc_gState->m_NetworkParams->ParamAccuracy();
                    if(d >= 0)
                    {
                        nMaxEmptyBlocks=(int)d+1;
                    }

                    fMineEmptyBlocks=false;
                    while(!fMineEmptyBlocks && (pindex != NULL) && (nEmptyBlocks < nMaxEmptyBlocks))
                    {
                        if(pindex->nTx > 1)
                        {
                            fMineEmptyBlocks=true;
                        }
                        else
                        {
                            nEmptyBlocks++;
                            pindex=pindex->pprev;
                        }
                    }
                    if(pindex == NULL)
                    {
                        fMineEmptyBlocks=true;
                    }
                }
                else
                {
                    fMineEmptyBlocks=true;
                }
            }
            if(!fMineEmptyBlocks)
            {
                if(chainActive.Tip()->nHeight <= LastForkedHeight())
                {
                    EmptyBlockToMine=chainActive.Tip()->nHeight+1;
                    LogPrint("mcminer","mchn-miner: Chain is forked on height %d, ignoring mine-empty-rounds, mining on height %d\n", LastForkedHeight(),chainActive.Tip()->nHeight+1);
                    fMineEmptyBlocks=true;
                }
            }
            if(fMineEmptyBlocks)
            {
                nMemPoolSize=1;
            }

            canMine=MC_PTP_MINE;
            if(mc_TimeNowAsDouble() < GetMinerAndExpectedMiningStartTime(pwallet, &kMiner,&sMinerPool, &dMiningStartTime,&dActiveMiners,&hLastBlockHash,&nMemPoolSize))
            {
                canMine=0;
            }
            else
            {
                if(!kMiner.IsValid())
                {
                    canMine=0;
                }
                else
                {
                    if( !fMineEmptyBlocks
                            && not_setup_period
                            && (mempool.hashList->m_Count == 0)
                            )
                    {
                        canMine=0;
                    }
                    else
                    {
                        if(!CanMineWithLockedBlock())
                        {
                            canMine=0;
                        }
                    }
                }
            }

//            if(mc_gState->m_ProtocolVersionToUpgrade > mc_gState->m_NetworkParams->ProtocolVersion())
            if( (mc_gState->m_ProtocolVersionToUpgrade > 0) && (mc_gState->IsSupported(mc_gState->m_ProtocolVersionToUpgrade) == 0) )
            {
                canMine=0;
            }

            if(mc_gState->m_NodePausedState & MC_NPS_MINING)
            {
                canMine=0;
            }

            if(fReindex)
            {
                canMine=0;
            }

            if(canMine & MC_PTP_MINE)
            {
                const unsigned char *pubkey_hash=(unsigned char *)Hash160(kMiner.begin(),kMiner.end()).begin();
                CScript scriptPubKey = CScript() << OP_DUP << OP_HASH160 << vector<unsigned char>(pubkey_hash, pubkey_hash + 20) << OP_EQUALVERIFY << OP_CHECKSIG;
                canMine=prevCanMine;
                auto_ptr<CBlockTemplate> pblocktemplate(CreateNewBlock(scriptPubKey,pwallet,&kMiner,&canMine,&pindexPrev));
                prevCanMine=canMine;
/* MCHN END */
            if (!pblocktemplate.get())
            {
                LogPrintf("Error in MultiChainMiner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n");
                return;
            }
            CBlock *pblock = &pblocktemplate->block;
            IncrementExtraNonce(pblock, pindexPrev, nExtraNonce,pwallet);

            LogPrint("mcminer","mchn-miner: Running MultiChainMiner with %u transactions in block (%u bytes)\n", pblock->vtx.size(),
                ::GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION));

            //
            // Search
            //
            int64_t nStart = GetTime();
            uint256 hashTarget = uint256().SetCompact(pblock->nBits);
            uint256 hash;
            uint32_t nNonce = 0;
            uint32_t nOldNonce = 0;

            double wStartTime=mc_TimeNowAsDouble();
            uint64_t wThisCount=0;
            while (true) {

                if(EmptyBlockToMine)
                {
                    if(chainActive.Tip()->nHeight != EmptyBlockToMine-1)
                    {
                        LogPrint("mcminer","mchn-miner: Avoiding mining block %d, required %d\n", chainActive.Tip()->nHeight+1,EmptyBlockToMine);
                        break;
                    }
                }

                bool fFound = ScanHash(pblock, nNonce, &hash, success_and_mask);
                uint32_t nHashesDone = nNonce - nOldNonce;
                nOldNonce = nNonce;

                wThisCount+=nHashesDone;

                // Check if something found
                if (fFound)
                {
                    if (hash <= hashTarget)
                    {
                        // Found a solution
                        pblock->nNonce = nNonce;
                        assert(hash == pblock->GetHash());

                        SetThreadPriority(THREAD_PRIORITY_NORMAL);

                        LogPrintf("MultiChainMiner: Block Found - %s, prev: %s, height: %d, txs: %d\n",
                                hash.GetHex(),pblock->hashPrevBlock.ToString().c_str(),mc_gState->m_Permissions->m_Block+1,(int)pblock->vtx.size());
/*
                        LogPrintf("MultiChainMiner:\n");
                        LogPrintf("proof-of-work found  \n  hash: %s  \ntarget: %s\n", hash.GetHex(), hashTarget.GetHex());
*/
/* MCHN START */
//                        if(mc_gState->m_ProtocolVersionToUpgrade > mc_gState->m_NetworkParams->ProtocolVersion())
                        if( (mc_gState->m_ProtocolVersionToUpgrade > 0) && (mc_gState->IsSupported(mc_gState->m_ProtocolVersionToUpgrade) == 0) )
                        {
                            LogPrintf("MultiChainMiner: Waiting for upgrade, block is dropped\n");
                        }
                        else
                        {
                            if(!ProcessBlockFound(pblock, *pwallet, reservekey))
                            {
                                __US_Sleep(1000);
                                boost::this_thread::interruption_point();
                            }
                        }
/* MCHN END */

                        SetThreadPriority(THREAD_PRIORITY_LOWEST);

                        // In regression test mode, stop mining after a block is found.
                        if (Params().MineBlocksOnDemand())
                            throw boost::thread_interrupted();

                        break;
                    }
                }

                // Meter hashes/sec
                static int64_t nHashCounter;
                if (nHPSTimerStart == 0)
                {
                    nHPSTimerStart = GetTimeMillis();
                    nHashCounter = 0;
                }
                else
                    nHashCounter += nHashesDone;
                if (GetTimeMillis() - nHPSTimerStart > 4000)
                {
                    static CCriticalSection cs;
                    {
                        LOCK(cs);
                        if (GetTimeMillis() - nHPSTimerStart > 4000)
                        {
                            dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
                            nHPSTimerStart = GetTimeMillis();
                            nHashCounter = 0;
                            static int64_t nLogTime;
                            if (GetTime() - nLogTime > 30 * 60)
                            {
                                nLogTime = GetTime();
                                LogPrintf("hashmeter %6.0f khash/s\n", dHashesPerSec/1000.0);
                            }
                        }
                    }
                }

                // Check for stop or if block needs to be rebuilt
                boost::this_thread::interruption_point();
                // Regtest mode doesn't require peers
                if (vNodes.empty() && Params().MiningRequiresPeers()
                        && not_setup_period
                        && ( (mc_gState->m_Permissions->GetMinerCount() > 1)
                        || (MCP_ANYONE_CAN_MINE != 0)
                        || (mc_gState->m_NetworkParams->IsProtocolMultichain() == 0)
                        )
                        )
                {
//                if (vNodes.empty() && Params().MiningRequiresPeers() && not_setup_period)
                    break;
                }
                if (nNonce >= 0xffff0000)
                    break;
                if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
                    break;
                if (pindexPrev != chainActive.Tip())
                    break;

                // Update nTime every few seconds

                if(UpdateTime(pblock, pindexPrev))
                {
/* MCHN START */
                    CreateBlockSignature(pblock,BLOCKSIGHASH_NO_SIGNATURE_AND_NONCE,pwallet);
/* MCHN END */
                }
                if (Params().AllowMinDifficultyBlocks())
                {
                    // Changing pblock->nTime can change work required on testnet:
                    hashTarget.SetCompact(pblock->nBits);
                }
            }
/* MCHN START */
            double wTimeNow=mc_TimeNowAsDouble();
//            if(wTimeNow>wStartTime+100)
            if(wTimeNow>wStartTime+0.01)
            {
                wCount[wPos]=wThisCount;
                wTime[wPos]=wTimeNow-wStartTime;
                wPos=(wPos+1)%wSize;
                dHashesPerSec=wThisCount/(wTimeNow-wStartTime);
            }

            }
            else
            {
                if(mc_gState->m_Permissions->m_Block > 1)
                {
                    __US_Sleep(100);
                }
            }
/* MCHN END */
        }
    }
    catch (boost::thread_interrupted)
    {
        LogPrintf("MultiChainMiner terminated\n");
        throw;
    }
}

void GenerateBitcoins(bool fGenerate, CWallet* pwallet, int nThreads)
{
    static boost::thread_group* minerThreads = NULL;

    if (nThreads < 0) {
        // In regtest threads defaults to 1
        if (Params().DefaultMinerThreads())
            nThreads = Params().DefaultMinerThreads();
        else
            nThreads = boost::thread::hardware_concurrency();
    }

    if (minerThreads != NULL)
    {
        minerThreads->interrupt_all();
/* MCHN START */
        minerThreads->join_all();
/* MCHN END */

        delete minerThreads;
        minerThreads = NULL;
    }

    if (nThreads == 0 || !fGenerate)
        return;

    minerThreads = new boost::thread_group();
    for (int i = 0; i < nThreads; i++)
        minerThreads->create_thread(boost::bind(&BitcoinMiner, pwallet));
}

#endif // ENABLE_WALLET

max_stars_repo_name: VersumDEX/VersumClient

max_issues_repo_name: VersumDEX/VersumClient

max_forks_repo_name: VersumDEX/VersumClient


text: #include <boost/container/slist.hpp>

ext: hpp

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#ifndef SIMPLE_WEB_CLIENT_WSS_HPP
#define SIMPLE_WEB_CLIENT_WSS_HPP

#include "client_ws.hpp"

#ifdef USE_STANDALONE_ASIO
#include <asio/ssl.hpp>
#else
#include <boost/asio/ssl.hpp>
#endif

namespace SimpleWeb {
  using WSS = asio::ssl::stream<asio::ip::tcp::socket>;

  template <>
  class SocketClient<WSS> : public SocketClientBase<WSS> {
  public:
    SocketClient(const std::string &server_port_path, bool verify_certificate = true,
                 const std::string &cert_file = std::string(), const std::string &private_key_file = std::string(),
                 const std::string &verify_file = std::string())
        : SocketClientBase<WSS>::SocketClientBase(server_port_path, 443), context(asio::ssl::context::tlsv12) {
      if(cert_file.size() > 0 && private_key_file.size() > 0) {
        context.use_certificate_chain_file(cert_file);
        context.use_private_key_file(private_key_file, asio::ssl::context::pem);
      }

      if(verify_certificate)
        context.set_verify_callback(asio::ssl::rfc2818_verification(host));

      if(verify_file.size() > 0)
        context.load_verify_file(verify_file);
      else
        context.set_default_verify_paths();

      if(verify_file.size() > 0 || verify_certificate)
        context.set_verify_mode(asio::ssl::verify_peer);
      else
        context.set_verify_mode(asio::ssl::verify_none);
    };

  protected:
    asio::ssl::context context;

    void connect() override {
      LockGuard connection_lock(connection_mutex);
      auto connection = this->connection = std::shared_ptr<Connection>(new Connection(handler_runner, config.timeout_idle, *io_service, context));
      connection_lock.unlock();

      std::pair<std::string, std::string> host_port;
      if(config.proxy_server.empty())
        host_port = {host, std::to_string(port)};
      else {
        auto proxy_host_port = parse_host_port(config.proxy_server, 8080);
        host_port = {proxy_host_port.first, std::to_string(proxy_host_port.second)};
      }

      auto resolver = std::make_shared<asio::ip::tcp::resolver>(*io_service);
      connection->set_timeout(config.timeout_request);
      async_resolve(*resolver, host_port, [this, connection, resolver](const error_code &ec, resolver_results results) {
        connection->cancel_timeout();
        auto lock = connection->handler_runner->continue_lock();
        if(!lock)
          return;
        if(!ec) {
          connection->set_timeout(this->config.timeout_request);
          asio::async_connect(connection->socket->lowest_layer(), results, [this, connection, resolver](const error_code &ec, async_connect_endpoint /*endpoint*/) {
            connection->cancel_timeout();
            auto lock = connection->handler_runner->continue_lock();
            if(!lock)
              return;
            if(!ec) {
              asio::ip::tcp::no_delay option(true);
              error_code ec;
              connection->socket->lowest_layer().set_option(option, ec);

              if(!this->config.proxy_server.empty()) {
                auto write_buffer = std::make_shared<asio::streambuf>();
                std::ostream write_stream(write_buffer.get());
                auto host_port = this->host + ':' + std::to_string(this->port);
                write_stream << "CONNECT " + host_port + " HTTP/1.1\r\n"
                             << "Host: " << host_port << "\r\n\r\n";
                connection->set_timeout(this->config.timeout_request);
                asio::async_write(connection->socket->next_layer(), *write_buffer, [this, connection, write_buffer](const error_code &ec, std::size_t /*bytes_transferred*/) {
                  connection->cancel_timeout();
                  auto lock = connection->handler_runner->continue_lock();
                  if(!lock)
                    return;
                  if(!ec) {
                    connection->set_timeout(this->config.timeout_request);
                    asio::async_read_until(connection->socket->next_layer(), connection->in_message->streambuf, "\r\n\r\n", [this, connection](const error_code &ec, std::size_t /*bytes_transferred*/) {
                      connection->cancel_timeout();
                      auto lock = connection->handler_runner->continue_lock();
                      if(!lock)
                        return;
                      if(!ec) {
                        if(!ResponseMessage::parse(*connection->in_message, connection->http_version, connection->status_code, connection->header))
                          this->connection_error(connection, make_error_code::make_error_code(errc::protocol_error));
                        else {
                          if(connection->status_code.compare(0, 3, "200") != 0)
                            this->connection_error(connection, make_error_code::make_error_code(errc::permission_denied));
                          else
                            this->handshake(connection);
                        }
                      }
                      else
                        this->connection_error(connection, ec);
                    });
                  }
                  else
                    this->connection_error(connection, ec);
                });
              }
              else
                this->handshake(connection);
            }
            else
              this->connection_error(connection, ec);
          });
        }
        else
          this->connection_error(connection, ec);
      });
    }

    void handshake(const std::shared_ptr<Connection> &connection) {
      SSL_set_tlsext_host_name(connection->socket->native_handle(), this->host.c_str());

      connection->set_timeout(this->config.timeout_request);
      connection->socket->async_handshake(asio::ssl::stream_base::client, [this, connection](const error_code &ec) {
        connection->cancel_timeout();
        auto lock = connection->handler_runner->continue_lock();
        if(!lock)
          return;
        if(!ec)
          upgrade(connection);
        else
          this->connection_error(connection, ec);
      });
    }
  };
} // namespace SimpleWeb

#endif /* SIMPLE_WEB_CLIENT_WSS_HPP */

max_stars_repo_name: robotil/rosbridgecpp

max_issues_repo_name: robotil/rosbridgecpp

max_forks_repo_name: robotil/rosbridgecpp


text:
#define BOOST_TEST_MODULE TestGeom
#include <boost/test/included/unit_test.hpp>
#include "db.h"
#include "helper.cpp"
#include <iostream>
using namespace odb;

BOOST_AUTO_TEST_SUITE( test_suite )

BOOST_AUTO_TEST_CASE( test_oct )
{
    Oct* oct = new Oct;
    oct->init(Point(0,0),Point(400,400),40);
    BOOST_TEST((oct->getCenterHigh() == Point(400,400)));
    BOOST_TEST((oct->getCenterLow() == Point(0,0)));
    BOOST_TEST(oct->getWidth()==40);
    BOOST_TEST(oct->xMin()==-20);
    BOOST_TEST(oct->xMax()==420);
    BOOST_TEST(oct->yMin()==-20);
    BOOST_TEST(oct->yMax()==420);
    BOOST_TEST(oct->dx()==440);
    BOOST_TEST(oct->dy()==440);

    BOOST_TEST(oct->getDir() == Oct::OCT_DIR::RIGHT);
    oct->init(Point(0,0),Point(-400,400),40);
    BOOST_TEST(oct->getDir() == Oct::OCT_DIR::LEFT);
    oct->init(Point(0,0),Point(-400,-400),40);
    BOOST_TEST(oct->getDir() == Oct::OCT_DIR::RIGHT);
    oct->init(Point(0,0),Point(400,-400),40);
    BOOST_TEST(oct->getDir() == Oct::OCT_DIR::LEFT);
}
BOOST_AUTO_TEST_CASE( test_geom_shape )
{
    Oct oct(Point(0,0),Point(400,400),40);
    GeomShape* shape = &oct;
    BOOST_TEST(shape->xMin()==-20);
    BOOST_TEST(shape->xMax()==420);
    BOOST_TEST(shape->yMin()==-20);
    BOOST_TEST(shape->yMax()==420);
    BOOST_TEST(shape->dx()==440);
    BOOST_TEST(shape->dy()==440);
    //OCT POINTS
    std::vector<Point> points = shape->getPoints();
    BOOST_TEST(points.size()==9);
    BOOST_TEST((points[0] == Point(-9,-20)));
    BOOST_TEST((points[1] == Point(9,-20)));
    BOOST_TEST((points[2] == Point(420,391)));
    BOOST_TEST((points[3] == Point(420,409)));
    BOOST_TEST((points[4] == Point(409,420)));
    BOOST_TEST((points[5] == Point(391,420)));
    BOOST_TEST((points[6] == Point(-20,9)));
    BOOST_TEST((points[7] == Point(-20,-9)));
    BOOST_TEST((points[8] == Point(-9,-20)));

    //RECT
    Rect rect(Point(0,0),Point(400,400));
    shape = ▭
    BOOST_TEST(shape->xMin()==0);
    BOOST_TEST(shape->xMax()==400);
    BOOST_TEST(shape->yMin()==0);
    BOOST_TEST(shape->yMax()==400);
    BOOST_TEST(shape->dx()==400);
    BOOST_TEST(shape->dy()==400);
    //RECT POINTS
    points = shape->getPoints();
    BOOST_TEST(points.size()==5);
    BOOST_TEST((points[0] == Point(0,0)));
    BOOST_TEST((points[1] == Point(400,0)));
    BOOST_TEST((points[2] == Point(400,400)));
    BOOST_TEST((points[3] == Point(0,400)));
    BOOST_TEST((points[4] == Point(0,0)));

}
BOOST_AUTO_TEST_CASE( test_rect_merge )
{
    Rect rect(Point(0,0),Point(100,50));
    Oct oct(Point(100,50),Point(200,200),80);
    rect.merge((GeomShape*)&oct);
    BOOST_TEST(rect.xMin()==0);
    BOOST_TEST(rect.xMax()==240);
    BOOST_TEST(rect.yMin()==0);
    BOOST_TEST(rect.yMax()==240);
    BOOST_TEST(rect.dx()==240);
    BOOST_TEST(rect.dy()==240);
}
BOOST_AUTO_TEST_SUITE_END()

ext: cpp

max_stars_repo_name: erictaur/OpenROAD

max_issues_repo_name: erictaur/OpenROAD

max_forks_repo_name: erictaur/OpenROAD


text:
/*
Copyright 2019 Glen Joseph Fernandes
(glenjofe@gmail.com)

Distributed under the Boost Software License, Version 1.0.
(http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_CORE_ALLOC_CONSTRUCT_HPP
#define BOOST_CORE_ALLOC_CONSTRUCT_HPP

#include <boost/core/noinit_adaptor.hpp>

namespace lslboost {

template<class A, class T>
inline void
alloc_destroy(A& a, T* p)
{
    lslboost::allocator_destroy(a, p);
}

template<class A, class T>
inline void
alloc_destroy_n(A& a, T* p, std::size_t n)
{
    while (n > 0) {
        lslboost::allocator_destroy(a, p + --n);
    }
}

template<class A, class T>
inline void
alloc_destroy(noinit_adaptor<A>&, T* p)
{
    p->~T();
}

template<class A, class T>
inline void
alloc_destroy_n(noinit_adaptor<A>&, T* p, std::size_t n)
{
    while (n > 0) {
        p[--n].~T();
    }
}

namespace detail {

template<class A, class T>
class alloc_destroyer {
public:
    alloc_destroyer(A& a, T* p) BOOST_NOEXCEPT
        : a_(a),
          p_(p),
          n_(0) { }

    ~alloc_destroyer() {
        lslboost::alloc_destroy_n(a_, p_, n_);
    }

    std::size_t& size() BOOST_NOEXCEPT {
        return n_;
    }

private:
    alloc_destroyer(const alloc_destroyer&);
    alloc_destroyer& operator=(const alloc_destroyer&);

    A& a_;
    T* p_;
    std::size_t n_;
};

} /* detail */

template<class A, class T>
inline void
alloc_construct(A& a, T* p)
{
    lslboost::allocator_construct(a, p);
}

#if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES)
#if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES)
template<class A, class T, class U, class... V>
inline void
alloc_construct(A& a, T* p, U&& u, V&&... v)
{
    lslboost::allocator_construct(a, p, std::forward<U>(u),
        std::forward<V>(v)...);
}
#else
template<class A, class T, class U>
inline void
alloc_construct(A& a, T* p, U&& u)
{
    lslboost::allocator_construct(a, p, std::forward<U>(u));
}
#endif
#else
template<class A, class T, class U>
inline void
alloc_construct(A& a, T* p, const U& u)
{
    lslboost::allocator_construct(a, p, u);
}

template<class A, class T, class U>
inline void
alloc_construct(A& a, T* p, U& u)
{
    lslboost::allocator_construct(a, p, u);
}
#endif

template<class A, class T>
inline void
alloc_construct_n(A& a, T* p, std::size_t n)
{
    detail::alloc_destroyer<A, T> hold(a, p);
    for (std::size_t& i = hold.size(); i < n; ++i) {
        lslboost::allocator_construct(a, p + i);
    }
    hold.size() = 0;
}

template<class A, class T>
inline void
alloc_construct_n(A& a, T* p, std::size_t n, const T* l, std::size_t m)
{
    detail::alloc_destroyer<A, T> hold(a, p);
    for (std::size_t& i = hold.size(); i < n; ++i) {
        lslboost::allocator_construct(a, p + i, l[i % m]);
    }
    hold.size() = 0;
}

template<class A, class T, class I>
inline void
alloc_construct_n(A& a, T* p, std::size_t n, I b)
{
    detail::alloc_destroyer<A, T> hold(a, p);
    for (std::size_t& i = hold.size(); i < n; void(++i), void(++b)) {
        lslboost::allocator_construct(a, p + i, *b);
    }
    hold.size() = 0;
}

template<class A, class T>
inline void
alloc_construct(noinit_adaptor<A>&, T* p)
{
    ::new(static_cast<void*>(p)) T;
}

template<class A, class T>
inline void
alloc_construct_n(noinit_adaptor<A>& a, T* p, std::size_t n)
{
    detail::alloc_destroyer<noinit_adaptor<A>, T> hold(a, p);
    for (std::size_t& i = hold.size(); i < n; ++i) {
        ::new(static_cast<void*>(p + i)) T;
    }
    hold.size() = 0;
}

} /* boost */

#endif

max_stars_repo_name: mvidaldp/liblsl-android-builder

max_issues_repo_name: mvidaldp/liblsl-android-builder

max_forks_repo_name: mvidaldp/liblsl-android-builder


text:
#include <boost/array.hpp>
#include <boost/asio.hpp>
#include <iostream>

using boost::asio::ip::udp;

int main(int argc, char *argv[]) {
  try {
    if (argc != 2) {
      std::cerr << "Usage: client <host>" << std::endl;
      return 1;
    }

    boost::asio::io_context io_context;

    udp::resolver resolver(io_context);
    udp::endpoint receiver_endpoint =
        *resolver.resolve(udp::v4(), argv[1], "daytime").begin();

    udp::socket socket(io_context);
    socket.open(udp::v4());

    boost::array<char, 1> send_buf = {{0}};
    socket.send_to(boost::asio::buffer(send_buf), receiver_endpoint);

    boost::array<char, 128> recv_buf;
    udp::endpoint sender_endpoint;
    size_t len =
        socket.receive_from(boost::asio::buffer(recv_buf), sender_endpoint);

    std::cout.write(recv_buf.data(), len);
  } catch (std::exception &e) {
    std::cerr << e.what() << std::endl;
  }

  return 0;
}

max_stars_repo_name: adlternative/boost-learn

max_issues_repo_name: adlternative/boost-learn

max_forks_repo_name: adlternative/boost-learn


text:
// FILE: src/packetgenie.cpp  Date Modified: March 17, 2015
// PacketGenie
// Copyright 2014 The Regents of the University of Michigan
// Dong-Hyeon Park, Ritesh Parikh, Valeria Bertacco
//
// PacketGenie is licensed under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//     http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.

#ifndef _TEST_CPP_
#define _TEST_CPP_

#include <boost/program_options.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/regex.hpp>
#include <string>
#include <iostream>
#include <sstream>
#include <map>
#include <vector>
#include <fstream>

#include "misc.cpp"
#include "node.hpp"
#include "network.hpp"
#include "globals.hpp"

// Parse a single line of string. Separates the string by any character in tokens.
static int extract_param(string const& line, string & key, vector<string> &params, string tokens)
{
    unsigned int pos = line.find_first_of(tokens);
    unsigned int initialPos = 0;
    unsigned int n = line.size();
    vector<string> strout;

    // Split line by any of the characters specified in tokens
    while( pos < n)
    {
        strout.push_back(line.substr(initialPos, pos - initialPos));
        initialPos = pos + 1;

        pos = line.find_first_of(tokens, initialPos);
    }

    strout.push_back(line.substr(initialPos, min( pos, n ) - initialPos));
    key = strout.front();
    strout.erase(strout.begin());
    params = strout;

    return strout.size();
}

// Parse through the config file to extract the variables and give it to param_list as a map.
static int process_config_file(string const& config_file_path,
                               multimap<string,vector<string> > &param_map)
{
    int num;
    string line, key;
    vector<string> str_param;

    ifstream config_text (config_file_path.c_str());
    while(getline(config_text, line))
    {
        if(line[0] == '-')
        {
            num = extract_param(line, key, str_param, " " );
            // Add to the parameter list, indexed by variable name in key.
            if (num > 0)
                 param_map.insert(pair< string, vector<string> >(key, str_param));
            str_param.clear();
        }

    }

    return SUCCESS;
}

int main(int argc, char** argv)
{
  try
  {

    string config_file_path;
    string outfile_path;
    unsigned int randseed = 0;

    // Parsing command line options
    // Get the path for configuration file and the path for the output.
    namespace po = boost::program_options;
    po::options_description desc("Basic Traffic Generator for NoCs.\n");

    // Adding options for the parser.
    desc.add_options()
      ("help,h", "Print help message")
      ("print,p", "Print results")
      ("runtime,r", "Print-as-you-go")
      ("noout,n", "No output file")
      ("seed,s", po::value<unsigned int>(&randseed), "Random seed")
      ("config_file", po::value<string>(&config_file_path),
       "Configuration file for the traffic generator")
      ("outfile", po::value<string>(&outfile_path),
       "Specify the location for the traffic output");

    // Specify positional options.
    po::positional_options_description positionalOptions;
    positionalOptions.add("config_file", 1);
    positionalOptions.add("outfile", 1);

    po::variables_map vm;

    try
    {
      // When help option is enabled
      po::store(po::command_line_parser(argc, argv).options(desc)
                  .positional(positionalOptions).run(),
                vm);

      if (vm.count("help"))
      {
        cout << "Basic Traffic Generator for simulating NoCs" << endl
             << desc << endl << endl;
        return SUCCESS;
      }

      if (!vm.count("config_file"))
      {
        cout << "ERROR: Need to specify a config file" << endl
             << desc << endl << endl;
        return SUCCESS;
      }

      if (!vm.count("outfile") && !vm.count("noout"))
      {
        cout << "ERROR: Need to specify a output file" << endl
             << desc << endl << endl;
        return SUCCESS;
      }

      po::notify(vm); // Throws an error.

    }
/*
    catch(boost::program_options::required_option& e)
    {
      cerr << "ERROR: " << e.what() << endl << endl;
      cerr << desc << endl;
      return ERROR_IN_CMDLN;
    }
*/
    catch(po::error& e)
    {
      cerr << "ERROR: " << e.what() << endl << endl;
      cerr << desc << endl;
      return ERROR_IN_CMDLN;
    }

    if (randseed)
        srand(randseed);
    else
        srand(time(NULL));

    if (vm.count("print"))
        gPrint = true;
    else
        gPrint = false;

    if (vm.count("runtime"))
        gRuntime = true;
    else
        gRuntime = false;

    if (vm.count("noout"))
	gNoOut = true;
    else
	gNoOut = false;

    multimap<string,vector<string> > param_map;

#if _Debug
        cout << "Parsing success!" << endl;
        cout << "config_file: " << config_file_path << endl;
     if (!gNoOut)
        cout << "Outfile to: " << outfile_path << endl;
#endif

    // Process the config file and store the variables to param_list
    // param_list is a map, indexed by the variable name and contains list of values in string.
    process_config_file(config_file_path, param_map);

#if _DEBUG
    // Print the map.
    for (multimap< string,vector<string> >::iterator it=param_map.begin();
         it != param_map.end(); ++it)
          cout << it->first << " => " << it->second << endl;
    cout << "MAP SIZE: " << param_map.size() << endl;
#endif

    try
    {
          int error;
          string top_type, traffic_pattern;
          unsigned int top_dim_x, top_dim_y;
          unsigned int simclk_end;

          // Parse basic network and simulation parameters.
          top_type = get_strvec(param_map, "-topology_type")[0];
          top_dim_x = boost::lexical_cast<unsigned int>
                                  (get_strvec(param_map, "-topology_type")[1]);
          top_dim_y = boost::lexical_cast<unsigned int>
                                  (get_strvec(param_map, "-topology_type")[2]);

          simclk_end = boost::lexical_cast<unsigned int>
                                  (get_strvec(param_map, "-simclk_end")[0]);

          if (gPrint)
          {
             cout << "Setting up Network" << endl;

          }

          // Initialize network. ( Declared as X by Y mesh network. )
          Network my_network = Network(NETWORK_MESH, top_dim_x, top_dim_y);

          pair< multimap< string,vector<string> >::iterator,
                    multimap< string, vector<string> >::iterator> it_range;
          multimap< string, vector<string> >::iterator it_param;

          // Simulation don't finish until all outstanding request-reply packets
          // have been processed.
          it_param = param_map.find("-wait_for_replies");
          if (it_param != param_map.end())
          {
              gWaitForReply = true;
          }

          if (gPrint)
          {
              cout << "=== Setting up Injection Process ===" << endl;
          }

          // Set injection processes
          it_range = param_map.equal_range("-traffic_inj_process");
          for ( it_param = it_range.first;
                it_param != it_range.second; ++it_param)
          {
              error = my_network.set_inj_process(&(it_param->second));
              if (error)
              {
                  cerr << "ERROR " << error
                       << ": ERROR SETTING INJECTION PROCESS" << endl;
                  return error;
              }
          }

          if (gPrint)
          {
              cout << endl
                   << "=== Setting up Traffic Pattern ===" << endl;
          }

          // Set injection processes
          it_range = param_map.equal_range("-traffic_pattern");
          for ( it_param = it_range.first;
                it_param != it_range.second; ++it_param)
          {
              error = my_network.set_traffic_pattern(&(it_param->second));
              if (error)
              {
                  cerr << "ERROR " << error
                       << ": ERROR SETTING TRAFFIC PATTERN" << endl;
                  return error;
              }
          }
          if (gPrint)
          {
              cout << endl
                   << "=== Setting up Senders ===" << endl;
          }

          // Set receivers
          it_range = param_map.equal_range("-traffic_senders");
          for ( it_param = it_range.first;
                it_param != it_range.second; ++it_param)
          {
              error = my_network.set_sender_nodes(&(it_param->second));
              if (error)
              {
                  cerr << "ERROR " << error
                       << ": ERROR SETTING SENDERS" << endl;
                  return error;
              }
          }

          if (gPrint)
          {
              cout << endl
                   << "=== Setting up Receivers ===" << endl;
          }

          // Set receivers
          it_range = param_map.equal_range("-traffic_receivers");
          for ( it_param = it_range.first;
                it_param != it_range.second; ++it_param)
          {
              error = my_network.set_receiver_nodes(&(it_param->second));
              if (error)
              {
                  cerr << "ERROR " << error
                       << ": ERROR SETTING RECEIVERS" << endl;
                  return error;
              }
          }

          if (gPrint)
          {
              cout << endl
                   << "=== Setting up Reply Packets ===" << endl;
          }

          // Set injection processes
          it_range = param_map.equal_range("-packet_type_reply");
          for ( it_param = it_range.first;
                it_param != it_range.second; ++it_param)
          {
              error = my_network.set_packet_type_reply(&(it_param->second));
              if (error)
              {
                  cerr << "ERROR " << error
                       << ": ERROR SETTING REPLY PACKETS" << endl;
                  return error;
              }
          }

          if (gPrint)
          {
              cout << endl
                   << "=== Setting up Packets ===" << endl;
          }

          // Set injection processes
          it_range = param_map.equal_range("-packet_type");
          for ( it_param = it_range.first;
                it_param != it_range.second; ++it_param)
          {
              error = my_network.set_packet_type(&(it_param->second));
              if (error)
              {
                  cerr << "ERROR " << error
                       << ": ERROR SETTING PACKETS" << endl;
                  return error;
              }
          }

          if (gPrint)
          {
              cout << endl
                   << "=== Setting up Dram Bank ===" << endl;
          }

          // Set injection processes
          it_range = param_map.equal_range("-dram_bank_config");
          for ( it_param = it_range.first;
                it_param != it_range.second; ++it_param)
          {
              error = my_network.set_dram_bank_config(&(it_param->second));
              if (error)
              {
                  cerr << "ERROR " << error
                       << ": ERROR SETTING DRAM BANK" << endl;
                  return error;
              }
          }

          if (gPrint)
          {
              cout << endl
                   << "=== Setting up Dram Timing ===" << endl;
          }

          // Set injection processes
          it_range = param_map.equal_range("-dram_timing_config");
          for ( it_param = it_range.first;
                it_param != it_range.second; ++it_param)
          {
              error = my_network.set_dram_timing_config(&(it_param->second));
              if (error)
              {
                  cerr << "ERROR " << error
                       << ": ERROR SETTING DRAM TIMING" << endl;
                  return error;
              }
          }

          if (gPrint)
          {
              cout << endl
                   << "=== Setting up Node Groups ===" << endl;
          }

          // Set node groups
          it_range = param_map.equal_range("-node_group");
          for ( it_param = it_range.first;
                it_param != it_range.second; ++it_param)
          {
              error = my_network.set_node_group(&(it_param->second));
              if (error & (error != ERROR_IGNORE))
              {
                  cerr << "ERROR: ERROR SETTING GROUPS" << endl;
                  return error;
              }
          }

          if (gPrint)
          {
              cout << endl
                   << "=== Configuring Nodes ===" << endl;
          }

          // Configure nodes
          it_range = param_map.equal_range("-node_config");
          for ( it_param = it_range.first;
                it_param != it_range.second; ++it_param)
          {
              error = my_network.config_nodes(&(it_param->second));
              if (error)
              {
                  cerr << "ERROR: ERROR CONFIGURING NODES" << endl;
                  return error;
              }
          }

#if _BOOKSIM
          string booksim_config_file;

          it_param = param_map.find("-booksim_enable");
          if (it_param != param_map.end())
          {
              cout << "Initializing Booksim" << endl;
              booksim_config_file = get_strvec(param_map, "-booksim_config_file")[0];
              error = my_network.config_BookSim(booksim_config_file.c_str());
              if (error)
              {
                  cerr << "ERROR: ERROR CONFIGURING BOOKSIM INTERCONNECT" << endl;
                  return error;
              }
          }
#endif

          // Initialize simuation
          my_network.init_sim(simclk_end);

          if (gPrint)
          {
              cout << ">>> Simulation Starts >>>" << endl;
          }

          /////////////////////////////////////
          // Step through until we are done! //
          // //////////////////////////////////
          do
          {
              error = my_network.step();
          }
          while((my_network.get_status() != NETWORK_STATUS_DONE) || error);

          if (error)
              cerr << "ERROR: ERROR OCCURED WHILE STEPPING THROUGH" << endl
                   << "=== traffic generaton aborted === " << endl;

          /////////////////////////////////////
          //       Print Final Outputs       //
          /////////////////////////////////////
          if (gPrint)
          {
              cout << "<<< Simulation Complete <<< " << endl << endl;
          }

          if (gPrint)
              my_network.print_traffic_records();

          // Write result to file
     if (!gNoOut) {
          string output;
          my_network.get_traffic_records(output);
          write_output(outfile_path, output);
     }

        // Run traffic generator
        //    (1) Go through each node and test for traffic
        //          - if the node will generate traffic, determine the destination and record.
        //    (2) Increment clock
        //    (3) Repeat 1-2 until clock reaches the end.
        //    (4) Write traffic log to a file, create any statistical data if necessary.

    }
    catch (const boost::bad_lexical_cast &)
    {
        cerr << "ERROR: BAD CASTING" << endl;
    }

    // In case of exceptions
  }
  catch(exception& e)
  {
    cerr << "Unhandled Exception reached the top of main: "
         << e.what() << ", application will now exit" << endl;
    return ERROR;
  }

  return SUCCESS;
}

#endif

max_stars_repo_name: packetgenie/PacketGenie

max_issues_repo_name: packetgenie/PacketGenie

max_forks_repo_name: packetgenie/PacketGenie


text:
#include "message.h"
#include "proof.h"
#include "rsa.h"
#include "proofrepository.h"
#include "logger.h"
#include <sstream>
#include <boost/archive/xml_iarchive.hpp>
#include <boost/archive/xml_oarchive.hpp>

const unsigned long KEYBITS = 4096;
const char * PREPFILE = "proofrep.xml" ;

using namespace std;

XLogDestination d2("test.log");
XLogger testlog(d2);

int main()
{
   LOG( testlog, "Completed test" ) ;

   PublicKeyEncryption * apub = 0;
   PrivateKeyEncryption * apriv = 0;
   RSACore::createkeypair( apub, apriv, KEYBITS ) ;

   PublicKeyEncryption * bpub = 0;
   PrivateKeyEncryption * bpriv = 0;
   RSACore::createkeypair( bpub, bpriv, KEYBITS ) ;

   Proof p;
   p.challenger = "a" ;
   p.responder = "b" ;
   p.observer = "a" ;

   ProofRepository rep;

   UBigNum test, encrypted, recovered;
   test.random(KEYBITS-8);

   bpub->Encrypt( encrypted, test )  ;
   p.challenge.challenge = encrypted;

   bpriv->Decrypt( recovered, encrypted ) ;
   p.response.response = recovered;

   assert( recovered == test ) ;

   rep.putProof(p);
   rep.save(PREPFILE);
   rep.clear();

   cout << "restoring" << endl ;
   rep.restore(PREPFILE);

   cout << "restored" << endl ;

   LOG( testlog, "Completed test" ) ;
   return 0;
}

max_stars_repo_name: ShoufuLuo/csaw

max_issues_repo_name: ShoufuLuo/csaw

max_forks_repo_name: ShoufuLuo/csaw


text:
#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE pcv_test

#include "test_common.h"
#include <vector>
#include <random>

#include <pcv/partition_sort/b_tree_impl.h>
#include <pcv/partition_sort/partition_sort_classifier.h>
#include <pcv/rule_parser/classbench_rule_parser.h>
#include <pcv/rule_parser/trace_tools.h>
#include <boost/thread.hpp>

using namespace pcv;
using namespace pcv::rule_conv_fn;
using namespace std;

BOOST_AUTO_TEST_SUITE( pcv_testsuite )

constexpr size_t D = 7;
using BTree = BTreeImp<_BTreeCfg<uint16_t, RuleValueInt, D>>;
using Classifier = PartitionSortClassifer<BTree, 32>;

/*
 * Select random rule and remove it or add it to classifier
 * */
void updater_entrypoint(Classifier & cls, vector<BTree::rule_spec_t> & rules,
		size_t reapeat_cnt, size_t seed = 0) {
	mt19937_64 rand(seed);
	std::uniform_int_distribution<int> distr_insert(0, rules.size() - 1);
	std::uniform_int_distribution<int> distr_insert_or_rem_decision(0, 1);

	for (size_t i = 0; i < reapeat_cnt; i++) {
		if (distr_insert_or_rem_decision()) {
			int insert_i = distr_insert();
			int _insert_i = insert_i;
			// find the first rule which is not already in classifier
			auto r = &rules[_insert_i];
			while (cls.rule_to_tree.find(*r) != cls.rule_to_tree.end()) {
				_insert_i = (_insert_i + 1) % rules.size();
				if (_insert_i == insert_i) {
					r = nullptr;
					break;
				}
				r = &rules[_insert_i];
			}
			if (r)
				cls.insert(*r);
		} else if (cls.rule_to_tree.size() == 0) {
			std::uniform_int_distribution<int> distr_rem(0,
					cls.rule_to_tree.size() - 1);
			auto to_rem = cls.rule_to_tree.begin() + distr_rem();
			cls.remove(to_rem->first)
		}
	}
}

/*
 *
 **/
void searcher_entrypoint(const Classifier & cls,
		const std::vector<packet_t> & packets, size_t reapeat_cnt) {
	for (size_t i = 0; i < reapeat_cnt; i++) {
		auto & p = packets[i % packets.size()];
		cls.search(p);
	}
}

/*
 * @note that this test actually does not check correctness
 * as it has no synchronisation between the lookup threads and update threads
 * However it check if the update of did not caused fault in lookup threads
 * */
BOOST_AUTO_TEST_CASE( simple ) {
	string rule_file = "tests/data/acl1_100";

	constexpr size_t UNIQUE_TRACE_CNT = 128;
	constexpr size_t LOOKUP_THREAD_CNT = 4;
	constexpr size_t UPDATE_THREAD_CNT = 1;
	constexpr size_t LOOKUPS_PER_THR = 1000000;

	Classifier cls;

	vector<iParsedRule*> _rules;
	vector<BTree::rule_spec_t> rules;

	RuleReader rp;
	_rules = rp.parse_rules(rule_file);
	{
		// load rules in to a classifier tree
		BTree::rule_id_t i = 0;
		for (auto _r : _rules) {
			auto __r = reinterpret_cast<Rule_Ipv4_ACL*>(_r);
			BTree::rule_spec_t r = { rule_to_array_16b(*__r), {0, i} };
			rules.push_back(r);
		}
	}
	auto packets = generate_packets_from_ruleset(
			*reinterpret_cast<vector<const Rule_Ipv4_ACL*>*>(&_rules),
			UNIQUE_TRACE_CNT);

	std::array<boost::thread *, UPDATE_THREAD_CNT> update_thr;
	std::array<boost::thread *, LOOKUP_THREAD_CNT> lookup_thr;
	for (size_t i = 0; i < LOOKUP_THREAD_CNT; i++) {
		update_thr[i] = new boost::thread(updater_entrypoint, cls, rules);
	}
	for (size_t i = 0; i < LOOKUP_THREAD_CNT; i++) {
		update_thr[i] = new boost::thread(searcher_entrypoint, cls, packets,
				LOOKUPS_PER_THR);
	}
	for (auto t : update_thr)
		t->join();
	for (auto t : lookup_thr)
		t->join();
}

//____________________________________________________________________________//

BOOST_AUTO_TEST_SUITE_END()


text:
/*=============================================================================
    Boost.Wave: A Standard compliant C++ preprocessor library
    http://www.boost.org/

    Copyright (c) 2001-2012 Hartmut Kaiser. Distributed under the Boost
    Software License, Version 1.0. (See accompanying file
    LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/

#define BOOST_WAVE_SOURCE 1

// disable stupid compiler warnings
#include <boost/config/warning_disable.hpp>
#include <boost/wave/wave_config.hpp>

#if BOOST_WAVE_SEPARATE_GRAMMAR_INSTANTIATION != 0

#include <string>

#include <boost/wave/cpplexer/cpp_lex_token.hpp>
#include <boost/wave/cpplexer/cpp_lex_iterator.hpp>

#include <boost/wave/grammars/cpp_defined_grammar.hpp>

// this must occur after all of the includes and before any code appears
#ifdef BOOST_HAS_ABI_HEADERS
#include BOOST_ABI_PREFIX
#endif

///////////////////////////////////////////////////////////////////////////////
//
//  Explicit instantiation of the defined_grammar_gen template
//  with the correct token type. This instantiates the corresponding parse
//  function, which in turn instantiates the defined_grammar
//  object (see wave/grammars/cpp_defined_grammar.hpp)
//
///////////////////////////////////////////////////////////////////////////////

// if you want to use your own token type the following line must be adjusted
typedef boost::wave::cpplexer::lex_token<> token_type;

// no need to change anything below
typedef boost::wave::cpplexer::lex_iterator<token_type> lexer_type;
template struct boost::wave::grammars::defined_grammar_gen<lexer_type>;

// the suffix header occurs after all of the code
#ifdef BOOST_HAS_ABI_HEADERS
#include BOOST_ABI_SUFFIX
#endif

#endif // #if BOOST_WAVE_SEPARATE_GRAMMAR_INSTANTIATION != 0

max_stars_repo_name: randolphwong/mcsema

max_issues_repo_name: randolphwong/mcsema

max_forks_repo_name: randolphwong/mcsema