void CStormnodePayments::ProcessMessageStormnodePayments(CNode* pfrom, std::string& strCommand, CDataStream& vRecv)
{
    if(!stormnodeSync.IsBlockchainSynced()) return;

    if(fLiteMode) return; //disable all Sandstorm/Stormnode related functionality


    if (strCommand == "snget") { //Stormnode Payments Request Sync
        if(fLiteMode) return; //disable all Sandstorm/Stormnode related functionality

        int nCountNeeded;
        vRecv >> nCountNeeded;

        if(Params().NetworkID() == CChainParams::MAIN){
            if(pfrom->HasFulfilledRequest("snget")) {
                LogPrintf("snget - peer already asked me for the list\n");
                Misbehaving(pfrom->GetId(), 20);
                return;
            }
        }

        pfrom->FulfilledRequest("snget");
        stormnodePayments.Sync(pfrom, nCountNeeded);
        LogPrintf("snget - Sent Stormnode winners to %s\n", pfrom->addr.ToString().c_str());
    }
    else if (strCommand == "snw") { //Stormnode Payments Declare Winner
std::string GetRequiredPaymentsString(int nBlockHeight)
{
    if(IsSporkActive(SPORK_13_ENABLE_SUPERBLOCKS) && budget.IsBudgetPaymentBlock(nBlockHeight)){
        return budget.GetRequiredPaymentsString(nBlockHeight);
    } else {
        return stormnodePayments.GetRequiredPaymentsString(nBlockHeight);
    }
}
void FillBlockPayee(CTransaction& txNew, CAmount nFees) //TODO (Amir): Use CMutableTransaction here
{
    CBlockIndex* pindexPrev = pindexBest;
    if(!pindexPrev) return;

    if(IsSporkActive(SPORK_13_ENABLE_SUPERBLOCKS) && budget.IsBudgetPaymentBlock(pindexPrev->nHeight+1)){
        budget.FillBlockPayee(txNew, nFees);
    } else {
        stormnodePayments.FillBlockPayee(txNew, nFees);
    }
}
//TODO (Amir): Use CMutableTransaction.
void CStormnodePayments::FillBlockPayee(CTransaction& txNew, CAmount nFees)
{
    CBlockIndex* pindexPrev = pindexBest;
    if(!pindexPrev) return;

    bool hasPayment = true;
    CScript payee;

    //spork
    if(!stormnodePayments.GetBlockPayee(pindexPrev->nHeight+1, payee)){
        //no stormnode detected
        CStormnode* winningNode = snodeman.GetCurrentStormNode();
        if(winningNode){
            payee = GetScriptForDestination(winningNode->pubkey.GetID());
        } else {
            LogPrintf("CreateNewBlock: Failed to detect stormnode to pay\n");
            hasPayment = false;
        }
    }

    if(hasPayment){

        //txNew.vout.resize(2);

        txNew.vout[1].scriptPubKey = payee;
        //txNew.vout[1].nValue = stormnodePayment;

        //txNew.vout[0].nValue -= stormnodePayment;

        // Stormnode Payments
        CAmount blockValue = GetBlockValue(pindexPrev->nBits, pindexPrev->nHeight, nFees);
        CAmount stormnodePayment = GetStormnodePayment(pindexPrev->nHeight+1, blockValue);

        if(txNew.vout.size() == 4) // 2 stake outputs, stake was split, plus a stormnode payment
        {
            txNew.vout[1].nValue = stormnodePayment;
            blockValue -= stormnodePayment;
            txNew.vout[2].nValue = (blockValue / 2 / CENT) * CENT;
            txNew.vout[3].nValue = blockValue - txNew.vout[1].nValue;
        }
        else if(txNew.vout.size() == 3) // only 1 stake output, was not split, plus a stormnode payment
        {
            txNew.vout[1].nValue = stormnodePayment;
            blockValue -= stormnodePayment;
            txNew.vout[2].nValue = blockValue;
        }
        CTxDestination address1;
        ExtractDestination(payee, address1);
        CDarkSilkAddress address2(address1);

        LogPrintf("Stormnode payment to %s\n", address2.ToString().c_str());
    }
}
bool IsBlockPayeeValid(const CTransaction& txNew, int nBlockHeight)
{
    if(!stormnodeSync.IsSynced()) { //there is no budget data to use to check anything -- find the longest chain
        LogPrint("snpayments", "Client not synced, skipping block payee checks\n");
        return true;
    }

    //check if it's a budget block
    if(IsSporkActive(SPORK_13_ENABLE_SUPERBLOCKS)){
        if(budget.IsBudgetPaymentBlock(nBlockHeight)){
            if(budget.IsTransactionValid(txNew, nBlockHeight)){
                return true;
            } else {
                LogPrintf("Invalid budget payment detected %s\n", txNew.ToString().c_str());
                if(IsSporkActive(SPORK_9_STORMNODE_BUDGET_ENFORCEMENT)){
                    return false;
                } else {
                    LogPrintf("Budget enforcement is disabled, accepting block\n");
                    return true;
                }
            }
        }
    }

    //check for stormnode payee
    if(stormnodePayments.IsTransactionValid(txNew, nBlockHeight))
    {
        return true;
    } else {
        LogPrintf("Invalid sn payment detected %s\n", txNew.ToString().c_str());
        if(IsSporkActive(SPORK_8_STORMNODE_PAYMENT_ENFORCEMENT)){
            return false;
        } else {
            LogPrintf("Stormnode payment enforcement is disabled, accepting block\n");
            return true;
        }
    }

    return false;
}
CStormnodePaymentDB::ReadResult CStormnodePaymentDB::Read(CStormnodePayments& objToLoad, bool fDryRun)
{

    int64_t nStart = GetTimeMillis();
    // open input file, and associate with CAutoFile
    FILE *file = fopen(pathDB.string().c_str(), "rb");
    CAutoFile filein(file, SER_DISK, CLIENT_VERSION);
    if (filein.IsNull())
    {
        error("%s : Failed to open file %s", __func__, pathDB.string());
        return FileError;
    }

    // use file size to size memory buffer
    int fileSize = boost::filesystem::file_size(pathDB);
    int dataSize = fileSize - sizeof(uint256);
    // Don't try to resize to a negative number if file is small
    if (dataSize < 0)
        dataSize = 0;
    vector<unsigned char> vchData;
    vchData.resize(dataSize);
    uint256 hashIn;

    // read data and checksum from file
    try {
        filein.read((char *)&vchData[0], dataSize);
        filein >> hashIn;
    }
    catch (std::exception &e) {
        error("%s : Deserialize or I/O error - %s", __func__, e.what());
        return HashReadError;
    }
    filein.fclose();

    CDataStream ssObj(vchData, SER_DISK, CLIENT_VERSION);

    // verify stored checksum matches input data
    uint256 hashTmp = Hash(ssObj.begin(), ssObj.end());
    if (hashIn != hashTmp)
    {
        error("%s : Checksum mismatch, data corrupted", __func__);
        return IncorrectHash;
    }


    unsigned char pchMsgTmp[4];
    std::string strMagicMessageTmp;
    try {
        // de-serialize file header (stormnode cache file specific magic message) and ..
        ssObj >> strMagicMessageTmp;

        // ... verify the message matches predefined one
        if (strMagicMessage != strMagicMessageTmp)
        {
            error("%s : Invalid stormnode payement cache magic message", __func__);
            return IncorrectMagicMessage;
        }


        // de-serialize file header (network specific magic number) and ..
        ssObj >> FLATDATA(pchMsgTmp);

        // ... verify the network matches ours
        if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp)))
        {
            error("%s : Invalid network magic number", __func__);
            return IncorrectMagicNumber;
        }

        // de-serialize data into CStormnodePayments object
        ssObj >> objToLoad;
    }
    catch (std::exception &e) {
        objToLoad.Clear();
        error("%s : Deserialize or I/O error - %s", __func__, e.what());
        return IncorrectFormat;
    }

    LogPrintf("Loaded info from snpayments.dat  %dms\n", GetTimeMillis() - nStart);
    LogPrintf("  %s\n", objToLoad.ToString());
    if(!fDryRun) {
        LogPrintf("Stormnode payments manager - cleaning....\n");
        objToLoad.CleanPaymentList();
        LogPrintf("Stormnode payments manager - result:\n");
        LogPrintf("  %s\n", objToLoad.ToString());
    }

    return Ok;
}
void ProcessMessageStormnodePayments(CNode* pfrom, std::string& strCommand, CDataStream& vRecv)
{
    if(IsInitialBlockDownload()) return;
    if (strCommand == "snget") //Stormnode Payments Request Sync
    {
        if(fLiteMode) return; //disable all sandstorm/stormnode related functionality

        /*if(pfrom->HasFulfilledRequest("snget")) {
            LogPrintf("snget - peer already asked me for the list\n");
            Misbehaving(pfrom->GetId(), 20);
            return;
        }*/

        pfrom->FulfilledRequest("snget");
        stormnodePayments.Sync(pfrom);
        LogPrintf("snget - Sent stormnode winners to %s\n", pfrom->addr.ToString().c_str());
    }
    else if (strCommand == "snw") { //Stormnode Payments Declare Winner

        LOCK(cs_stormnodepayments);

        //this is required in litemode
        CStormnodePaymentWinner winner;
        vRecv >> winner;

        if(pindexBest == NULL) return;

        CTxDestination address1;
        ExtractDestination(winner.payee, address1);
        CDarkSilkAddress address2(address1);

        uint256 hash = winner.GetHash();
        if(mapSeenStormnodeVotes.count(hash)) {
            if(fDebug) LogPrintf("snw - seen vote %s Addr %s Height %d bestHeight %d\n", hash.ToString().c_str(), address2.ToString().c_str(), winner.nBlockHeight, pindexBest->nHeight);
            return;
        }

        if(winner.nBlockHeight < pindexBest->nHeight - 10 || winner.nBlockHeight > pindexBest->nHeight+20){
            LogPrintf("snw - winner out of range %s Addr %s Height %d bestHeight %d\n", winner.vin.ToString().c_str(), address2.ToString().c_str(), winner.nBlockHeight, pindexBest->nHeight);
            return;
        }

        if(winner.vin.nSequence != std::numeric_limits<unsigned int>::max()){
            LogPrintf("snw - invalid nSequence\n");
            Misbehaving(pfrom->GetId(), 100);
            return;
        }

        LogPrintf("snw - winning vote - Vin %s Addr %s Height %d bestHeight %d\n", winner.vin.ToString().c_str(), address2.ToString().c_str(), winner.nBlockHeight, pindexBest->nHeight);
 
        if(!stormnodePayments.CheckSignature(winner)){
            LogPrintf("snw - invalid signature\n");
            Misbehaving(pfrom->GetId(), 100);
            return;
        }

        mapSeenStormnodeVotes.insert(make_pair(hash, winner));

        if(stormnodePayments.AddWinningStormnode(winner)){
            stormnodePayments.Relay(winner);
        }
    }