void WalletInit::AddWalletOptions() const
{
    gArgs.AddArg("-addresstype", strprintf("What type of addresses to use (\"legacy\", \"p2sh-segwit\", or \"bech32\", default: \"%s\")", FormatOutputType(DEFAULT_ADDRESS_TYPE)), false, OptionsCategory::WALLET);
    gArgs.AddArg("-avoidpartialspends", strprintf(_("Group outputs by address, selecting all or none, instead of selecting on a per-output basis. Privacy is improved as an address is only used once (unless someone sends to it after spending from it), but may result in slightly higher fees as suboptimal coin selection may result due to the added limitation (default: %u)"), DEFAULT_AVOIDPARTIALSPENDS), false, OptionsCategory::WALLET);
    gArgs.AddArg("-changetype", "What type of change to use (\"legacy\", \"p2sh-segwit\", or \"bech32\"). Default is same as -addresstype, except when -addresstype=p2sh-segwit a native segwit output is used when sending to a native segwit address)", false, OptionsCategory::WALLET);
    gArgs.AddArg("-disablewallet", "Do not load the wallet and disable wallet RPC calls", false, OptionsCategory::WALLET);
    gArgs.AddArg("-discardfee=<amt>", strprintf("The fee rate (in %s/kB) that indicates your tolerance for discarding change by adding it to the fee (default: %s). "
                                                                "Note: An output is discarded if it is dust at this rate, but we will always discard up to the dust relay fee and a discard fee above that is limited by the fee estimate for the longest target",
                                                              CURRENCY_UNIT, FormatMoney(DEFAULT_DISCARD_FEE)), false, OptionsCategory::WALLET);
    gArgs.AddArg("-fallbackfee=<amt>", strprintf("A fee rate (in %s/kB) that will be used when fee estimation has insufficient data (default: %s)",
                                                               CURRENCY_UNIT, FormatMoney(DEFAULT_FALLBACK_FEE)), false, OptionsCategory::WALLET);
    gArgs.AddArg("-keypool=<n>", strprintf("Set key pool size to <n> (default: %u)", DEFAULT_KEYPOOL_SIZE), false, OptionsCategory::WALLET);
    gArgs.AddArg("-mintxfee=<amt>", strprintf("Fees (in %s/kB) smaller than this are considered zero fee for transaction creation (default: %s)",
                                                            CURRENCY_UNIT, FormatMoney(DEFAULT_TRANSACTION_MINFEE)), false, OptionsCategory::WALLET);
    gArgs.AddArg("-paytxfee=<amt>", strprintf("Fee (in %s/kB) to add to transactions you send (default: %s)",
                                                            CURRENCY_UNIT, FormatMoney(CFeeRate{DEFAULT_PAY_TX_FEE}.GetFeePerK())), false, OptionsCategory::WALLET);
    gArgs.AddArg("-rescan", "Rescan the block chain for missing wallet transactions on startup", false, OptionsCategory::WALLET);
    gArgs.AddArg("-salvagewallet", "Attempt to recover private keys from a corrupt wallet on startup", false, OptionsCategory::WALLET);
    gArgs.AddArg("-spendzeroconfchange", strprintf("Spend unconfirmed change when sending transactions (default: %u)", DEFAULT_SPEND_ZEROCONF_CHANGE), false, OptionsCategory::WALLET);
    gArgs.AddArg("-txconfirmtarget=<n>", strprintf("If paytxfee is not set, include enough fee so transactions begin confirmation on average within n blocks (default: %u)", DEFAULT_TX_CONFIRM_TARGET), false, OptionsCategory::WALLET);
    gArgs.AddArg("-upgradewallet", "Upgrade wallet to latest format on startup", false, OptionsCategory::WALLET);
    gArgs.AddArg("-wallet=<path>", "Specify wallet database path. Can be specified multiple times to load multiple wallets. Path is interpreted relative to <walletdir> if it is not absolute, and will be created if it does not exist (as a directory containing a wallet.dat file and log files). For backwards compatibility this will also accept names of existing data files in <walletdir>.)", false, OptionsCategory::WALLET);
    gArgs.AddArg("-walletbroadcast",  strprintf("Make the wallet broadcast transactions (default: %u)", DEFAULT_WALLETBROADCAST), false, OptionsCategory::WALLET);
    gArgs.AddArg("-walletdir=<dir>", "Specify directory to hold wallets (default: <datadir>/wallets if it exists, otherwise <datadir>)", false, OptionsCategory::WALLET);
    gArgs.AddArg("-walletnotify=<cmd>", "Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)", false, OptionsCategory::WALLET);
    gArgs.AddArg("-walletrbf", strprintf("Send transactions with full-RBF opt-in enabled (RPC only, default: %u)", DEFAULT_WALLET_RBF), false, OptionsCategory::WALLET);
    gArgs.AddArg("-zapwallettxes=<mode>", "Delete all wallet transactions and only recover those parts of the blockchain through -rescan on startup"
                               " (1 = keep tx meta data e.g. account owner and payment request information, 2 = drop tx meta data)", false, OptionsCategory::WALLET);

    gArgs.AddArg("-dblogsize=<n>", strprintf("Flush wallet database activity from memory to disk log every <n> megabytes (default: %u)", DEFAULT_WALLET_DBLOGSIZE), true, OptionsCategory::WALLET_DEBUG_TEST);
    gArgs.AddArg("-flushwallet", strprintf("Run a thread to flush wallet periodically (default: %u)", DEFAULT_FLUSHWALLET), true, OptionsCategory::WALLET_DEBUG_TEST);
    gArgs.AddArg("-privdb", strprintf("Sets the DB_PRIVATE flag in the wallet db environment (default: %u)", DEFAULT_WALLET_PRIVDB), true, OptionsCategory::WALLET_DEBUG_TEST);
    gArgs.AddArg("-walletrejectlongchains", strprintf("Wallet will not create transactions that violate mempool chain limits (default: %u)", DEFAULT_WALLET_REJECT_LONG_CHAINS), true, OptionsCategory::WALLET_DEBUG_TEST);
}
Beispiel #2
0
void ExtFrame::OnQuotes() 
{
	// TODO: Add your command handler code here
    const StockBase* stockHandle = B_GetStockHandle("INTC");
    CString str;
    if(B_IsStockValid(stockHandle))
    {
        const BookEntry* be;
        const unsigned int entries = 6;
        unsigned int count;
        char num[33];

        
        Observable* level2 = B_GetLevel2(stockHandle);
        void* m_bidIterator = B_CreateBookIterator(level2, true);

        str += "BIDS\n";
        count = 0;
        B_StartIteration(m_bidIterator);
        while((be = B_GetNextBookEntry(m_bidIterator)) && count < entries)
        {
            count++;
            str += be->GetMmid();
            str += "  ";
            FormatMoney(str, *be);
            str += "    ";
			_itoa_s(be->GetSize(), num, sizeof(num), 10);
            str += num;
            str += "\n";
        }
        B_DestroyIterator(m_bidIterator);

        str += "\nASKS\n";
        count = 0;
        void* m_askIterator = B_CreateBookIterator(level2, false);
        B_StartIteration(m_askIterator);
        while((be = B_GetNextBookEntry(m_askIterator)) && count < entries)
        {
            count++;
            str += be->GetMmid();
            str += "  ";
            FormatMoney(str, *be);
            str += "    ";
			_itoa_s(be->GetSize(), num, sizeof(num), 10);
            str += num;
            str += "\n";
        }
        B_DestroyIterator(m_askIterator);

    }
	else
    {
        str += "Stock is not loaded yet. Try again";
    }
	
    AfxGetMainWnd()->MessageBox(str, "INTC Level 2", MB_OK);
}
Beispiel #3
0
void ExtFrame::OnAgrBookQuotes() 
{
    const StockBase* stockHandle = B_GetStockHandle("INTC");
    CString str;
    if(B_IsStockValid(stockHandle))
    {
        const BookEntry* be;
        const unsigned int entries = 6;
        unsigned int count;
        char num[33];

        
        unsigned int filter = 0xFFFFFFFF & ~(1 << NYSE_BOOK);
		unsigned int mmLines = 0xFFFFFFFF;
        void* bidIterator = B_CreateMultiBookIterator(stockHandle, true, false, filter, mmLines, true, NULL);//m_aggregatedView, this);

        str += "BIDS\n";
        count = 0;
        B_StartIteration(bidIterator);
        while((be = B_GetNextBookEntry(bidIterator)) && count < entries)
        {
            count++;
            str += be->GetMmid();
            str += "  ";
            FormatMoney(str, *be);
            str += "  ";
			_itoa_s(be->GetSize(), num, sizeof(num), 10);
            str += num;
            str += "\n";
        }
        B_DestroyIterator(bidIterator);

        str += "\nASKS\n";
        count = 0;
        void* askIterator = B_CreateMultiBookIterator(stockHandle, false, false, filter, mmLines, true, NULL);//m_aggregatedView, this);
        B_StartIteration(askIterator);
        while((be = B_GetNextBookEntry(askIterator)) && count < entries)
        {
            count++;
            str += be->GetMmid();
            str += "  ";
            FormatMoney(str, *be);
            str += "  ";
			_itoa_s(be->GetSize(), num, sizeof(num), 10);
            str += num;
            str += "\n";
        }
        B_DestroyIterator(askIterator);

    }
	else
    {
        str += "Stock is not loaded yet. Try again";
    }
    AfxGetMainWnd()->MessageBox(str, "INTC Expanded Book", MB_OK);
}
Beispiel #4
0
void ExtFrame::OnOrders() 
{
	// TODO: Add your command handler code here
    Observable* account = B_GetCurrentAccount();
    if(!account)
    {
        return;
    }
    CString str;
    char num[33];
    void* iterator = B_CreateOrderIterator(OS_CANCELLED|OS_FILLED|OS_PENDINGLONG|OS_PENDINGSHORT,(1 << ST_LAST) - 1, account);
    B_StartIteration(iterator);
    const Order* order;
    while(order = B_GetNextOrder(iterator))
    {
        str += "\n";
        str += order->GetSymbol();
        str += " Id=";
		_ultoa_s(order->GetId(), num, sizeof(num), 10);
        str += num;
        str += " Side=";
        str += order->GetSide();
        str += " P&&L=";
        FormatMoney(str, order->GetPnl());
        str += " Market=";
        str += order->GetDestination();
        str += " Contra=";
        str += order->GetCounterparty();
        str += " Price=";
        FormatMoney(str, *order);
        str += " Size=";
		_ultoa_s(order->GetSize(), num, sizeof(num), 10);
        str += num;
        str += " ExecPrice=";
        FormatMoney(str, order->GetExecutedPrice());
        str += " ExecSize=";
		_ultoa_s(order->GetExecutedSize(), num, sizeof(num), 10);
        str += num;
        str += " Pending=";
		_ultoa_s(order->GetRemainingSize(), num, sizeof(num), 10);
        str += num;
        str += " Confirmed=";
        str += order->isConfirmed() ? "Yes" : "No";
        str += " BeingCanceled=";
        str += order->isBeingCanceled() ? "Yes" : "No";
        str += " MarketOrder=";
        str += order->isMarketOrder() ? "Yes" : "No";
/*
    time_t GetTimeCanceled() const{return m_timeCanceled;}
    unsigned int GetTimeInForce() const{return m_tif;}
    virtual void Cancel() = 0;
*/        
    }
    B_DestroyIterator(iterator);
    AfxGetMainWnd()->MessageBox(str, "Orders", MB_OK);
}
Beispiel #5
0
void CTxMemPool::PrioritiseTransaction(const uint256& hash, const CAmount& nFeeDelta)
{
    {
        LOCK(cs);
        CAmount &delta = mapDeltas[hash];
        delta += nFeeDelta;
        txiter it = mapTx.find(hash);
        if (it != mapTx.end()) {
            mapTx.modify(it, update_fee_delta(delta));
            // Now update all ancestors' modified fees with descendants
            setEntries setAncestors;
            uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
            std::string dummy;
            CalculateMemPoolAncestors(*it, setAncestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy, false);
            for (txiter ancestorIt : setAncestors) {
                mapTx.modify(ancestorIt, update_descendant_state(0, nFeeDelta, 0));
            }
            // Now update all descendants' modified fees with ancestors
            setEntries setDescendants;
            CalculateDescendants(it, setDescendants);
            setDescendants.erase(it);
            for (txiter descendantIt : setDescendants) {
                mapTx.modify(descendantIt, update_ancestor_state(0, nFeeDelta, 0, 0));
            }
            ++nTransactionsUpdated;
        }
    }
    LogPrintf("PrioritiseTransaction: %s feerate += %s\n", hash.ToString(), FormatMoney(nFeeDelta));
}
QVariant OptionsModel::data(const QModelIndex & index, int role) const
{
    if(role == Qt::EditRole)
    {
        switch(index.row())
        {
        case StartAtStartup:
            return QVariant();
        case MinimizeToTray:
            return QVariant(fMinimizeToTray);
        case MapPortUPnP:
            return QVariant(fUseUPnP);
        case MinimizeOnClose:
            return QVariant(fMinimizeOnClose);
        case ConnectSOCKS4:
            return QVariant(fUseProxy);
        case ProxyIP:
            return QVariant(QString::fromStdString(addrProxy.ToStringIP()));
        case ProxyPort:
            return QVariant(QString::fromStdString(addrProxy.ToStringPort()));
        case Fee:
            return QVariant(QString::fromStdString(FormatMoney(nTransactionFee)));
        default:
            return QVariant();
        }
    }
    return QVariant();
}
Beispiel #7
0
void ExtFrame::FormatMoneySize(CString& dest, const MoneySize& money)
{
    FormatMoney(dest, money);
    char num[33];
    dest += "  ";
	_itoa_s(money.GetSize(), num, sizeof(num), 10);
    dest += num;
}
void TxToUniv(const CTransaction &tx, const uint256 &hashBlock,
              UniValue &entry) {
    entry.pushKV("txid", tx.GetId().GetHex());
    entry.pushKV("hash", tx.GetHash().GetHex());
    entry.pushKV("version", tx.nVersion);
    entry.pushKV("locktime", (int64_t)tx.nLockTime);

    UniValue vin(UniValue::VARR);
    for (unsigned int i = 0; i < tx.vin.size(); i++) {
        const CTxIn &txin = tx.vin[i];
        UniValue in(UniValue::VOBJ);
        if (tx.IsCoinBase()) {
            in.pushKV("coinbase",
                      HexStr(txin.scriptSig.begin(), txin.scriptSig.end()));
        } else {
            in.pushKV("txid", txin.prevout.hash.GetHex());
            in.pushKV("vout", (int64_t)txin.prevout.n);
            UniValue o(UniValue::VOBJ);
            o.pushKV("asm", ScriptToAsmStr(txin.scriptSig, true));
            o.pushKV("hex",
                     HexStr(txin.scriptSig.begin(), txin.scriptSig.end()));
            in.pushKV("scriptSig", o);
        }

        in.pushKV("sequence", (int64_t)txin.nSequence);
        vin.push_back(in);
    }

    entry.pushKV("vin", vin);

    UniValue vout(UniValue::VARR);
    for (unsigned int i = 0; i < tx.vout.size(); i++) {
        const CTxOut &txout = tx.vout[i];

        UniValue out(UniValue::VOBJ);

        UniValue outValue(UniValue::VNUM,
                          FormatMoney(txout.nValue.GetSatoshis()));
        out.pushKV("value", outValue);
        out.pushKV("n", (int64_t)i);

        UniValue o(UniValue::VOBJ);
        ScriptPubKeyToUniv(txout.scriptPubKey, o, true);
        out.pushKV("scriptPubKey", o);
        vout.push_back(out);
    }

    entry.pushKV("vout", vout);

    if (!hashBlock.IsNull()) {
        entry.pushKV("blockhash", hashBlock.GetHex());
    }

    // the hex-encoded transaction. used the name "hex" to be consistent with
    // the verbose output of "getrawtransaction".
    entry.pushKV("hex", EncodeHexTx(tx));
}
Beispiel #9
0
void TxToUniv(const CTransaction& tx, const uint256& hashBlock, UniValue& entry)
{
    entry.pushKV("txid", tx.GetHash().GetHex());
    entry.pushKV("hash", tx.GetWitnessHash().GetHex());
    entry.pushKV("version", tx.nVersion);
    entry.pushKV("size", (int)::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION));
    entry.pushKV("vsize", (GetTransactionWeight(tx) + WITNESS_SCALE_FACTOR - 1) / WITNESS_SCALE_FACTOR);
    entry.pushKV("locktime", (int64_t)tx.nLockTime);

    UniValue vin(UniValue::VARR);
    for (unsigned int i = 0; i < tx.vin.size(); i++) {
        const CTxIn& txin = tx.vin[i];
        UniValue in(UniValue::VOBJ);
        if (tx.IsCoinBase())
            in.pushKV("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end()));
        else {
            in.pushKV("txid", txin.prevout.hash.GetHex());
            in.pushKV("vout", (int64_t)txin.prevout.n);
            UniValue o(UniValue::VOBJ);
            o.pushKV("asm", ScriptToAsmStr(txin.scriptSig, true));
            o.pushKV("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end()));
            in.pushKV("scriptSig", o);
            if (!tx.vin[i].scriptWitness.IsNull()) {
                UniValue txinwitness(UniValue::VARR);
                for (const auto& item : tx.vin[i].scriptWitness.stack) {
                    txinwitness.push_back(HexStr(item.begin(), item.end()));
                }
                in.pushKV("txinwitness", txinwitness);
            }
        }
        in.pushKV("sequence", (int64_t)txin.nSequence);
        vin.push_back(in);
    }
    entry.pushKV("vin", vin);

    UniValue vout(UniValue::VARR);
    for (unsigned int i = 0; i < tx.vout.size(); i++) {
        const CTxOut& txout = tx.vout[i];

        UniValue out(UniValue::VOBJ);

        UniValue outValue(UniValue::VNUM, FormatMoney(txout.nValue));
        out.pushKV("value", outValue);
        out.pushKV("n", (int64_t)i);

        UniValue o(UniValue::VOBJ);
        ScriptPubKeyToUniv(txout.scriptPubKey, o, true);
        out.pushKV("scriptPubKey", o);
        vout.push_back(out);
    }
    entry.pushKV("vout", vout);

    if (!hashBlock.IsNull())
        entry.pushKV("blockhash", hashBlock.GetHex());

    entry.pushKV("hex", EncodeHexTx(tx)); // the hex-encoded transaction. used the name "hex" to be consistent with the verbose output of "getrawtransaction".
}
    QVariant data(const QModelIndex &index, int role) const
    {
        if (!index.isValid())
            return QVariant();

        if (role == Qt::DisplayRole || role == Qt::EditRole)
        {
            int i = alive[index.row()];
            QueuedPlayerMoves::const_iterator mi;
            std::map<int, Game::CharacterState>::const_iterator mi2;
            switch (index.column())
            {
                case Name:
                {
                    // TODO: for sorting return the index as number
                    Game::CharacterID chid(player, i);
                    QString ret = QString::fromStdString(chid.ToString());
                    if (role == Qt::DisplayRole)
                    {
                        if (i == 0)
                            ret = QString::fromUtf8("\u2605") + ret;
                        if (crownHolder == chid)
                            ret += QString::fromUtf8(" \u265B");
                    }
                    return ret;
                }
                case Coins:
                    mi2 = state.characters.find(i);
                    if (mi2 != state.characters.end())
                        return QString::fromStdString(FormatMoney(mi2->second.loot.nAmount));    // TODO: for sorting return as float value
                    return QVariant();
                case Status:
                    if (pending)
                        return tr("Pending");
                    mi = queuedMoves.find(i);
                    if (mi != queuedMoves.end())
                    {
                        if (mi->second.destruct)
                            return tr("Destruct");
                        else
                            return tr("Queued");
                    }
                    else
                    {
                        mi2 = state.characters.find(i);
                        if (mi2 != state.characters.end() && mi2->second.waypoints.empty())
                            return tr("Ready");
                        else
                            return tr("Moving");
                    }
            }
        }
        else if (role == Qt::TextAlignmentRole)
            return QVariant(int(Qt::AlignLeft|Qt::AlignVCenter));

        return QVariant();
    }
Beispiel #11
0
bool Consensus::CheckTxInputs(const CTransaction& tx, CValidationState& state, const CCoinsViewCache& inputs, int nSpendHeight, CAmount& txfee)
{
    // are the actual inputs available?
    if (!inputs.HaveInputs(tx)) {
        return state.DoS(100, false, REJECT_INVALID, "bad-txns-inputs-missingorspent", false,
                         strprintf("%s: inputs missing/spent", __func__));
    }

    CAmount nValueIn = 0;
    for (unsigned int i = 0; i < tx.vin.size(); ++i) {
        const COutPoint &prevout = tx.vin[i].prevout;
        const Coin& coin = inputs.AccessCoin(prevout);
        assert(!coin.IsSpent());

        // If prev is coinbase, check that it's matured
        if (coin.IsCoinBase() && nSpendHeight - coin.nHeight < COINBASE_MATURITY) {
            return state.Invalid(false,
                REJECT_INVALID, "bad-txns-premature-spend-of-coinbase",
                strprintf("tried to spend coinbase at depth %d", nSpendHeight - coin.nHeight));
        }

        // Check for negative or overflow input values
        nValueIn += coin.out.nValue;
        if (!MoneyRange(coin.out.nValue) || !MoneyRange(nValueIn)) {
            return state.DoS(100, false, REJECT_INVALID, "bad-txns-inputvalues-outofrange");
        }
    }

    const CAmount value_out = tx.GetValueOut();
    if (nValueIn < value_out) {
        return state.DoS(100, false, REJECT_INVALID, "bad-txns-in-belowout", false,
            strprintf("value in (%s) < value out (%s)", FormatMoney(nValueIn), FormatMoney(value_out)));
    }

    // Tally transaction fees
    const CAmount txfee_aux = nValueIn - value_out;
    if (!MoneyRange(txfee_aux)) {
        return state.DoS(100, false, REJECT_INVALID, "bad-txns-fee-outofrange");
    }

    txfee = txfee_aux;
    return true;
}
void CMasternodePayments::FillBlockPayee(CMutableTransaction& txNew, int64_t nFees, bool fProofOfStake, bool fZXAPStake)
{
    CBlockIndex* pindexPrev = chainActive.Tip();
    if (!pindexPrev) return;

    bool hasPayment = true;
    CScript payee;

    //spork
    if (!masternodePayments.GetBlockPayee(pindexPrev->nHeight + 1, payee)) {
        //no masternode detected
        CMasternode* winningNode = mnodeman.GetCurrentMasterNode(1);
        if (winningNode) {
            payee = GetScriptForDestination(winningNode->pubKeyCollateralAddress.GetID());
        } else {
            LogPrint("masternode","CreateNewBlock: Failed to detect masternode to pay\n");
            hasPayment = false;
        }
    }

    CAmount blockValue = GetBlockValue(pindexPrev->nHeight);
    CAmount masternodePayment = GetMasternodePayment(pindexPrev->nHeight, blockValue, 0, fZXAPStake);

    if (hasPayment) {
        if (fProofOfStake) {
            /**For Proof Of Stake vout[0] must be null
             * Stake reward can be split into many different outputs, so we must
             * use vout.size() to align with several different cases.
             * An additional output is appended as the masternode payment
             */
            unsigned int i = txNew.vout.size();
            txNew.vout.resize(i + 1);
            txNew.vout[i].scriptPubKey = payee;
            txNew.vout[i].nValue = masternodePayment;

            //subtract mn payment from the stake reward
            if (!txNew.vout[1].IsZerocoinMint())
                txNew.vout[i - 1].nValue -= masternodePayment;
        } else {
            txNew.vout.resize(2);
            txNew.vout[1].scriptPubKey = payee;
            txNew.vout[1].nValue = masternodePayment;
            txNew.vout[0].nValue = blockValue - masternodePayment;
        }

        CTxDestination address1;
        ExtractDestination(payee, address1);
        CBitcoinAddress address2(address1);

        LogPrint("masternode","Masternode payment of %s to %s\n", FormatMoney(masternodePayment).c_str(), address2.ToString().c_str());
    } else {
		if (!fProofOfStake)
			txNew.vout[0].nValue = blockValue;
	}
}
Beispiel #13
0
void SendCoinsDialog::on_sendButton_clicked()
{
    bool valid;
    QString payAmount = ui->payAmount->text();
    QString label;
    qint64 payAmountParsed;

    valid = ParseMoney(payAmount.toStdString(), payAmountParsed);

    if(!valid)
    {
        QMessageBox::warning(this, tr("Send Coins"),
            tr("The amount to pay must be a valid number."),
            QMessageBox::Ok, QMessageBox::Ok);
        return;
    }

    if(ui->addToAddressBook->isChecked())
    {
        // Add address to address book under label, if specified
        label = ui->addAsLabel->text();
    }

    switch(model->sendCoins(ui->payTo->text(), payAmountParsed, label))
    {
    case ClientModel::InvalidAddress:
        QMessageBox::warning(this, tr("Send Coins"),
            tr("The recepient address is not valid, please recheck."),
            QMessageBox::Ok, QMessageBox::Ok);
        ui->payTo->setFocus();
        break;
    case ClientModel::InvalidAmount:
        QMessageBox::warning(this, tr("Send Coins"),
            tr("The amount to pay must be larger than 0."),
            QMessageBox::Ok, QMessageBox::Ok);
        ui->payAmount->setFocus();
        break;
    case ClientModel::AmountExceedsBalance:
        QMessageBox::warning(this, tr("Send Coins"),
            tr("Amount exceeds your balance"),
            QMessageBox::Ok, QMessageBox::Ok);
        ui->payAmount->setFocus();
        break;
    case ClientModel::AmountWithFeeExceedsBalance:
        QMessageBox::warning(this, tr("Send Coins"),
            tr("Total exceeds your balance when the %1 transaction fee is included").
                arg(QString::fromStdString(FormatMoney(model->getOptionsModel()->getTransactionFee()))),
            QMessageBox::Ok, QMessageBox::Ok);
        ui->payAmount->setFocus();
        break;
    case ClientModel::OK:
        accept();
        break;
    }
}
Beispiel #14
0
void BitcoinGUI::askFee(qint64 nFeeRequired, bool *payFee)
{
    QString strMessage =
        tr("This transaction is over the size limit.  You can still send it for a fee of %1, "
          "which goes to the nodes that process your transaction and helps to support the network.  "
          "Do you want to pay the fee?").arg(QString::fromStdString(FormatMoney(nFeeRequired)));
    QMessageBox::StandardButton retval = QMessageBox::question(
          this, tr("Sending..."), strMessage,
          QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Yes);
    *payFee = (retval == QMessageBox::Yes);
}
Beispiel #15
0
std::string GetWalletHelpString(bool showDebug)
{
    std::string strUsage = HelpMessageGroup(_("Wallet options:"));
    strUsage += HelpMessageOpt("-addresstype", strprintf("What type of addresses to use (\"legacy\", \"p2sh-segwit\", or \"bech32\", default: \"%s\")", FormatOutputType(OUTPUT_TYPE_DEFAULT)));
    strUsage += HelpMessageOpt("-changetype", "What type of change to use (\"legacy\", \"p2sh-segwit\", or \"bech32\"). Default is same as -addresstype, except when -addresstype=p2sh-segwit a native segwit output is used when sending to a native segwit address)");
    strUsage += HelpMessageOpt("-disablewallet", _("Do not load the wallet and disable wallet RPC calls"));
    strUsage += HelpMessageOpt("-discardfee=<amt>", strprintf(_("The fee rate (in %s/kB) that indicates your tolerance for discarding change by adding it to the fee (default: %s). "
                                                                "Note: An output is discarded if it is dust at this rate, but we will always discard up to the dust relay fee and a discard fee above that is limited by the fee estimate for the longest target"),
                                                              CURRENCY_UNIT, FormatMoney(DEFAULT_DISCARD_FEE)));
    strUsage += HelpMessageOpt("-fallbackfee=<amt>", strprintf(_("A fee rate (in %s/kB) that will be used when fee estimation has insufficient data (default: %s)"),
                                                               CURRENCY_UNIT, FormatMoney(DEFAULT_FALLBACK_FEE)));
    strUsage += HelpMessageOpt("-keypool=<n>", strprintf(_("Set key pool size to <n> (default: %u)"), DEFAULT_KEYPOOL_SIZE));
    strUsage += HelpMessageOpt("-mintxfee=<amt>", strprintf(_("Fees (in %s/kB) smaller than this are considered zero fee for transaction creation (default: %s)"),
                                                            CURRENCY_UNIT, FormatMoney(DEFAULT_TRANSACTION_MINFEE)));
    strUsage += HelpMessageOpt("-paytxfee=<amt>", strprintf(_("Fee (in %s/kB) to add to transactions you send (default: %s)"),
                                                            CURRENCY_UNIT, FormatMoney(payTxFee.GetFeePerK())));
    strUsage += HelpMessageOpt("-rescan", _("Rescan the block chain for missing wallet transactions on startup"));
    strUsage += HelpMessageOpt("-salvagewallet", _("Attempt to recover private keys from a corrupt wallet on startup"));
    strUsage += HelpMessageOpt("-spendzeroconfchange", strprintf(_("Spend unconfirmed change when sending transactions (default: %u)"), DEFAULT_SPEND_ZEROCONF_CHANGE));
    strUsage += HelpMessageOpt("-txconfirmtarget=<n>", strprintf(_("If paytxfee is not set, include enough fee so transactions begin confirmation on average within n blocks (default: %u)"), DEFAULT_TX_CONFIRM_TARGET));
    strUsage += HelpMessageOpt("-upgradewallet", _("Upgrade wallet to latest format on startup"));
    strUsage += HelpMessageOpt("-wallet=<file>", _("Specify wallet file (within data directory)") + " " + strprintf(_("(default: %s)"), DEFAULT_WALLET_DAT));
    strUsage += HelpMessageOpt("-walletbroadcast", _("Make the wallet broadcast transactions") + " " + strprintf(_("(default: %u)"), DEFAULT_WALLETBROADCAST));
    strUsage += HelpMessageOpt("-walletdir=<dir>", _("Specify directory to hold wallets (default: <datadir>/wallets if it exists, otherwise <datadir>)"));
    strUsage += HelpMessageOpt("-walletnotify=<cmd>", _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)"));
    strUsage += HelpMessageOpt("-walletrbf", strprintf(_("Send transactions with full-RBF opt-in enabled (RPC only, default: %u)"), DEFAULT_WALLET_RBF));
    strUsage += HelpMessageOpt("-zapwallettxes=<mode>", _("Delete all wallet transactions and only recover those parts of the blockchain through -rescan on startup") +
                               " " + _("(1 = keep tx meta data e.g. account owner and payment request information, 2 = drop tx meta data)"));

    if (showDebug)
    {
        strUsage += HelpMessageGroup(_("Wallet debugging/testing options:"));

        strUsage += HelpMessageOpt("-dblogsize=<n>", strprintf("Flush wallet database activity from memory to disk log every <n> megabytes (default: %u)", DEFAULT_WALLET_DBLOGSIZE));
        strUsage += HelpMessageOpt("-flushwallet", strprintf("Run a thread to flush wallet periodically (default: %u)", DEFAULT_FLUSHWALLET));
        strUsage += HelpMessageOpt("-privdb", strprintf("Sets the DB_PRIVATE flag in the wallet db environment (default: %u)", DEFAULT_WALLET_PRIVDB));
        strUsage += HelpMessageOpt("-walletrejectlongchains", strprintf(_("Wallet will not create transactions that violate mempool chain limits (default: %u)"), DEFAULT_WALLET_REJECT_LONG_CHAINS));
    }

    return strUsage;
}
void CreateProposalDialog::Clear()
{
    ui->lineEdit_Abstract->clear();
    ui->lineEdit_Length->clear();
    ui->lineEdit_Name->clear();
    ui->lineEdit_StartBlock->clear();
    ui->label_Fee_result->setText(QString::fromStdString(FormatMoney(CVoteProposal::FEE)));
    ui->label_Hash_result->setText("(Automatically Generated)");
    ui->label_Location_result->setText("(Automatically Generated)");
    ui->label_Location_result->setText("(Automatically Generated)");
    ui->button_SendProposal->setEnabled(false);
}
Beispiel #17
0
QString GingerCoinUnits::format(int unit, const mpq& n, bool fPlus)
{
    // Note: not using straight sprintf here because we do NOT want
    // localized number formatting.
    if(!valid(unit))
        return QString(); // Refuse to format invalid unit
    mpq q = n * COIN / factor(unit);
    std::string str = FormatMoney(q, fPlus);
    int diff = 8 - decimals(unit);
    if(diff > 0)
        str.erase(str.length() - diff, diff);
    return QString::fromStdString(str);
}
Beispiel #18
0
std::vector<Game::Coord> Bot::getGatherAfkCoords(const Game::PlayerState &playerState,const Game::GameState &gameState) {
	std::vector<Game::Coord> result;
	BOOST_FOREACH(const PAIRTYPE(int, Game::CharacterState) &charState, playerState.characters) {
		if (charState.first > 2) {continue;}
		if (charState.second.loot.nAmount >= maxLoot) {
			printf("MAX LOOT %s GO HOME -- ",FormatMoney(charState.second.loot.nAmount).c_str());
			result.push_back(BotHelper::getHomeCoord(color));
		} else if (dests.size() > charState.first) {
			printf("CHAR %d SEND TO DEST (%d,%d) -- ",charState.first,dests[charState.first].x,dests[charState.first].y);
			result.push_back(dests[charState.first]);
		}
	}
	return result;
}
Beispiel #19
0
void TxToUniv(const CTransaction& tx, const uint256& hashBlock, UniValue& entry)
{
    entry.pushKV("txid", tx.GetHash().GetHex());
    entry.pushKV("version", tx.nVersion);
    entry.pushKV("locktime", (int64_t)tx.nLockTime);

    UniValue vin(UniValue::VARR);
    BOOST_FOREACH(const CTxIn& txin, tx.vin) {
        UniValue in(UniValue::VOBJ);
        if (tx.IsCoinBase())
            in.pushKV("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end()));
        else {
            in.pushKV("txid", txin.prevout.hash.GetHex());
            in.pushKV("vout", (int64_t)txin.prevout.n);
            UniValue o(UniValue::VOBJ);
            o.pushKV("asm", txin.scriptSig.ToString());
            o.pushKV("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end()));
            in.pushKV("scriptSig", o);
        }
        in.pushKV("sequence", (int64_t)txin.nSequence);
        vin.push_back(in);
    }
    entry.pushKV("vin", vin);

    UniValue vout(UniValue::VARR);
    for (unsigned int i = 0; i < tx.vout.size(); i++) {
        const CTxOut& txout = tx.vout[i];

        UniValue out(UniValue::VOBJ);

        UniValue outValue(UniValue::VNUM, FormatMoney(txout.nValue));
        out.pushKV("value", outValue);
        out.pushKV("n", (int64_t)i);

        UniValue o(UniValue::VOBJ);
        ScriptPubKeyToUniv(txout.scriptPubKey, o, true);
        out.pushKV("scriptPubKey", o);
        vout.push_back(out);
    }
    entry.pushKV("vout", vout);

    if (hashBlock != 0)
        entry.pushKV("blockhash", hashBlock.GetHex());
}
Beispiel #20
0
/*  Create a nice string to show the denominations
    Function returns as follows (for 4 denominations):
        ( bit on if present )
        bit 0           - 10
        bit 1           - 1
        bit 2           - .1
        bit 3           - .01
        bit 4 and so on - out-of-bounds
        none of above   - non-denom
*/
std::string CPrivateSend::GetDenominationsToString(int nDenom)
{
    std::string strDenom = "";
    int nMaxDenoms = vecStandardDenominations.size();

    if(nDenom >= (1 << nMaxDenoms)) {
        return "out-of-bounds";
    }

    for (int i = 0; i < nMaxDenoms; ++i) {
        if(nDenom & (1 << i)) {
            strDenom += (strDenom.empty() ? "" : "+") + FormatMoney(vecStandardDenominations[i]);
        }
    }

    if(strDenom.empty()) {
        return "non-denom";
    }

    return strDenom;
}
Beispiel #21
0
void BitcoinGUI::incomingTransaction(const QModelIndex & parent, int start, int end)
{
    TransactionTableModel *ttm = model->getTransactionTableModel();
    qint64 amount = ttm->index(start, TransactionTableModel::Amount, parent)
                    .data(Qt::EditRole).toULongLong();
    if(amount>0 && !model->inInitialBlockDownload())
    {
        // On incoming transaction, make an info balloon
        // Unless the initial block download is in progress, to prevent balloon-spam
        QString date = ttm->index(start, TransactionTableModel::Date, parent)
                        .data().toString();
        QString type = ttm->index(start, TransactionTableModel::Type, parent)
                        .data().toString();
        QString address = ttm->index(start, TransactionTableModel::ToAddress, parent)
                        .data().toString();

        // TODO! Make chain of notifications (if Freedesktop notify not supported use Qt Notify and add this to Notification)
        /*trayIcon->showMessage(tr("Incoming transaction"),
                              tr("Date: ") + date + "\n" +
                              tr("Amount: ") + QString::fromStdString(FormatMoney(amount, true)) + "\n" +
                              tr("Type: ") + type + "\n" +
                              tr("Address: ") + address + "\n",
                              QSystemTrayIcon::Information);*/

        // TODO! Icon hardcoded because of that QIcon don't return path of file
        Notifiction::instance()->notify(tr("Date: %1\n"
                                           "Amount: %2\n"
                                           "Type: %3\n"
                                           "Address: %4")
                                        .arg(date)
                                        .arg(QString::fromStdString(FormatMoney(amount, true)))
                                        .arg(type)
                                        .arg(address),
                                        tr("Incoming transaction"),
                                        QLatin1String("/usr/share/icons/oxygen/64x64/actions/main-receive.png"));
    }


}
Beispiel #22
0
void MultisigDialog::updateCoinControl(CAmount nAmount, unsigned int nQuantity)
{
    ui->labelAmount_int->setText(QString::fromStdString(FormatMoney(nAmount)));
    ui->labelQuantity_int->setText(QString::number(nQuantity));
}
Beispiel #23
0
bool KnapsackSolver(const CAmount& nTargetValue, std::vector<CInputCoin>& vCoins, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet)
{
    setCoinsRet.clear();
    nValueRet = 0;

    // List of values less than target
    boost::optional<CInputCoin> coinLowestLarger;
    std::vector<CInputCoin> vValue;
    CAmount nTotalLower = 0;

    random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);

    for (const CInputCoin &coin : vCoins)
    {
        if (coin.txout.nValue == nTargetValue)
        {
            setCoinsRet.insert(coin);
            nValueRet += coin.txout.nValue;
            return true;
        }
        else if (coin.txout.nValue < nTargetValue + MIN_CHANGE)
        {
            vValue.push_back(coin);
            nTotalLower += coin.txout.nValue;
        }
        else if (!coinLowestLarger || coin.txout.nValue < coinLowestLarger->txout.nValue)
        {
            coinLowestLarger = coin;
        }
    }

    if (nTotalLower == nTargetValue)
    {
        for (const auto& input : vValue)
        {
            setCoinsRet.insert(input);
            nValueRet += input.txout.nValue;
        }
        return true;
    }

    if (nTotalLower < nTargetValue)
    {
        if (!coinLowestLarger)
            return false;
        setCoinsRet.insert(coinLowestLarger.get());
        nValueRet += coinLowestLarger->txout.nValue;
        return true;
    }

    // Solve subset sum by stochastic approximation
    std::sort(vValue.begin(), vValue.end(), descending);
    std::vector<char> vfBest;
    CAmount nBest;

    ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest);
    if (nBest != nTargetValue && nTotalLower >= nTargetValue + MIN_CHANGE)
        ApproximateBestSubset(vValue, nTotalLower, nTargetValue + MIN_CHANGE, vfBest, nBest);

    // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
    //                                   or the next bigger coin is closer), return the bigger coin
    if (coinLowestLarger &&
        ((nBest != nTargetValue && nBest < nTargetValue + MIN_CHANGE) || coinLowestLarger->txout.nValue <= nBest))
    {
        setCoinsRet.insert(coinLowestLarger.get());
        nValueRet += coinLowestLarger->txout.nValue;
    }
    else {
        for (unsigned int i = 0; i < vValue.size(); i++)
            if (vfBest[i])
            {
                setCoinsRet.insert(vValue[i]);
                nValueRet += vValue[i].txout.nValue;
            }

        if (LogAcceptCategory(BCLog::SELECTCOINS)) {
            LogPrint(BCLog::SELECTCOINS, "SelectCoins() best subset: "); /* Continued */
            for (unsigned int i = 0; i < vValue.size(); i++) {
                if (vfBest[i]) {
                    LogPrint(BCLog::SELECTCOINS, "%s ", FormatMoney(vValue[i].txout.nValue)); /* Continued */
                }
            }
            LogPrint(BCLog::SELECTCOINS, "total %s\n", FormatMoney(nBest));
        }
    }

    return true;
}
Beispiel #24
0
std::string CTxOut::ToString() const
{
    if (IsEmpty()) return "CTxOut(empty)";
    return strprintf("CTxOut(nValue=%s, scriptPubKey=%s)", FormatMoney(nValue), scriptPubKey.ToString());
}
Beispiel #25
0
void BitcoinGUI::setBalance(qint64 balance)
{
    labelBalance->setText(QString::fromStdString(FormatMoney(balance)));
}
Beispiel #26
0
CFeeBumper::CFeeBumper(const CWallet *pWallet, const uint256 txidIn, int newConfirmTarget, bool specifiedConfirmTarget, CAmount totalFee, bool newTxReplaceable)
    :
    txid(std::move(txidIn)),
    nOldFee(0),
    nNewFee(0)
{
    vErrors.clear();
    bumpedTxid.SetNull();
    AssertLockHeld(pWallet->cs_wallet);
    if (!pWallet->mapWallet.count(txid)) {
        vErrors.push_back("Invalid or non-wallet transaction id");
        currentResult = BumpFeeResult::INVALID_ADDRESS_OR_KEY;
        return;
    }
    auto it = pWallet->mapWallet.find(txid);
    const CWalletTx& wtx = it->second;

    if (!preconditionChecks(pWallet, wtx)) {
        return;
    }

    if (!SignalsOptInRBF(wtx)) {
        vErrors.push_back("Transaction is not BIP 125 replaceable");
        currentResult = BumpFeeResult::WALLET_ERROR;
        return;
    }

    if (wtx.mapValue.count("replaced_by_txid")) {
        vErrors.push_back(strprintf("Cannot bump transaction %s which was already bumped by transaction %s", txid.ToString(), wtx.mapValue.at("replaced_by_txid")));
        currentResult = BumpFeeResult::WALLET_ERROR;
        return;
    }

    // check that original tx consists entirely of our inputs
    // if not, we can't bump the fee, because the wallet has no way of knowing the value of the other inputs (thus the fee)
    if (!pWallet->IsAllFromMe(wtx, ISMINE_SPENDABLE)) {
        vErrors.push_back("Transaction contains inputs that don't belong to this wallet");
        currentResult = BumpFeeResult::WALLET_ERROR;
        return;
    }

    // figure out which output was change
    // if there was no change output or multiple change outputs, fail
    int nOutput = -1;
    for (size_t i = 0; i < wtx.tx->vout.size(); ++i) {
        if (pWallet->IsChange(wtx.tx->vout[i])) {
            if (nOutput != -1) {
                vErrors.push_back("Transaction has multiple change outputs");
                currentResult = BumpFeeResult::WALLET_ERROR;
                return;
            }
            nOutput = i;
        }
    }
    if (nOutput == -1) {
        vErrors.push_back("Transaction does not have a change output");
        currentResult = BumpFeeResult::WALLET_ERROR;
        return;
    }

    // Calculate the expected size of the new transaction.
    int64_t txSize = GetVirtualTransactionSize(*(wtx.tx));
    const int64_t maxNewTxSize = CalculateMaximumSignedTxSize(*wtx.tx, pWallet);
    if (maxNewTxSize < 0) {
        vErrors.push_back("Transaction contains inputs that cannot be signed");
        currentResult = BumpFeeResult::INVALID_ADDRESS_OR_KEY;
        return;
    }

    // calculate the old fee and fee-rate
    nOldFee = wtx.GetDebit(ISMINE_SPENDABLE) - wtx.tx->GetValueOut();
    CFeeRate nOldFeeRate(nOldFee, txSize);
    CFeeRate nNewFeeRate;
    // The wallet uses a conservative WALLET_INCREMENTAL_RELAY_FEE value to
    // future proof against changes to network wide policy for incremental relay
    // fee that our node may not be aware of.
    CFeeRate walletIncrementalRelayFee = CFeeRate(WALLET_INCREMENTAL_RELAY_FEE);
    if (::incrementalRelayFee > walletIncrementalRelayFee) {
        walletIncrementalRelayFee = ::incrementalRelayFee;
    }

    if (totalFee > 0) {
        CAmount minTotalFee = nOldFeeRate.GetFee(maxNewTxSize) + ::incrementalRelayFee.GetFee(maxNewTxSize);
        if (totalFee < minTotalFee) {
            vErrors.push_back(strprintf("Insufficient totalFee, must be at least %s (oldFee %s + incrementalFee %s)",
                                                                FormatMoney(minTotalFee), FormatMoney(nOldFeeRate.GetFee(maxNewTxSize)), FormatMoney(::incrementalRelayFee.GetFee(maxNewTxSize))));
            currentResult = BumpFeeResult::INVALID_PARAMETER;
            return;
        }
        CAmount requiredFee = CWallet::GetRequiredFee(maxNewTxSize);
        if (totalFee < requiredFee) {
            vErrors.push_back(strprintf("Insufficient totalFee (cannot be less than required fee %s)",
                                                                FormatMoney(requiredFee)));
            currentResult = BumpFeeResult::INVALID_PARAMETER;
            return;
        }
        nNewFee = totalFee;
        nNewFeeRate = CFeeRate(totalFee, maxNewTxSize);
    } else {
        // if user specified a confirm target then don't consider any global payTxFee
        if (specifiedConfirmTarget) {
            nNewFee = CWallet::GetMinimumFee(maxNewTxSize, newConfirmTarget, mempool, ::feeEstimator, true);
        }
        // otherwise use the regular wallet logic to select payTxFee or default confirm target
        else {
            nNewFee = CWallet::GetMinimumFee(maxNewTxSize, newConfirmTarget, mempool, ::feeEstimator);
        }

        nNewFeeRate = CFeeRate(nNewFee, maxNewTxSize);

        // New fee rate must be at least old rate + minimum incremental relay rate
        // walletIncrementalRelayFee.GetFeePerK() should be exact, because it's initialized
        // in that unit (fee per kb).
        // However, nOldFeeRate is a calculated value from the tx fee/size, so
        // add 1 satoshi to the result, because it may have been rounded down.
        if (nNewFeeRate.GetFeePerK() < nOldFeeRate.GetFeePerK() + 1 + walletIncrementalRelayFee.GetFeePerK()) {
            nNewFeeRate = CFeeRate(nOldFeeRate.GetFeePerK() + 1 + walletIncrementalRelayFee.GetFeePerK());
            nNewFee = nNewFeeRate.GetFee(maxNewTxSize);
        }
    }

    // Check that in all cases the new fee doesn't violate maxTxFee
     if (nNewFee > maxTxFee) {
         vErrors.push_back(strprintf("Specified or calculated fee %s is too high (cannot be higher than maxTxFee %s)",
                               FormatMoney(nNewFee), FormatMoney(maxTxFee)));
         currentResult = BumpFeeResult::WALLET_ERROR;
         return;
     }

    // check that fee rate is higher than mempool's minimum fee
    // (no point in bumping fee if we know that the new tx won't be accepted to the mempool)
    // This may occur if the user set TotalFee or paytxfee too low, if fallbackfee is too low, or, perhaps,
    // in a rare situation where the mempool minimum fee increased significantly since the fee estimation just a
    // moment earlier. In this case, we report an error to the user, who may use totalFee to make an adjustment.
    CFeeRate minMempoolFeeRate = mempool.GetMinFee(GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000);
    if (nNewFeeRate.GetFeePerK() < minMempoolFeeRate.GetFeePerK()) {
        vErrors.push_back(strprintf("New fee rate (%s) is less than the minimum fee rate (%s) to get into the mempool. totalFee value should to be at least %s or settxfee value should be at least %s to add transaction.", FormatMoney(nNewFeeRate.GetFeePerK()), FormatMoney(minMempoolFeeRate.GetFeePerK()), FormatMoney(minMempoolFeeRate.GetFee(maxNewTxSize)), FormatMoney(minMempoolFeeRate.GetFeePerK())));
        currentResult = BumpFeeResult::WALLET_ERROR;
        return;
    }

    // Now modify the output to increase the fee.
    // If the output is not large enough to pay the fee, fail.
    CAmount nDelta = nNewFee - nOldFee;
    assert(nDelta > 0);
    mtx =  *wtx.tx;
    CTxOut* poutput = &(mtx.vout[nOutput]);
    if (poutput->nValue < nDelta) {
        vErrors.push_back("Change output is too small to bump the fee");
        currentResult = BumpFeeResult::WALLET_ERROR;
        return;
    }

    // If the output would become dust, discard it (converting the dust to fee)
    poutput->nValue -= nDelta;
    if (poutput->nValue <= GetDustThreshold(*poutput, ::dustRelayFee)) {
        LogPrint(BCLog::RPC, "Bumping fee and discarding dust output\n");
        nNewFee += poutput->nValue;
        mtx.vout.erase(mtx.vout.begin() + nOutput);
    }

    // Mark new tx not replaceable, if requested.
    if (!newTxReplaceable) {
        for (auto& input : mtx.vin) {
            if (input.nSequence < 0xfffffffe) input.nSequence = 0xfffffffe;
        }
    }

    currentResult = BumpFeeResult::OK;
}
Beispiel #27
0
void ExtFrame::OnLevel1()
{
    const StockBase* stockHandle = B_GetStockHandle("AMD");
    CString str;
    if(B_IsStockValid(stockHandle))
    {
        char num[33];
        Observable* level1 = B_GetLevel1(stockHandle);
        str += "BidTick ";
        switch(B_GetBidTickStatus(level1))
        {
            case NOTICK:
            str += "NO";
            break;

            case UPTICK:
            str += "UP";
            break;

            case DOWNTICK:
            str += "DOWN";
            break;
        }

        str += "\nBid ";
        FormatMoneySize(str, B_GetBid(level1));

        str += "\nAsk ";
        FormatMoneySize(str, B_GetAsk(level1));
        
        str += "\nLastTrade ";
        FormatMoneySize(str, B_GetLastTrade(level1));
        
        str += "\nLastTradeTime ";
        CTime t(B_GetLastTradeTime(level1));
        str += t.Format("%H:%M:%S");
        
        str += "\nVolume ";
		_i64toa_s(B_GetVolume(level1), num, sizeof(num), 10);
        str += num;
        
        str += "\nOpen Price ";
        FormatMoney(str, B_GetOpenPrice(level1));

        str += "\nClose Price ";
        FormatMoney(str, B_GetClosePrice(level1));

        str += "\nHi Price ";
        FormatMoney(str, B_GetIntraDayHigh(level1));

        str += "\nLo Price ";
        FormatMoney(str, B_GetIntraDayLow(level1));

        str += "\nNet Change ";
        FormatMoney(str, B_GetNetChange(level1));
    }	
	else
    {
        str += "Stock is not loaded yet. Try again";
    }
    AfxGetMainWnd()->MessageBox(str, "INTC Level 1", MB_OK);
}
WalletModel::SendCoinsReturn WalletModel::sendCoins(const QList<SendCoinsRecipient> &recipients, const CCoinControl *coinControl)
{
    qint64 total = 0;
    QSet<QString> setAddress;
    QString hex;

    if(recipients.empty())
    {
        return OK;
    }

    // Pre-check input data for validity
    foreach(const SendCoinsRecipient &rcp, recipients)
    {
        if(!validateAddress(rcp.address))
        {
            return InvalidAddress;
        }
        setAddress.insert(rcp.address);

        if(rcp.amount <= 0)
        {
            return InvalidAmount;
        }
        total += rcp.amount;
    }

    if(recipients.size() > setAddress.size())
    {
        return DuplicateAddress;
    }

    int64_t nBalance = 0;
    std::vector<COutput> vCoins;
    wallet->AvailableCoins(vCoins, true, coinControl);

    BOOST_FOREACH(const COutput& out, vCoins)
        nBalance += out.tx->vout[out.i].nValue;

    if(total > nBalance)
    {
        return AmountExceedsBalance;
    }

    if((total + nTransactionFee) > nBalance)
    {
        return SendCoinsReturn(AmountWithFeeExceedsBalance, nTransactionFee);
    }

	std::string txid = "";
	std::string messages = "";
	std::string hashBoinc = "";

    {
        LOCK2(cs_main, wallet->cs_wallet);

        // Sendmany
        std::vector<std::pair<CScript, int64_t> > vecSend;
		bool coinTracking = false;
		foreach(const SendCoinsRecipient &rcp, recipients)
        {
            CScript scriptPubKey;
            scriptPubKey.SetDestination(CBitcoinAddress(rcp.address.toStdString()).Get());
            vecSend.push_back(make_pair(scriptPubKey, rcp.amount));
			if (rcp.CoinTracking) coinTracking=true;
			messages += "<MESSAGE>" + AdvancedCrypt(FromQStringW(rcp.Message)) + "</MESSAGE>";
        
        }

        CWalletTx wtx;
        CReserveKey keyChange(wallet);
        int64_t nFeeRequired = 0;
		if (coinTracking)
		{
			printf("Creating tracked tx : old hashboinc %s",wtx.hashBoinc.c_str());
			wtx.hashBoinc = "<TRACK>" + wtx.GetHash().ToString() + "</TRACK>";
			//Run time code execution feature - 12-7-2014
			std::string q = "\"";
			std::string code = "MsgBox(" + q + "Hello!" + q + ",MsgBoxStyle.Critical," + q + "Message Title" + q + ")\r\n";
			wtx.hashBoinc += "<CODE>" + code + "</CODE>";
		}

		if (!msAttachmentGuid.empty())
		{
				printf("Adding attachment to tx %s",wtx.hashBoinc.c_str());
				wtx.hashBoinc += "<ATTACHMENT><TXID>" + wtx.GetHash().ToString() + "</TXID><ATTACHMENTGUID>" + msAttachmentGuid + "</ATTACHMENTGUID></ATTACHMENT>";
		}
		wtx.hashBoinc += messages;
		bool fCreated = wallet->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, coinControl);

        if(!fCreated)
        {
            if((total + nFeeRequired) > nBalance) // FIXME: could cause collisions in the future
            {
                return SendCoinsReturn(AmountWithFeeExceedsBalance, nFeeRequired);
            }
            return TransactionCreationFailed;
        }
       
		if (coinTracking)
		{
			printf("Tracking hashBoinc %s",wtx.hashBoinc.c_str());
		}
		
		
		std::string samt = FormatMoney(wtx.vout[0].nValue);
		double dblAmt = dblFromAmount(wtx.vout[0].nValue);
	

        if(!uiInterface.ThreadSafeAskFee(nFeeRequired, tr("Sending...").toStdString()))
        {
            return Aborted;
        }
        if(!wallet->CommitTransaction(wtx, keyChange))
        {
            return TransactionCommitFailed;
        }
        hex = QString::fromStdString(wtx.GetHash().GetHex());
		txid = wtx.GetHash().GetHex();
		hashBoinc = wtx.hashBoinc;
    }
Beispiel #29
0
void ExtFrame::OnBookQuotes() 
{
	// TODO: Add your command handler code here
    const StockBase* stockHandle = B_GetStockHandle("INTC");
    CString str;
    if(B_IsStockValid(stockHandle))
    {
        const BookEntry* be;
        const unsigned int entries = 6;
        unsigned int count;
        char num[33];

        
//        Observable* book = B_GetExpandedBook(stockHandle);
        unsigned int filter = 0xFFFFFFFF & ~(1 << NYSE_BOOK);
		unsigned int mmLines = 0xFFFFFFFF;
        void* bidIterator = B_CreateMultiBookIterator(stockHandle, true, false, filter, mmLines, false, NULL);//m_aggregatedView, this);

        str += "BIDS\n";
        count = 0;
        B_StartIteration(bidIterator);
        while((be = B_GetNextBookEntry(bidIterator)) && count < entries)
        {
            count++;
            str += be->GetMmid();
            str += "  ";
//            FormatDollarsAndCents(str, be->GetPriceWhole(), be->GetPriceThousandsFraction());
            FormatMoney(str, *be);
            str += "  ";
			_itoa_s(be->GetSize(), num, sizeof(num), 10);
            str += num;
            str += "\n";
        }
        B_DestroyIterator(bidIterator);

        str += "\nASKS\n";
        count = 0;
//        unsigned int m_askIterator = B_CreateBookIterator(book, false);
        void* askIterator = B_CreateMultiBookIterator(stockHandle, false, false, filter, mmLines, false, NULL);//m_aggregatedView, this);
        B_StartIteration(askIterator);
        while((be = B_GetNextBookEntry(askIterator)) && count < entries)
        {
            count++;
            str += be->GetMmid();
            str += "  ";
//            FormatDollarsAndCents(str, be->GetPriceWhole(), be->GetPriceThousandsFraction());
            FormatMoney(str, *be);
            str += "  ";
			_itoa_s(be->GetSize(), num, sizeof(num), 10);
            str += num;
            str += "\n";
        }
        B_DestroyIterator(askIterator);

    }
	else
    {
        str += "Stock is not loaded yet. Try again";
    }
	
    AfxGetMainWnd()->MessageBox(str, "INTC Expanded Book", MB_OK);
}
Beispiel #30
0
void ExtFrame::OnAccount() 
{
    Observable* account = B_GetCurrentAccount();
    if(account)
    {
        char num[33];
        CString accountInfo;
        accountInfo += "Name ";
        accountInfo += B_GetAccountName(account);

        accountInfo += "\nFirm ";
        accountInfo += B_GetAccountFirm(account);
        
        accountInfo += "\nSimulation ";
        accountInfo += B_IsAccountSimulation(account) ? "Yes" : "No";
        
        accountInfo += "\nMaxOpenPosMoney ";
        FormatMoney(accountInfo, B_GetAccountMaxOpenPositionValue(account));
        
        accountInfo += "\nMaxOpenPosSize ";
		_itoa_s(B_GetMaxOpenPositionSize(account), num, sizeof(num), 10);
        accountInfo += num;
        
        accountInfo += "\nMaxOrderSize ";
		_itoa_s(B_GetMaxOrderSize(account), num, sizeof(num), 10);
        accountInfo += num;
        
        accountInfo += "\nBuyingPower ";
        FormatMoney(accountInfo, B_GetAccountBuyingPower(account));

        accountInfo += "\nBuyingPower in use ";
        FormatMoney(accountInfo, B_GetAccountBuyingPowerInUse(account));

        accountInfo += "\nOpen P&&L ";
        FormatMoney(accountInfo, B_GetAccountOpenPnl(account));

        accountInfo += "\nClosed P&&L ";
        FormatMoney(accountInfo, B_GetAccountClosedPnl(account));

        accountInfo += "\nSharesTraded ";
		_itoa_s(B_GetAccountSharesTraded(account), num, sizeof(num), 10);
        accountInfo += num;
        
        accountInfo += "\nLongPositions ";
		_itoa_s(B_GetLongPositionsCount(account), num, sizeof(num), 10);
        accountInfo += num;
        
        accountInfo += "\nShortPositions ";
		_itoa_s(B_GetShortPositionsCount(account), num, sizeof(num), 10);
        accountInfo += num;
        
        accountInfo += "\nMoney Invested ";
        FormatMoney(accountInfo, B_GetAccountMoneyInvested(account));

        accountInfo += "\nMoney Traded Long ";
        FormatMoney(accountInfo, B_GetAccountMoneyTradedLong(account));

        accountInfo += "\nMoney Traded Short ";
        FormatMoney(accountInfo, B_GetAccountMoneyTradedShort(account));

        accountInfo += "\nMoney Traded ";
        FormatMoney(accountInfo, B_GetAccountMoneyTraded(account));

        AfxGetMainWnd()->MessageBox(accountInfo, "Account", MB_OK);
    }
/*
Observable* WINAPI B_SetCurrentAccount(const char* name);
Observable* WINAPI B_GetAccount(const char* name);
Order* WINAPI B_CancelLastOrder(CO_BUY | CO_SELL | CO_NONDAY | CO_DAY, const Observable* account = NULL);
void WINAPI B_CancelAllOrders(CO_BUY | CO_SELL | CO_NONDAY | CO_DAY, const Observable* account = NULL);
void WINAPI B_CancelAllStockOrders(const char* symbol, CO_BUY | CO_SELL | CO_NONDAY | CO_DAY, const Observable* account = NULL);
*/
}