Research
Timechain
Search Donate
Sponsors
Cake Wallet, private Bitcoin and Monero walletSideShift.ai, no-signup crypto exchangeOrangeRock, non-custodial bitcoin spot and perps tradingBraiins Hashpower, buy and sell Bitcoin hashrateeCash.com
Bitcoin v0.1.3 · 2009-01-12

ui.cpp

3,228 lines · plain text · MIT license (license.txt)
1// Copyright (c) 2009 Satoshi Nakamoto2// Distributed under the MIT/X11 software license, see the accompanying3// file license.txt or http://www.opensource.org/licenses/mit-license.php.45#include "headers.h"6#ifdef _MSC_VER7#include <crtdbg.h>8#endif9101112DEFINE_EVENT_TYPE(wxEVT_CROSSTHREADCALL)13DEFINE_EVENT_TYPE(wxEVT_REPLY1)14DEFINE_EVENT_TYPE(wxEVT_REPLY2)15DEFINE_EVENT_TYPE(wxEVT_REPLY3)16DEFINE_EVENT_TYPE(wxEVT_TABLEADDED)17DEFINE_EVENT_TYPE(wxEVT_TABLEUPDATED)18DEFINE_EVENT_TYPE(wxEVT_TABLEDELETED)1920CMainFrame* pframeMain = NULL;21map<string, string> mapAddressBook;222324void ThreadRequestProductDetails(void* parg);25void ThreadRandSendTest(void* parg);26bool fRandSendTest = false;27void RandSend();28293031323334//////////////////////////////////////////////////////////////////////////////35//36// Util37//3839void HandleCtrlA(wxKeyEvent& event)40{41    // Ctrl-a select all42    wxTextCtrl* textCtrl = (wxTextCtrl*)event.GetEventObject();43    if (event.GetModifiers() == wxMOD_CONTROL && event.GetKeyCode() == 'A')44        textCtrl->SetSelection(-1, -1);45    event.Skip();46}4748bool Is24HourTime()49{50    //char pszHourFormat[256];51    //pszHourFormat[0] = '\0';52    //GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_ITIME, pszHourFormat, 256);53    //return (pszHourFormat[0] != '0');54    return true;55}5657string DateStr(int64 nTime)58{59    return (string)wxDateTime((time_t)nTime).FormatDate();60}6162string DateTimeStr(int64 nTime)63{64    wxDateTime datetime((time_t)nTime);65    if (Is24HourTime())66        return (string)datetime.Format("%x %H:%M");67    else68        return (string)datetime.Format("%x ") + itostr((datetime.GetHour() + 11) % 12 + 1) + (string)datetime.Format(":%M %p");69}7071wxString GetItemText(wxListCtrl* listCtrl, int nIndex, int nColumn)72{73    // Helper to simplify access to listctrl74    wxListItem item;75    item.m_itemId = nIndex;76    item.m_col = nColumn;77    item.m_mask = wxLIST_MASK_TEXT;78    if (!listCtrl->GetItem(item))79        return "";80    return item.GetText();81}8283int InsertLine(wxListCtrl* listCtrl, const wxString& str0, const wxString& str1)84{85    int nIndex = listCtrl->InsertItem(listCtrl->GetItemCount(), str0);86    listCtrl->SetItem(nIndex, 1, str1);87    return nIndex;88}8990int InsertLine(wxListCtrl* listCtrl, const wxString& str0, const wxString& str1, const wxString& str2, const wxString& str3, const wxString& str4)91{92    int nIndex = listCtrl->InsertItem(listCtrl->GetItemCount(), str0);93    listCtrl->SetItem(nIndex, 1, str1);94    listCtrl->SetItem(nIndex, 2, str2);95    listCtrl->SetItem(nIndex, 3, str3);96    listCtrl->SetItem(nIndex, 4, str4);97    return nIndex;98}99100int InsertLine(wxListCtrl* listCtrl, void* pdata, const wxString& str0, const wxString& str1, const wxString& str2, const wxString& str3, const wxString& str4)101{102    int nIndex = listCtrl->InsertItem(listCtrl->GetItemCount(), str0);103    listCtrl->SetItemPtrData(nIndex, (wxUIntPtr)pdata);104    listCtrl->SetItem(nIndex, 1, str1);105    listCtrl->SetItem(nIndex, 2, str2);106    listCtrl->SetItem(nIndex, 3, str3);107    listCtrl->SetItem(nIndex, 4, str4);108    return nIndex;109}110111void SetSelection(wxListCtrl* listCtrl, int nIndex)112{113    int nSize = listCtrl->GetItemCount();114    long nState = (wxLIST_STATE_SELECTED|wxLIST_STATE_FOCUSED);115    for (int i = 0; i < nSize; i++)116        listCtrl->SetItemState(i, (i == nIndex ? nState : 0), nState);117}118119int GetSelection(wxListCtrl* listCtrl)120{121    int nSize = listCtrl->GetItemCount();122    for (int i = 0; i < nSize; i++)123        if (listCtrl->GetItemState(i, wxLIST_STATE_FOCUSED))124            return i;125    return -1;126}127128129string HtmlEscape(const char* psz, bool fMultiLine=false)130{131    int len = 0;132    for (const char* p = psz; *p; p++)133    {134             if (*p == '<') len += 4;135        else if (*p == '>') len += 4;136        else if (*p == '&') len += 5;137        else if (*p == '"') len += 6;138        else if (*p == ' ' && p > psz && p[-1] == ' ' && p[1] == ' ') len += 6;139        else if (*p == '\n' && fMultiLine) len += 5;140        else141            len++;142    }143    string str;144    str.reserve(len);145    for (const char* p = psz; *p; p++)146    {147             if (*p == '<') str += "&lt;";148        else if (*p == '>') str += "&gt;";149        else if (*p == '&') str += "&amp;";150        else if (*p == '"') str += "&quot;";151        else if (*p == ' ' && p > psz && p[-1] == ' ' && p[1] == ' ') str += "&nbsp;";152        else if (*p == '\n' && fMultiLine) str += "<br>\n";153        else154            str += *p;155    }156    return str;157}158159string HtmlEscape(const string& str, bool fMultiLine=false)160{161    return HtmlEscape(str.c_str(), fMultiLine);162}163164void AddToMyProducts(CProduct product)165{166    CProduct& productInsert = mapMyProducts[product.GetHash()];167    productInsert = product;168    InsertLine(pframeMain->m_listCtrlProductsSent, &productInsert,169                product.mapValue["category"],170                product.mapValue["title"].substr(0, 100),171                product.mapValue["description"].substr(0, 100),172                product.mapValue["price"],173                "");174}175176177178179180181//////////////////////////////////////////////////////////////////////////////182//183// Custom events184//185186set<void*> setCallbackAvailable;187CCriticalSection cs_setCallbackAvailable;188189void AddCallbackAvailable(void* p)190{191    CRITICAL_BLOCK(cs_setCallbackAvailable)192        setCallbackAvailable.insert(p);193}194195void RemoveCallbackAvailable(void* p)196{197    CRITICAL_BLOCK(cs_setCallbackAvailable)198        setCallbackAvailable.erase(p);199}200201bool IsCallbackAvailable(void* p)202{203    CRITICAL_BLOCK(cs_setCallbackAvailable)204        return setCallbackAvailable.count(p);205    return false;206}207208template<typename T>209void AddPendingCustomEvent(wxEvtHandler* pevthandler, int nEventID, const T pbeginIn, const T pendIn)210{211    if (!pevthandler)212        return;213214    const char* pbegin = (pendIn != pbeginIn) ? &pbeginIn[0] : NULL;215    const char* pend = pbegin + (pendIn - pbeginIn) * sizeof(pbeginIn[0]);216    wxCommandEvent event(nEventID);217    wxString strData(wxChar(0), (pend - pbegin) / sizeof(wxChar) + 1);218    memcpy(&strData[0], pbegin, pend - pbegin);219    event.SetString(strData);220    event.SetInt(pend - pbegin);221222    pevthandler->AddPendingEvent(event);223}224225template<class T>226void AddPendingCustomEvent(wxEvtHandler* pevthandler, int nEventID, const T& obj)227{228    CDataStream ss;229    ss << obj;230    AddPendingCustomEvent(pevthandler, nEventID, ss.begin(), ss.end());231}232233void AddPendingReplyEvent1(void* pevthandler, CDataStream& vRecv)234{235    if (IsCallbackAvailable(pevthandler))236        AddPendingCustomEvent((wxEvtHandler*)pevthandler, wxEVT_REPLY1, vRecv.begin(), vRecv.end());237}238239void AddPendingReplyEvent2(void* pevthandler, CDataStream& vRecv)240{241    if (IsCallbackAvailable(pevthandler))242        AddPendingCustomEvent((wxEvtHandler*)pevthandler, wxEVT_REPLY2, vRecv.begin(), vRecv.end());243}244245void AddPendingReplyEvent3(void* pevthandler, CDataStream& vRecv)246{247    if (IsCallbackAvailable(pevthandler))248        AddPendingCustomEvent((wxEvtHandler*)pevthandler, wxEVT_REPLY3, vRecv.begin(), vRecv.end());249}250251CDataStream GetStreamFromEvent(const wxCommandEvent& event)252{253    wxString strData = event.GetString();254    return CDataStream(strData.begin(), strData.begin() + event.GetInt(), SER_NETWORK);255}256257258259260261262263//////////////////////////////////////////////////////////////////////////////264//265// CMainFrame266//267268CMainFrame::CMainFrame(wxWindow* parent) : CMainFrameBase(parent)269{270    Connect(wxEVT_CROSSTHREADCALL, wxCommandEventHandler(CMainFrame::OnCrossThreadCall), NULL, this);271272    // Init273    fRefreshListCtrl = false;274    fRefreshListCtrlRunning = false;275    fOnSetFocusAddress = false;276    pindexBestLast = NULL;277    m_choiceFilter->SetSelection(0);278    m_staticTextBalance->SetLabel(FormatMoney(GetBalance()) + "  ");279    m_listCtrl->SetFocus();280    SetIcon(wxICON(bitcoin));281    m_menuOptions->Check(wxID_OPTIONSGENERATEBITCOINS, fGenerateBitcoins);282283    // Init toolbar with transparency masked bitmaps284    m_toolBar->ClearTools();285286    //// shouldn't have to do mask separately anymore, bitmap alpha support added in wx 2.8.9,287    wxBitmap bmpSend(wxT("send20"), wxBITMAP_TYPE_RESOURCE);288    bmpSend.SetMask(new wxMask(wxBitmap(wxT("send20mask"), wxBITMAP_TYPE_RESOURCE)));289    m_toolBar->AddTool(wxID_BUTTONSEND, wxT("&Send Coins"), bmpSend, wxNullBitmap, wxITEM_NORMAL, wxEmptyString, wxEmptyString);290291    wxBitmap bmpAddressBook(wxT("addressbook20"), wxBITMAP_TYPE_RESOURCE);292    bmpAddressBook.SetMask(new wxMask(wxBitmap(wxT("addressbook20mask"), wxBITMAP_TYPE_RESOURCE)));293    m_toolBar->AddTool(wxID_BUTTONRECEIVE, wxT("&Address Book"), bmpAddressBook, wxNullBitmap, wxITEM_NORMAL, wxEmptyString, wxEmptyString);294295    m_toolBar->Realize();296297    // Init column headers298    int nDateWidth = DateTimeStr(1229413914).size() * 6 + 8;299    m_listCtrl->InsertColumn(0, "",             wxLIST_FORMAT_LEFT,     0);300    m_listCtrl->InsertColumn(1, "",             wxLIST_FORMAT_LEFT,     0);301    m_listCtrl->InsertColumn(2, "Status",       wxLIST_FORMAT_LEFT,    90);302    m_listCtrl->InsertColumn(3, "Date",         wxLIST_FORMAT_LEFT,   nDateWidth);303    m_listCtrl->InsertColumn(4, "Description",  wxLIST_FORMAT_LEFT,   409 - nDateWidth);304    m_listCtrl->InsertColumn(5, "Debit",        wxLIST_FORMAT_RIGHT,   79);305    m_listCtrl->InsertColumn(6, "Credit",       wxLIST_FORMAT_RIGHT,   79);306307    //m_listCtrlProductsSent->InsertColumn(0, "Category",      wxLIST_FORMAT_LEFT,  100);308    //m_listCtrlProductsSent->InsertColumn(1, "Title",         wxLIST_FORMAT_LEFT,  100);309    //m_listCtrlProductsSent->InsertColumn(2, "Description",   wxLIST_FORMAT_LEFT,  100);310    //m_listCtrlProductsSent->InsertColumn(3, "Price",         wxLIST_FORMAT_LEFT,  100);311    //m_listCtrlProductsSent->InsertColumn(4, "",              wxLIST_FORMAT_LEFT,  100);312313    //m_listCtrlOrdersSent->InsertColumn(0, "Time",          wxLIST_FORMAT_LEFT,  100);314    //m_listCtrlOrdersSent->InsertColumn(1, "Price",         wxLIST_FORMAT_LEFT,  100);315    //m_listCtrlOrdersSent->InsertColumn(2, "",              wxLIST_FORMAT_LEFT,  100);316    //m_listCtrlOrdersSent->InsertColumn(3, "",              wxLIST_FORMAT_LEFT,  100);317    //m_listCtrlOrdersSent->InsertColumn(4, "",              wxLIST_FORMAT_LEFT,  100);318319    //m_listCtrlOrdersReceived->InsertColumn(0, "Time",            wxLIST_FORMAT_LEFT,  100);320    //m_listCtrlOrdersReceived->InsertColumn(1, "Price",           wxLIST_FORMAT_LEFT,  100);321    //m_listCtrlOrdersReceived->InsertColumn(2, "Payment Status",  wxLIST_FORMAT_LEFT,  100);322    //m_listCtrlOrdersReceived->InsertColumn(3, "",                wxLIST_FORMAT_LEFT,  100);323    //m_listCtrlOrdersReceived->InsertColumn(4, "",                wxLIST_FORMAT_LEFT,  100);324325    // Init status bar326    int pnWidths[3] = { -100, 81, 286 };327    m_statusBar->SetFieldsCount(3, pnWidths);328329    // Fill your address text box330    vector<unsigned char> vchPubKey;331    if (CWalletDB("r").ReadDefaultKey(vchPubKey))332        m_textCtrlAddress->SetValue(PubKeyToAddress(vchPubKey));333334    // Fill listctrl with wallet transactions335    RefreshListCtrl();336}337338CMainFrame::~CMainFrame()339{340    pframeMain = NULL;341}342343void Shutdown(void* parg)344{345    static CCriticalSection cs_Shutdown;346    CRITICAL_BLOCK(cs_Shutdown)347    {348        fShutdown = true;349        nTransactionsUpdated++;350        DBFlush(false);351        StopNode();352        DBFlush(true);353354        printf("Bitcoin exiting\n");355        exit(0);356    }357}358359void CMainFrame::OnClose(wxCloseEvent& event)360{361    Destroy();362    _beginthread(Shutdown, 0, NULL);363}364365void CMainFrame::OnMouseEvents(wxMouseEvent& event)366{367    RandAddSeed();368    RAND_add(&event.m_x, sizeof(event.m_x), 0.25);369    RAND_add(&event.m_y, sizeof(event.m_y), 0.25);370}371372void CMainFrame::OnListColBeginDrag(wxListEvent& event)373{374     // Hidden columns not resizeable375     if (event.GetColumn() <= 1 && !fDebug)376        event.Veto();377}378379void CMainFrame::InsertLine(bool fNew, int nIndex, uint256 hashKey, string strSort, const wxString& str2, const wxString& str3, const wxString& str4, const wxString& str5, const wxString& str6)380{381    string str0 = strSort;382    long nData = *(long*)&hashKey;383384    if (fNew)385    {386        nIndex = m_listCtrl->InsertItem(0, str0);387    }388    else389    {390        if (nIndex == -1)391        {392            // Find item393            while ((nIndex = m_listCtrl->FindItem(nIndex, nData)) != -1)394                if (GetItemText(m_listCtrl, nIndex, 1) == hashKey.ToString())395                    break;396            if (nIndex == -1)397            {398                printf("CMainFrame::InsertLine : Couldn't find item to be updated\n");399                return;400            }401        }402403        // If sort key changed, must delete and reinsert to make it relocate404        if (GetItemText(m_listCtrl, nIndex, 0) != str0)405        {406            m_listCtrl->DeleteItem(nIndex);407            nIndex = m_listCtrl->InsertItem(0, str0);408        }409    }410411    m_listCtrl->SetItem(nIndex, 1, hashKey.ToString());412    m_listCtrl->SetItem(nIndex, 2, str2);413    m_listCtrl->SetItem(nIndex, 3, str3);414    m_listCtrl->SetItem(nIndex, 4, str4);415    m_listCtrl->SetItem(nIndex, 5, str5);416    m_listCtrl->SetItem(nIndex, 6, str6);417    m_listCtrl->SetItemData(nIndex, nData);418}419420string FormatTxStatus(const CWalletTx& wtx)421{422    // Status423    int nDepth = wtx.GetDepthInMainChain();424    if (!wtx.IsFinal())425        return strprintf("Open for %d blocks", nBestHeight - wtx.nLockTime);426    else if (nDepth < 6)427        return strprintf("%d/unconfirmed", nDepth);428    else429        return strprintf("%d blocks", nDepth);430}431432void CMainFrame::InsertTransaction(const CWalletTx& wtx, bool fNew, int nIndex)433{434    int64 nTime = wtx.nTimeDisplayed = wtx.GetTxTime();435    int64 nCredit = wtx.GetCredit();436    int64 nDebit = wtx.GetDebit();437    int64 nNet = nCredit - nDebit;438    uint256 hash = wtx.GetHash();439    string strStatus = FormatTxStatus(wtx);440    map<string, string> mapValue = wtx.mapValue;441442    // Find the block the tx is in443    CBlockIndex* pindex = NULL;444    map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(wtx.hashBlock);445    if (mi != mapBlockIndex.end())446        pindex = (*mi).second;447448    // Sort order, unrecorded transactions sort to the top449    string strSort = strprintf("%010d-%01d-%010u",450        (pindex ? pindex->nHeight : INT_MAX),451        (wtx.IsCoinBase() ? 1 : 0),452        wtx.nTimeReceived);453454    // Insert line455    if (nNet > 0 || wtx.IsCoinBase())456    {457        //458        // Credit459        //460        string strDescription;461462        if (wtx.IsCoinBase())463        {464            // Coinbase465            strDescription = "Generated";466            if (nCredit == 0)467            {468                int64 nUnmatured = 0;469                foreach(const CTxOut& txout, wtx.vout)470                    nUnmatured += txout.GetCredit();471                if (wtx.IsInMainChain())472                    strDescription += strprintf(" (%s matures in %d blocks)", FormatMoney(nUnmatured).c_str(), wtx.GetBlocksToMaturity());473                else474                    strDescription += " (not accepted)";475            }476        }477        else if (!mapValue["from"].empty() || !mapValue["message"].empty())478        {479            // Online transaction480            if (!mapValue["from"].empty())481                strDescription += "From: " + mapValue["from"];482            if (!mapValue["message"].empty())483            {484                if (!strDescription.empty())485                    strDescription += " - ";486                strDescription += mapValue["message"];487            }488        }489        else490        {491            // Offline transaction492            foreach(const CTxOut& txout, wtx.vout)493            {494                if (txout.IsMine())495                {496                    vector<unsigned char> vchPubKey;497                    if (ExtractPubKey(txout.scriptPubKey, true, vchPubKey))498                    {499                        string strAddress = PubKeyToAddress(vchPubKey);500                        if (mapAddressBook.count(strAddress))501                        {502                            strDescription += "Received with: ";503                            if (!mapAddressBook[strAddress].empty())504                                strDescription += mapAddressBook[strAddress] + " ";505                            strDescription += strAddress;506                        }507                    }508                    break;509                }510            }511        }512513        string strDescription2;514        foreach(int c, strDescription)515            if (c >= ' ')516                strDescription2 += c;517518        InsertLine(fNew, nIndex, hash, strSort,519                   strStatus,520                   nTime ? DateTimeStr(nTime) : "",521                   strDescription2,522                   "",523                   FormatMoney(nNet, true));524    }525    else526    {527        bool fAllFromMe = true;528        foreach(const CTxIn& txin, wtx.vin)529            fAllFromMe = fAllFromMe && txin.IsMine();530531        bool fAllToMe = true;532        foreach(const CTxOut& txout, wtx.vout)533            fAllToMe = fAllToMe && txout.IsMine();534535        if (fAllFromMe && fAllToMe)536        {537            // Payment to self538            int64 nValue = wtx.vout[0].nValue;539            InsertLine(fNew, nIndex, hash, strSort,540                       strStatus,541                       nTime ? DateTimeStr(nTime) : "",542                       "Payment to yourself",543                       FormatMoney(nNet - nValue, true),544                       FormatMoney(nValue, true));545        }546        else if (fAllFromMe)547        {548            //549            // Debit550            //551            int64 nTxFee = nDebit - wtx.GetValueOut();552            for (int nOut = 0; nOut < wtx.vout.size(); nOut++)553            {554                const CTxOut& txout = wtx.vout[nOut];555                if (txout.IsMine())556                    continue;557558                string strAddress;559                if (!mapValue["to"].empty())560                {561                    // Online transaction562                    strAddress = mapValue["to"];563                }564                else565                {566                    // Offline transaction567                    uint160 hash160;568                    if (ExtractHash160(txout.scriptPubKey, hash160))569                        strAddress = Hash160ToAddress(hash160);570                }571572                string strDescription = "To: ";573                if (mapAddressBook.count(strAddress) && !mapAddressBook[strAddress].empty())574                    strDescription += mapAddressBook[strAddress] + " ";575                strDescription += strAddress;576                if (!mapValue["message"].empty())577                {578                    if (!strDescription.empty())579                        strDescription += " - ";580                    strDescription += mapValue["message"];581                }582583                string strDescription2;584                foreach(int c, strDescription)585                    if (c >= ' ')586                        strDescription2 += c;587588                int64 nValue = txout.nValue;589                if (nOut == 0 && nTxFee > 0)590                    nValue += nTxFee;591592                InsertLine(fNew, nIndex, hash, strprintf("%s-%d", strSort.c_str(), nOut),593                           strStatus,594                           nTime ? DateTimeStr(nTime) : "",595                           strDescription2,596                           FormatMoney(-nValue, true),597                           "");598            }599        }600        else601        {602            //603            // Mixed debit transaction, can't break down payees604            //605            bool fAllMine = true;606            foreach(const CTxOut& txout, wtx.vout)607                fAllMine = fAllMine && txout.IsMine();608            foreach(const CTxIn& txin, wtx.vin)609                fAllMine = fAllMine && txin.IsMine();610611            InsertLine(fNew, nIndex, hash, strSort,612                       strStatus,613                       nTime ? DateTimeStr(nTime) : "",614                       "",615                       FormatMoney(nNet, true),616                       "");617        }618    }619}620621void CMainFrame::RefreshStatus()622{623    static int nLastTop;624    int nTop = m_listCtrl->GetTopItem();625    if (nTop == nLastTop && pindexBestLast == pindexBest)626        return;627628    TRY_CRITICAL_BLOCK(cs_mapWallet)629    {630        int nStart = nTop;631        int nEnd = min(nStart + 100, m_listCtrl->GetItemCount());632        if (pindexBestLast == pindexBest)633        {634            if (nStart >= nLastTop && nStart < nLastTop + 100)635                nStart = nLastTop + 100;636            if (nEnd >= nLastTop && nEnd < nLastTop + 100)637                nEnd = nLastTop;638        }639        nLastTop = nTop;640        pindexBestLast = pindexBest;641642        for (int nIndex = nStart; nIndex < nEnd; nIndex++)643        {644            uint256 hash((string)GetItemText(m_listCtrl, nIndex, 1));645            map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash);646            if (mi == mapWallet.end())647            {648                printf("CMainFrame::RefreshStatus() : tx not found in mapWallet\n");649                continue;650            }651            const CWalletTx& wtx = (*mi).second;652            if (wtx.IsCoinBase() || wtx.GetTxTime() != wtx.nTimeDisplayed)653                InsertTransaction(wtx, false, nIndex);654            else655                m_listCtrl->SetItem(nIndex, 2, FormatTxStatus(wtx));656        }657    }658}659660void CMainFrame::RefreshListCtrl()661{662    fRefreshListCtrl = true;663    ::wxWakeUpIdle();664}665666void CMainFrame::OnIdle(wxIdleEvent& event)667{668    if (fRefreshListCtrl)669    {670        // Collect list of wallet transactions and sort newest first671        bool fEntered = false;672        vector<pair<unsigned int, uint256> > vSorted;673        TRY_CRITICAL_BLOCK(cs_mapWallet)674        {675            printf("RefreshListCtrl starting\n");676            fEntered = true;677            fRefreshListCtrl = false;678            vWalletUpdated.clear();679680            // Do the newest transactions first681            vSorted.reserve(mapWallet.size());682            for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)683            {684                const CWalletTx& wtx = (*it).second;685                unsigned int nTime = UINT_MAX - wtx.GetTxTime();686                vSorted.push_back(make_pair(nTime, (*it).first));687            }688            m_listCtrl->DeleteAllItems();689        }690        if (!fEntered)691            return;692693        sort(vSorted.begin(), vSorted.end());694695        // Fill list control696        for (int i = 0; i < vSorted.size();)697        {698            if (fShutdown)699                return;700            bool fEntered = false;701            TRY_CRITICAL_BLOCK(cs_mapWallet)702            {703                fEntered = true;704                uint256& hash = vSorted[i++].second;705                map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash);706                if (mi != mapWallet.end())707                    InsertTransaction((*mi).second, true);708            }709            if (!fEntered || i == 100 || i % 500 == 0)710                wxYield();711        }712713        printf("RefreshListCtrl done\n");714    }715    else716    {717        // Check for time updates718        static int64 nLastTime;719        if (GetTime() > nLastTime + 30)720        {721            TRY_CRITICAL_BLOCK(cs_mapWallet)722            {723                nLastTime = GetTime();724                for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)725                {726                    CWalletTx& wtx = (*it).second;727                    if (wtx.nTimeDisplayed && wtx.nTimeDisplayed != wtx.GetTxTime())728                        InsertTransaction(wtx, false);729                }730            }731        }732    }733}734735void CMainFrame::OnPaint(wxPaintEvent& event)736{737    event.Skip();738}739740void CMainFrame::OnPaintListCtrl(wxPaintEvent& event)741{742    // Update listctrl contents743    if (!vWalletUpdated.empty())744    {745        TRY_CRITICAL_BLOCK(cs_mapWallet)746        {747            pair<uint256, bool> item;748            foreach(item, vWalletUpdated)749            {750                bool fNew = item.second;751                map<uint256, CWalletTx>::iterator mi = mapWallet.find(item.first);752                if (mi != mapWallet.end())753                {754                    printf("vWalletUpdated: %s %s\n", (*mi).second.GetHash().ToString().substr(0,6).c_str(), fNew ? "new" : "");755                    InsertTransaction((*mi).second, fNew);756                }757            }758            m_listCtrl->ScrollList(0, INT_MAX);759            vWalletUpdated.clear();760        }761    }762763    // Update status column of visible items only764    RefreshStatus();765766    // Update status bar767    string strGen = "";768    if (fGenerateBitcoins)769        strGen = "    Generating";770    if (fGenerateBitcoins && vNodes.empty())771        strGen = "(not connected)";772    m_statusBar->SetStatusText(strGen, 1);773774    string strStatus = strprintf("     %d connections     %d blocks     %d transactions", vNodes.size(), nBestHeight + 1, m_listCtrl->GetItemCount());775    m_statusBar->SetStatusText(strStatus, 2);776777    // Balance total778    TRY_CRITICAL_BLOCK(cs_mapWallet)779        m_staticTextBalance->SetLabel(FormatMoney(GetBalance()) + "  ");780781    m_listCtrl->OnPaint(event);782}783784void CrossThreadCall(wxCommandEvent& event)785{786    if (pframeMain)787        pframeMain->GetEventHandler()->AddPendingEvent(event);788}789790void CrossThreadCall(int nID, void* pdata)791{792    wxCommandEvent event;793    event.SetInt(nID);794    event.SetClientData(pdata);795    if (pframeMain)796        pframeMain->GetEventHandler()->AddPendingEvent(event);797}798799void CMainFrame::OnCrossThreadCall(wxCommandEvent& event)800{801    void* pdata = event.GetClientData();802    switch (event.GetInt())803    {804        case UICALL_ADDORDER:805        {806            break;807        }808809        case UICALL_UPDATEORDER:810        {811            break;812        }813    }814}815816void CMainFrame::OnMenuFileExit(wxCommandEvent& event)817{818    Close(true);819}820821void CMainFrame::OnMenuOptionsGenerate(wxCommandEvent& event)822{823    fGenerateBitcoins = event.IsChecked();824    nTransactionsUpdated++;825    CWalletDB().WriteSetting("fGenerateBitcoins", fGenerateBitcoins);826827    if (fGenerateBitcoins)828        if (_beginthread(ThreadBitcoinMiner, 0, NULL) == -1)829            printf("Error: _beginthread(ThreadBitcoinMiner) failed\n");830831    Refresh();832    wxPaintEvent eventPaint;833    AddPendingEvent(eventPaint);834}835836void CMainFrame::OnMenuOptionsOptions(wxCommandEvent& event)837{838    COptionsDialog dialog(this);839    dialog.ShowModal();840}841842void CMainFrame::OnMenuHelpAbout(wxCommandEvent& event)843{844    CAboutDialog dialog(this);845    dialog.ShowModal();846}847848void CMainFrame::OnButtonSend(wxCommandEvent& event)849{850    /// debug test851    if (fRandSendTest)852    {853        RandSend();854        return;855    }856857    // Toolbar: Send858    CSendDialog dialog(this);859    dialog.ShowModal();860}861862void CMainFrame::OnButtonAddressBook(wxCommandEvent& event)863{864    // Toolbar: Address Book865    CAddressBookDialog dialogAddr(this, "", false);866    if (dialogAddr.ShowModal() == 2)867    {868        // Send869        CSendDialog dialogSend(this, dialogAddr.GetAddress());870        dialogSend.ShowModal();871    }872}873874void CMainFrame::OnSetFocusAddress(wxFocusEvent& event)875{876    // Automatically select-all when entering window877    m_textCtrlAddress->SetSelection(-1, -1);878    fOnSetFocusAddress = true;879    event.Skip();880}881882void CMainFrame::OnMouseEventsAddress(wxMouseEvent& event)883{884    if (fOnSetFocusAddress)885        m_textCtrlAddress->SetSelection(-1, -1);886    fOnSetFocusAddress = false;887    event.Skip();888}889890void CMainFrame::OnButtonCopy(wxCommandEvent& event)891{892    // Copy address box to clipboard893    if (wxTheClipboard->Open())894    {895        wxTheClipboard->SetData(new wxTextDataObject(m_textCtrlAddress->GetValue()));896        wxTheClipboard->Close();897    }898}899900void CMainFrame::OnButtonChange(wxCommandEvent& event)901{902    CYourAddressDialog dialog(this, string(m_textCtrlAddress->GetValue()));903    if (!dialog.ShowModal())904        return;905    string strAddress = (string)dialog.GetAddress();906    if (strAddress != m_textCtrlAddress->GetValue())907    {908        uint160 hash160;909        if (!AddressToHash160(strAddress, hash160))910            return;911        if (!mapPubKeys.count(hash160))912            return;913        CWalletDB().WriteDefaultKey(mapPubKeys[hash160]);914        m_textCtrlAddress->SetValue(strAddress);915    }916}917918void CMainFrame::OnListItemActivatedAllTransactions(wxListEvent& event)919{920    uint256 hash((string)GetItemText(m_listCtrl, event.GetIndex(), 1));921    CWalletTx wtx;922    CRITICAL_BLOCK(cs_mapWallet)923    {924        map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash);925        if (mi == mapWallet.end())926        {927            printf("CMainFrame::OnListItemActivatedAllTransactions() : tx not found in mapWallet\n");928            return;929        }930        wtx = (*mi).second;931    }932    CTxDetailsDialog dialog(this, wtx);933    dialog.ShowModal();934    //CTxDetailsDialog* pdialog = new CTxDetailsDialog(this, wtx);935    //pdialog->Show();936}937938void CMainFrame::OnListItemActivatedProductsSent(wxListEvent& event)939{940    CProduct& product = *(CProduct*)event.GetItem().GetData();941    CEditProductDialog* pdialog = new CEditProductDialog(this);942    pdialog->SetProduct(product);943    pdialog->Show();944}945946void CMainFrame::OnListItemActivatedOrdersSent(wxListEvent& event)947{948    CWalletTx& order = *(CWalletTx*)event.GetItem().GetData();949    CViewOrderDialog* pdialog = new CViewOrderDialog(this, order, false);950    pdialog->Show();951}952953void CMainFrame::OnListItemActivatedOrdersReceived(wxListEvent& event)954{955    CWalletTx& order = *(CWalletTx*)event.GetItem().GetData();956    CViewOrderDialog* pdialog = new CViewOrderDialog(this, order, true);957    pdialog->Show();958}959960961962963964965966//////////////////////////////////////////////////////////////////////////////967//968// CTxDetailsDialog969//970971CTxDetailsDialog::CTxDetailsDialog(wxWindow* parent, CWalletTx wtx) : CTxDetailsDialogBase(parent)972{973    string strHTML;974    strHTML.reserve(4000);975976    int64 nTime = wtx.GetTxTime();977    int64 nCredit = wtx.GetCredit();978    int64 nDebit = wtx.GetDebit();979    int64 nNet = nCredit - nDebit;980981982983984    strHTML += "<b>Status:</b> " + FormatTxStatus(wtx) + "<br>";985    strHTML += "<b>Date:</b> " + (nTime ? DateTimeStr(nTime) : "") + "<br>";986987988    //989    // From990    //991    if (wtx.IsCoinBase())992    {993        strHTML += "<b>Source:</b> Generated<br>";994    }995    else if (!wtx.mapValue["from"].empty())996    {997        // Online transaction998        if (!wtx.mapValue["from"].empty())999            strHTML += "<b>From:</b> " + HtmlEscape(wtx.mapValue["from"]) + "<br>";1000    }1001    else1002    {1003        // Offline transaction1004        foreach(const CTxOut& txout, wtx.vout)1005        {1006            if (txout.IsMine())1007            {1008                vector<unsigned char> vchPubKey;1009                if (ExtractPubKey(txout.scriptPubKey, true, vchPubKey))1010                {1011                    string strAddress = PubKeyToAddress(vchPubKey);1012                    if (mapAddressBook.count(strAddress))1013                    {1014                        strHTML += "<b>Received with:</b> ";1015                        if (!mapAddressBook[strAddress].empty())1016                            strHTML += mapAddressBook[strAddress] + " ";1017                        strHTML += HtmlEscape(strAddress);1018                        strHTML += "<br>";1019                    }1020                }1021                break;1022            }1023        }1024    }102510261027    //1028    // To1029    //1030    string strAddress;1031    if (!wtx.mapValue["to"].empty())1032    {1033        // Online transaction1034        strAddress = wtx.mapValue["to"];1035        strHTML += "<b>To:</b> ";1036        if (mapAddressBook.count(strAddress) && !mapAddressBook[strAddress].empty())1037            strHTML += mapAddressBook[strAddress] + " ";1038        strHTML += HtmlEscape(strAddress) + "<br>";1039    }104010411042    //1043    // Amount1044    //1045    if (wtx.IsCoinBase() && nCredit == 0)1046    {1047        //1048        // Coinbase1049        //1050        int64 nUnmatured = 0;1051        foreach(const CTxOut& txout, wtx.vout)1052            nUnmatured += txout.GetCredit();1053        if (wtx.IsInMainChain())1054            strHTML += strprintf("<b>Credit:</b> (%s matures in %d blocks)<br>", FormatMoney(nUnmatured).c_str(), wtx.GetBlocksToMaturity());1055        else1056            strHTML += "<b>Credit:</b> (not accepted)<br>";1057    }1058    else if (nNet > 0)1059    {1060        //1061        // Credit1062        //1063        strHTML += "<b>Credit:</b> " + FormatMoney(nNet) + "<br>";1064    }1065    else1066    {1067        bool fAllFromMe = true;1068        foreach(const CTxIn& txin, wtx.vin)1069            fAllFromMe = fAllFromMe && txin.IsMine();10701071        bool fAllToMe = true;1072        foreach(const CTxOut& txout, wtx.vout)1073            fAllToMe = fAllToMe && txout.IsMine();10741075        if (fAllFromMe)1076        {1077            //1078            // Debit1079            //1080            foreach(const CTxOut& txout, wtx.vout)1081            {1082                if (txout.IsMine())1083                    continue;10841085                string strAddress;1086                if (!wtx.mapValue["to"].empty())1087                {1088                    // Online transaction1089                    strAddress = wtx.mapValue["to"];1090                }1091                else1092                {1093                    // Offline transaction1094                    uint160 hash160;1095                    if (ExtractHash160(txout.scriptPubKey, hash160))1096                        strAddress = Hash160ToAddress(hash160);1097                }10981099                strHTML += "<b>Debit:</b> " + FormatMoney(-txout.nValue) + " &nbsp;&nbsp; ";1100                strHTML += "(to ";1101                if (mapAddressBook.count(strAddress) && !mapAddressBook[strAddress].empty())1102                    strHTML += mapAddressBook[strAddress] + " ";1103                strHTML += strAddress;1104                strHTML += ")<br>";1105            }11061107            if (fAllToMe)1108            {1109                // Payment to self1110                int64 nValue = wtx.vout[0].nValue;1111                strHTML += "<b>Debit:</b> " + FormatMoney(-nValue) + "<br>";1112                strHTML += "<b>Credit:</b> " + FormatMoney(nValue) + "<br>";1113            }11141115            int64 nTxFee = nDebit - wtx.GetValueOut();1116            if (nTxFee > 0)1117                strHTML += "<b>Transaction fee:</b> " + FormatMoney(-nTxFee) + "<br>";1118        }1119        else1120        {1121            //1122            // Mixed debit transaction1123            //1124            foreach(const CTxIn& txin, wtx.vin)1125                if (txin.IsMine())1126                    strHTML += "<b>Debit:</b> " + FormatMoney(-txin.GetDebit()) + "<br>";1127            foreach(const CTxOut& txout, wtx.vout)1128                if (txout.IsMine())1129                    strHTML += "<b>Credit:</b> " + FormatMoney(txout.GetCredit()) + "<br>";1130        }1131    }11321133    strHTML += "<b>Net amount:</b> " + FormatMoney(nNet, true) + "<br>";113411351136    //1137    // Message1138    //1139    if (!wtx.mapValue["message"].empty())1140        strHTML += "<br><b>Message:</b><br>" + HtmlEscape(wtx.mapValue["message"], true) + "<br>";114111421143    //1144    // Debug view1145    //1146    if (fDebug)1147    {1148        strHTML += "<hr><br>debug print<br><br>";1149        foreach(const CTxIn& txin, wtx.vin)1150            if (txin.IsMine())1151                strHTML += "<b>Debit:</b> " + FormatMoney(-txin.GetDebit()) + "<br>";1152        foreach(const CTxOut& txout, wtx.vout)1153            if (txout.IsMine())1154                strHTML += "<b>Credit:</b> " + FormatMoney(txout.GetCredit()) + "<br>";11551156        strHTML += "<b>Inputs:</b><br>";1157        CRITICAL_BLOCK(cs_mapWallet)1158        {1159            foreach(const CTxIn& txin, wtx.vin)1160            {1161                COutPoint prevout = txin.prevout;1162                map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);1163                if (mi != mapWallet.end())1164                {1165                    const CWalletTx& prev = (*mi).second;1166                    if (prevout.n < prev.vout.size())1167                    {1168                        strHTML += HtmlEscape(prev.ToString(), true);1169                        strHTML += " &nbsp;&nbsp; " + FormatTxStatus(prev) + ", ";1170                        strHTML = strHTML + "IsMine=" + (prev.vout[prevout.n].IsMine() ? "true" : "false") + "<br>";1171                    }1172                }1173            }1174        }11751176        strHTML += "<br><hr><br><b>Transaction:</b><br>";1177        strHTML += HtmlEscape(wtx.ToString(), true);1178    }117911801181    string(strHTML.begin(), strHTML.end()).swap(strHTML);1182    m_htmlWin->SetPage(strHTML);1183    m_buttonOK->SetFocus();1184}11851186void CTxDetailsDialog::OnButtonOK(wxCommandEvent& event)1187{1188    Close();1189    //Destroy();1190}119111921193119411951196//////////////////////////////////////////////////////////////////////////////1197//1198// COptionsDialog1199//12001201COptionsDialog::COptionsDialog(wxWindow* parent) : COptionsDialogBase(parent)1202{1203    m_textCtrlTransactionFee->SetValue(FormatMoney(nTransactionFee));1204    m_buttonOK->SetFocus();1205}12061207void COptionsDialog::OnKillFocusTransactionFee(wxFocusEvent& event)1208{1209    int64 nTmp = nTransactionFee;1210    ParseMoney(m_textCtrlTransactionFee->GetValue(), nTmp);1211    m_textCtrlTransactionFee->SetValue(FormatMoney(nTmp));1212}12131214void COptionsDialog::OnButtonOK(wxCommandEvent& event)1215{1216    // nTransactionFee1217    int64 nPrevTransactionFee = nTransactionFee;1218    if (ParseMoney(m_textCtrlTransactionFee->GetValue(), nTransactionFee) && nTransactionFee != nPrevTransactionFee)1219        CWalletDB().WriteSetting("nTransactionFee", nTransactionFee);12201221    Close();1222}12231224void COptionsDialog::OnButtonCancel(wxCommandEvent& event)1225{1226    Close();1227}1228122912301231123212331234//////////////////////////////////////////////////////////////////////////////1235//1236// CAboutDialog1237//12381239CAboutDialog::CAboutDialog(wxWindow* parent) : CAboutDialogBase(parent)1240{1241    m_staticTextVersion->SetLabel(strprintf("version 0.%d.%d Alpha", VERSION/100, VERSION%100));12421243    // Workaround until upgrade to wxWidgets supporting UTF-81244    wxString str = m_staticTextMain->GetLabel();1245    if (str.Find('Â') != wxNOT_FOUND)1246        str.Remove(str.Find('Â'), 1);1247    m_staticTextMain->SetLabel(str);1248}12491250void CAboutDialog::OnButtonOK(wxCommandEvent& event)1251{1252    Close();1253}1254125512561257125812591260//////////////////////////////////////////////////////////////////////////////1261//1262// CSendDialog1263//12641265CSendDialog::CSendDialog(wxWindow* parent, const wxString& strAddress) : CSendDialogBase(parent)1266{1267    // Init1268    m_textCtrlAddress->SetValue(strAddress);1269    m_choiceTransferType->SetSelection(0);1270    m_bitmapCheckMark->Show(false);1271    //// todo: should add a display of your balance for convenience12721273    // Set Icon1274    wxBitmap bmpSend(wxT("send16"), wxBITMAP_TYPE_RESOURCE);1275    bmpSend.SetMask(new wxMask(wxBitmap(wxT("send16masknoshadow"), wxBITMAP_TYPE_RESOURCE)));1276    wxIcon iconSend;1277    iconSend.CopyFromBitmap(bmpSend);1278    SetIcon(iconSend);12791280    wxCommandEvent event;1281    OnTextAddress(event);12821283    // Fixup the tab order1284    m_buttonPaste->MoveAfterInTabOrder(m_buttonCancel);1285    m_buttonAddress->MoveAfterInTabOrder(m_buttonPaste);1286    this->Layout();1287}12881289void CSendDialog::OnTextAddress(wxCommandEvent& event)1290{1291    // Check mark1292    bool fBitcoinAddress = IsValidBitcoinAddress(m_textCtrlAddress->GetValue());1293    m_bitmapCheckMark->Show(fBitcoinAddress);12941295    // Grey out message if bitcoin address1296    bool fEnable = !fBitcoinAddress;1297    m_staticTextFrom->Enable(fEnable);1298    m_textCtrlFrom->Enable(fEnable);1299    m_staticTextMessage->Enable(fEnable);1300    m_textCtrlMessage->Enable(fEnable);1301    m_textCtrlMessage->SetBackgroundColour(wxSystemSettings::GetColour(fEnable ? wxSYS_COLOUR_WINDOW : wxSYS_COLOUR_BTNFACE));1302}13031304void CSendDialog::OnKillFocusAmount(wxFocusEvent& event)1305{1306    // Reformat the amount1307    if (m_textCtrlAmount->GetValue().Trim().empty())1308        return;1309    int64 nTmp;1310    if (ParseMoney(m_textCtrlAmount->GetValue(), nTmp))1311        m_textCtrlAmount->SetValue(FormatMoney(nTmp));1312}13131314void CSendDialog::OnButtonAddressBook(wxCommandEvent& event)1315{1316    // Open address book1317    CAddressBookDialog dialog(this, m_textCtrlAddress->GetValue(), true);1318    if (dialog.ShowModal())1319        m_textCtrlAddress->SetValue(dialog.GetAddress());1320}13211322void CSendDialog::OnButtonPaste(wxCommandEvent& event)1323{1324    // Copy clipboard to address box1325    if (wxTheClipboard->Open())1326    {1327        if (wxTheClipboard->IsSupported(wxDF_TEXT))1328        {1329            wxTextDataObject data;1330            wxTheClipboard->GetData(data);1331            m_textCtrlAddress->SetValue(data.GetText());1332        }1333        wxTheClipboard->Close();1334    }1335}13361337void CSendDialog::OnButtonSend(wxCommandEvent& event)1338{1339    CWalletTx wtx;1340    string strAddress = (string)m_textCtrlAddress->GetValue();13411342    // Parse amount1343    int64 nValue = 0;1344    if (!ParseMoney(m_textCtrlAmount->GetValue(), nValue) || nValue <= 0)1345    {1346        wxMessageBox("Error in amount ");1347        return;1348    }1349    if (nValue > GetBalance())1350    {1351        wxMessageBox("Amount exceeds your balance ");1352        return;1353    }1354    if (nValue + nTransactionFee > GetBalance())1355    {1356        wxMessageBox(string("Total exceeds your balance when the ") + FormatMoney(nTransactionFee) + " transaction fee is included ");1357        return;1358    }13591360    // Parse bitcoin address1361    uint160 hash160;1362    bool fBitcoinAddress = AddressToHash160(strAddress, hash160);13631364    if (fBitcoinAddress)1365    {1366        // Send to bitcoin address1367        CScript scriptPubKey;1368        scriptPubKey << OP_DUP << OP_HASH160 << hash160 << OP_EQUALVERIFY << OP_CHECKSIG;13691370        if (!SendMoney(scriptPubKey, nValue, wtx))1371            return;13721373        wxMessageBox("Payment sent ", "Sending...");1374    }1375    else1376    {1377        // Parse IP address1378        CAddress addr(strAddress.c_str());1379        if (addr.ip == 0)1380        {1381            wxMessageBox("Invalid address ");1382            return;1383        }13841385        // Message1386        wtx.mapValue["to"] = strAddress;1387        wtx.mapValue["from"] = m_textCtrlFrom->GetValue();1388        wtx.mapValue["message"] = m_textCtrlMessage->GetValue();13891390        // Send to IP address1391        CSendingDialog* pdialog = new CSendingDialog(this, addr, nValue, wtx);1392        if (!pdialog->ShowModal())1393            return;1394    }13951396    if (!mapAddressBook.count(strAddress))1397        SetAddressBookName(strAddress, "");13981399    EndModal(true);1400}14011402void CSendDialog::OnButtonCancel(wxCommandEvent& event)1403{1404    // Cancel1405    EndModal(false);1406}1407140814091410141114121413//////////////////////////////////////////////////////////////////////////////1414//1415// CSendingDialog1416//14171418CSendingDialog::CSendingDialog(wxWindow* parent, const CAddress& addrIn, int64 nPriceIn, const CWalletTx& wtxIn) : CSendingDialogBase(NULL) // we have to give null so parent can't destroy us1419{1420    addr = addrIn;1421    nPrice = nPriceIn;1422    wtx = wtxIn;1423    start = wxDateTime::UNow();1424    strStatus = "";1425    fCanCancel = true;1426    fAbort = false;1427    fSuccess = false;1428    fUIDone = false;1429    fWorkDone = false;14301431    SetTitle(strprintf("Sending %s to %s...", FormatMoney(nPrice).c_str(), wtx.mapValue["to"].c_str()));1432    m_textCtrlStatus->SetValue("");14331434    _beginthread(SendingDialogStartTransfer, 0, this);1435}14361437CSendingDialog::~CSendingDialog()1438{1439    printf("~CSendingDialog()\n");1440}14411442void CSendingDialog::Close()1443{1444    // Last one out turn out the lights.1445    // fWorkDone signals that work side is done and UI thread should call destroy.1446    // fUIDone signals that UI window has closed and work thread should call destroy.1447    // This allows the window to disappear and end modality when cancelled1448    // without making the user wait for ConnectNode to return.  The dialog object1449    // hangs around in the background until the work thread exits.1450    if (IsModal())1451        EndModal(fSuccess);1452    else1453        Show(false);1454    if (fWorkDone)1455        Destroy();1456    else1457        fUIDone = true;1458}14591460void CSendingDialog::OnClose(wxCloseEvent& event)1461{1462    if (!event.CanVeto() || fWorkDone || fAbort || !fCanCancel)1463    {1464        Close();1465    }1466    else1467    {1468        event.Veto();1469        wxCommandEvent cmdevent;1470        OnButtonCancel(cmdevent);1471    }1472}14731474void CSendingDialog::OnButtonOK(wxCommandEvent& event)1475{1476    if (fWorkDone)1477        Close();1478}14791480void CSendingDialog::OnButtonCancel(wxCommandEvent& event)1481{1482    if (fCanCancel)1483        fAbort = true;1484}14851486void CSendingDialog::OnPaint(wxPaintEvent& event)1487{1488    if (strStatus.size() > 130)1489        m_textCtrlStatus->SetValue(string("\n") + strStatus);1490    else1491        m_textCtrlStatus->SetValue(string("\n\n") + strStatus);1492    m_staticTextSending->SetFocus();1493    if (!fCanCancel)1494        m_buttonCancel->Enable(false);1495    if (fWorkDone)1496    {1497        m_buttonOK->Enable(true);1498        m_buttonOK->SetFocus();1499        m_buttonCancel->Enable(false);1500    }1501    if (fAbort && fCanCancel && IsShown())1502    {1503        strStatus = "CANCELLED";1504        m_buttonOK->Enable(true);1505        m_buttonOK->SetFocus();1506        m_buttonCancel->Enable(false);1507        m_buttonCancel->SetLabel("Cancelled");1508        Close();1509        wxMessageBox("Transfer cancelled ", "Sending...", wxOK, this);1510    }1511    event.Skip();15121513    /// debug test1514    if (fRandSendTest && fWorkDone && fSuccess)1515    {1516        Close();1517        Sleep(1000);1518        RandSend();1519    }1520}152115221523//1524// Everything from here on is not in the UI thread and must only communicate1525// with the rest of the dialog through variables and calling repaint.1526//15271528void CSendingDialog::Repaint()1529{1530    Refresh();1531    wxPaintEvent event;1532    AddPendingEvent(event);1533}15341535bool CSendingDialog::Status()1536{1537    if (fUIDone)1538    {1539        Destroy();1540        return false;1541    }1542    if (fAbort && fCanCancel)1543    {1544        strStatus = "CANCELLED";1545        Repaint();1546        fWorkDone = true;1547        return false;1548    }1549    return true;1550}15511552bool CSendingDialog::Status(const string& str)1553{1554    if (!Status())1555        return false;1556    strStatus = str;1557    Repaint();1558    return true;1559}15601561bool CSendingDialog::Error(const string& str)1562{1563    fCanCancel = false;1564    fWorkDone = true;1565    Status(string("Error: ") + str);1566    return false;1567}15681569void SendingDialogStartTransfer(void* parg)1570{1571    ((CSendingDialog*)parg)->StartTransfer();1572}15731574void CSendingDialog::StartTransfer()1575{1576    // Make sure we have enough money1577    if (nPrice + nTransactionFee > GetBalance())1578    {1579        Error("You don't have enough money");1580        return;1581    }15821583    // We may have connected already for product details1584    if (!Status("Connecting..."))1585        return;1586    CNode* pnode = ConnectNode(addr, 5 * 60);1587    if (!pnode)1588    {1589        Error("Unable to connect");1590        return;1591    }15921593    // Send order to seller, with response going to OnReply2 via event handler1594    if (!Status("Requesting public key..."))1595        return;1596    pnode->PushRequest("checkorder", wtx, SendingDialogOnReply2, this);1597}15981599void SendingDialogOnReply2(void* parg, CDataStream& vRecv)1600{1601    ((CSendingDialog*)parg)->OnReply2(vRecv);1602}16031604void CSendingDialog::OnReply2(CDataStream& vRecv)1605{1606    if (!Status("Received public key..."))1607        return;16081609    CScript scriptPubKey;1610    int nRet;1611    try1612    {1613        vRecv >> nRet;1614        if (nRet > 0)1615        {1616            string strMessage;1617            vRecv >> strMessage;1618            Error("Transfer was not accepted");1619            //// todo: enlarge the window and enable a hidden white box to put seller's message1620            return;1621        }1622        vRecv >> scriptPubKey;1623    }1624    catch (...)1625    {1626        //// what do we want to do about this?1627        Error("Invalid response received");1628        return;1629    }16301631    // Should already be connected1632    CNode* pnode = ConnectNode(addr, 5 * 60);1633    if (!pnode)1634    {1635        Error("Lost connection");1636        return;1637    }16381639    // Pause to give the user a chance to cancel1640    while (wxDateTime::UNow() < start + wxTimeSpan(0, 0, 0, 2 * 1000))1641    {1642        Sleep(200);1643        if (!Status())1644            return;1645    }16461647    CRITICAL_BLOCK(cs_main)1648    {1649        // Pay1650        if (!Status("Creating transaction..."))1651            return;1652        if (nPrice + nTransactionFee > GetBalance())1653        {1654            Error("You don't have enough money");1655            return;1656        }1657        int64 nFeeRequired;1658        if (!CreateTransaction(scriptPubKey, nPrice, wtx, nFeeRequired))1659        {1660            if (nPrice + nFeeRequired > GetBalance())1661                Error(strprintf("This is an oversized transaction that requires a transaction fee of %s", FormatMoney(nFeeRequired).c_str()));1662            else1663                Error("Transaction creation failed");1664            return;1665        }16661667        // Last chance to cancel1668        Sleep(50);1669        if (!Status())1670            return;1671        fCanCancel = false;1672        if (fAbort)1673        {1674            fCanCancel = true;1675            if (!Status())1676                return;1677            fCanCancel = false;1678        }1679        if (!Status("Sending payment..."))1680            return;16811682        // Commit1683        if (!CommitTransactionSpent(wtx))1684        {1685            Error("Error finalizing payment");1686            return;1687        }16881689        // Send payment tx to seller, with response going to OnReply3 via event handler1690        pnode->PushRequest("submitorder", wtx, SendingDialogOnReply3, this);16911692        // Accept and broadcast transaction1693        if (!wtx.AcceptTransaction())1694            printf("ERROR: CSendingDialog : wtxNew.AcceptTransaction() %s failed\n", wtx.GetHash().ToString().c_str());1695        wtx.RelayWalletTransaction();16961697        Status("Waiting for confirmation...");1698        MainFrameRepaint();1699    }1700}17011702void SendingDialogOnReply3(void* parg, CDataStream& vRecv)1703{1704    ((CSendingDialog*)parg)->OnReply3(vRecv);1705}17061707void CSendingDialog::OnReply3(CDataStream& vRecv)1708{1709    int nRet;1710    try1711    {1712        vRecv >> nRet;1713        if (nRet > 0)1714        {1715            Error("The payment was sent, but the recipient was unable to verify it.\n"1716                  "The transaction is recorded and will credit to the recipient if it is valid,\n"1717                  "but without comment information.");1718            return;1719        }1720    }1721    catch (...)1722    {1723        //// what do we want to do about this?1724        Error("Payment was sent, but an invalid response was received");1725        return;1726    }17271728    fSuccess = true;1729    fWorkDone = true;1730    Status("Payment completed");1731}1732173317341735173617371738//////////////////////////////////////////////////////////////////////////////1739//1740// CYourAddressDialog1741//17421743CYourAddressDialog::CYourAddressDialog(wxWindow* parent, const string& strInitSelected) : CYourAddressDialogBase(parent)1744{1745    // Init column headers1746    m_listCtrl->InsertColumn(0, "Name", wxLIST_FORMAT_LEFT, 200);1747    m_listCtrl->InsertColumn(1, "Bitcoin Address", wxLIST_FORMAT_LEFT, 350);1748    m_listCtrl->SetFocus();17491750    // Fill listctrl with address book data1751    CRITICAL_BLOCK(cs_mapKeys)1752    {1753        foreach(const PAIRTYPE(string, string)& item, mapAddressBook)1754        {1755            string strAddress = item.first;1756            string strName = item.second;1757            uint160 hash160;1758            bool fMine = (AddressToHash160(strAddress, hash160) && mapPubKeys.count(hash160));1759            if (fMine)1760            {1761                int nIndex = InsertLine(m_listCtrl, strName, strAddress);1762                if (strAddress == strInitSelected)1763                    m_listCtrl->SetItemState(nIndex, wxLIST_STATE_SELECTED|wxLIST_STATE_FOCUSED, wxLIST_STATE_SELECTED|wxLIST_STATE_FOCUSED);1764            }1765        }1766    }1767}17681769wxString CYourAddressDialog::GetAddress()1770{1771    int nIndex = GetSelection(m_listCtrl);1772    if (nIndex == -1)1773        return "";1774    return GetItemText(m_listCtrl, nIndex, 1);1775}17761777void CYourAddressDialog::OnListEndLabelEdit(wxListEvent& event)1778{1779    // Update address book with edited name1780    if (event.IsEditCancelled())1781        return;1782    string strAddress = (string)GetItemText(m_listCtrl, event.GetIndex(), 1);1783    SetAddressBookName(strAddress, string(event.GetText()));1784    pframeMain->RefreshListCtrl();1785}17861787void CYourAddressDialog::OnListItemSelected(wxListEvent& event)1788{1789}17901791void CYourAddressDialog::OnListItemActivated(wxListEvent& event)1792{1793    // Doubleclick returns selection1794    EndModal(true);1795}17961797void CYourAddressDialog::OnButtonRename(wxCommandEvent& event)1798{1799    // Ask new name1800    int nIndex = GetSelection(m_listCtrl);1801    if (nIndex == -1)1802        return;1803    string strName = (string)m_listCtrl->GetItemText(nIndex);1804    string strAddress = (string)GetItemText(m_listCtrl, nIndex, 1);1805    CGetTextFromUserDialog dialog(this, "Rename Bitcoin Address", "New Name", strName);1806    if (!dialog.ShowModal())1807        return;1808    strName = dialog.GetValue();18091810    // Change name1811    SetAddressBookName(strAddress, strName);1812    m_listCtrl->SetItemText(nIndex, strName);1813    pframeMain->RefreshListCtrl();1814}18151816void CYourAddressDialog::OnButtonNew(wxCommandEvent& event)1817{1818    // Ask name1819    CGetTextFromUserDialog dialog(this, "New Bitcoin Address", "Name", "");1820    if (!dialog.ShowModal())1821        return;1822    string strName = dialog.GetValue();18231824    // Generate new key1825    string strAddress = PubKeyToAddress(GenerateNewKey());1826    SetAddressBookName(strAddress, strName);18271828    // Add to list and select it1829    int nIndex = InsertLine(m_listCtrl, strName, strAddress);1830    SetSelection(m_listCtrl, nIndex);1831    m_listCtrl->SetFocus();1832}18331834void CYourAddressDialog::OnButtonCopy(wxCommandEvent& event)1835{1836    // Copy address box to clipboard1837    if (wxTheClipboard->Open())1838    {1839        wxTheClipboard->SetData(new wxTextDataObject(GetAddress()));1840        wxTheClipboard->Close();1841    }1842}18431844void CYourAddressDialog::OnButtonOK(wxCommandEvent& event)1845{1846    // OK1847    EndModal(true);1848}18491850void CYourAddressDialog::OnButtonCancel(wxCommandEvent& event)1851{1852    // Cancel1853    EndModal(false);1854}18551856void CYourAddressDialog::OnClose(wxCloseEvent& event)1857{1858    // Close1859    EndModal(false);1860}1861186218631864186518661867//////////////////////////////////////////////////////////////////////////////1868//1869// CAddressBookDialog1870//18711872CAddressBookDialog::CAddressBookDialog(wxWindow* parent, const wxString& strInitSelected, bool fSendingIn) : CAddressBookDialogBase(parent)1873{1874    fSending = fSendingIn;1875    if (!fSending)1876        m_buttonCancel->Show(false);18771878    // Init column headers1879    m_listCtrl->InsertColumn(0, "Name", wxLIST_FORMAT_LEFT, 200);1880    m_listCtrl->InsertColumn(1, "Address", wxLIST_FORMAT_LEFT, 350);1881    m_listCtrl->SetFocus();18821883    // Set Icon1884    wxBitmap bmpAddressBook(wxT("addressbook16"), wxBITMAP_TYPE_RESOURCE);1885    bmpAddressBook.SetMask(new wxMask(wxBitmap(wxT("addressbook16mask"), wxBITMAP_TYPE_RESOURCE)));1886    wxIcon iconAddressBook;1887    iconAddressBook.CopyFromBitmap(bmpAddressBook);1888    SetIcon(iconAddressBook);18891890    // Fill listctrl with address book data1891    CRITICAL_BLOCK(cs_mapKeys)1892    {1893        foreach(const PAIRTYPE(string, string)& item, mapAddressBook)1894        {1895            string strAddress = item.first;1896            string strName = item.second;1897            uint160 hash160;1898            bool fMine = (AddressToHash160(strAddress, hash160) && mapPubKeys.count(hash160));1899            if (!fMine)1900            {1901                int nIndex = InsertLine(m_listCtrl, strName, strAddress);1902                if (strAddress == strInitSelected)1903                    m_listCtrl->SetItemState(nIndex, wxLIST_STATE_SELECTED|wxLIST_STATE_FOCUSED, wxLIST_STATE_SELECTED|wxLIST_STATE_FOCUSED);1904            }1905        }1906    }1907}19081909wxString CAddressBookDialog::GetAddress()1910{1911    int nIndex = GetSelection(m_listCtrl);1912    if (nIndex == -1)1913        return "";1914    return GetItemText(m_listCtrl, nIndex, 1);1915}19161917void CAddressBookDialog::OnListEndLabelEdit(wxListEvent& event)1918{1919    // Update address book with edited name1920    if (event.IsEditCancelled())1921        return;1922    string strAddress = (string)GetItemText(m_listCtrl, event.GetIndex(), 1);1923    SetAddressBookName(strAddress, string(event.GetText()));1924    pframeMain->RefreshListCtrl();1925}19261927void CAddressBookDialog::OnListItemSelected(wxListEvent& event)1928{1929}19301931void CAddressBookDialog::OnListItemActivated(wxListEvent& event)1932{1933    if (fSending)1934    {1935        // Doubleclick returns selection1936        EndModal(GetAddress() != "" ? 2 : 0);1937    }1938    else1939    {1940        // Doubleclick edits item1941        wxCommandEvent event;1942        OnButtonEdit(event);1943    }1944}19451946void CAddressBookDialog::OnButtonEdit(wxCommandEvent& event)1947{1948    // Ask new name1949    int nIndex = GetSelection(m_listCtrl);1950    if (nIndex == -1)1951        return;1952    string strName = (string)m_listCtrl->GetItemText(nIndex);1953    string strAddress = (string)GetItemText(m_listCtrl, nIndex, 1);1954    string strAddressOrg = strAddress;1955    CGetTextFromUserDialog dialog(this, "Edit Address", "Name", strName, "Address", strAddress);1956    if (!dialog.ShowModal())1957        return;1958    strName = dialog.GetValue1();1959    strAddress = dialog.GetValue2();19601961    // Change name1962    if (strAddress != strAddressOrg)1963        CWalletDB().EraseName(strAddressOrg);1964    SetAddressBookName(strAddress, strName);1965    m_listCtrl->SetItem(nIndex, 1, strAddress);1966    m_listCtrl->SetItemText(nIndex, strName);1967    pframeMain->RefreshListCtrl();1968}19691970void CAddressBookDialog::OnButtonNew(wxCommandEvent& event)1971{1972    // Ask name1973    CGetTextFromUserDialog dialog(this, "New Address", "Name", "", "Address", "");1974    if (!dialog.ShowModal())1975        return;1976    string strName = dialog.GetValue1();1977    string strAddress = dialog.GetValue2();19781979    // Add to list and select it1980    SetAddressBookName(strAddress, strName);1981    int nIndex = InsertLine(m_listCtrl, strName, strAddress);1982    SetSelection(m_listCtrl, nIndex);1983    m_listCtrl->SetFocus();1984}19851986void CAddressBookDialog::OnButtonDelete(wxCommandEvent& event)1987{1988    for (int nIndex = m_listCtrl->GetItemCount()-1; nIndex >= 0; nIndex--)1989    {1990        if (m_listCtrl->GetItemState(nIndex, wxLIST_STATE_SELECTED))1991        {1992            string strAddress = (string)GetItemText(m_listCtrl, nIndex, 1);1993            CWalletDB().EraseName(strAddress);1994            m_listCtrl->DeleteItem(nIndex);1995        }1996    }1997    pframeMain->RefreshListCtrl();1998}19992000void CAddressBookDialog::OnButtonCopy(wxCommandEvent& event)2001{2002    // Copy address box to clipboard2003    if (wxTheClipboard->Open())2004    {2005        wxTheClipboard->SetData(new wxTextDataObject(GetAddress()));2006        wxTheClipboard->Close();2007    }2008}20092010void CAddressBookDialog::OnButtonOK(wxCommandEvent& event)2011{2012    // OK2013    EndModal(GetAddress() != "" ? 1 : 0);2014}20152016void CAddressBookDialog::OnButtonCancel(wxCommandEvent& event)2017{2018    // Cancel2019    EndModal(0);2020}20212022void CAddressBookDialog::OnClose(wxCloseEvent& event)2023{2024    // Close2025    EndModal(0);2026}2027202820292030203120322033//////////////////////////////////////////////////////////////////////////////2034//2035// CProductsDialog2036//20372038bool CompareIntStringPairBestFirst(const pair<int, string>& item1, const pair<int, string>& item2)2039{2040    return (item1.first > item2.first);2041}20422043CProductsDialog::CProductsDialog(wxWindow* parent) : CProductsDialogBase(parent)2044{2045    // Init column headers2046    m_listCtrl->InsertColumn(0, "Title",  wxLIST_FORMAT_LEFT, 200);2047    m_listCtrl->InsertColumn(1, "Price",  wxLIST_FORMAT_LEFT, 80);2048    m_listCtrl->InsertColumn(2, "Seller", wxLIST_FORMAT_LEFT, 80);2049    m_listCtrl->InsertColumn(3, "Stars",  wxLIST_FORMAT_LEFT, 50);2050    m_listCtrl->InsertColumn(4, "Power",  wxLIST_FORMAT_LEFT, 50);20512052    // Tally top categories2053    map<string, int> mapTopCategories;2054    CRITICAL_BLOCK(cs_mapProducts)2055        for (map<uint256, CProduct>::iterator mi = mapProducts.begin(); mi != mapProducts.end(); ++mi)2056            mapTopCategories[(*mi).second.mapValue["category"]]++;20572058    // Sort top categories2059    vector<pair<int, string> > vTopCategories;2060    for (map<string, int>::iterator mi = mapTopCategories.begin(); mi != mapTopCategories.end(); ++mi)2061        vTopCategories.push_back(make_pair((*mi).second, (*mi).first));2062    sort(vTopCategories.begin(), vTopCategories.end(), CompareIntStringPairBestFirst);20632064    // Fill categories combo box2065    int nLimit = 250;2066    for (vector<pair<int, string> >::iterator it = vTopCategories.begin(); it != vTopCategories.end() && nLimit-- > 0; ++it)2067        m_comboBoxCategory->Append((*it).second);20682069    // Fill window with initial search2070    //wxCommandEvent event;2071    //OnButtonSearch(event);2072}20732074void CProductsDialog::OnCombobox(wxCommandEvent& event)2075{2076    OnButtonSearch(event);2077}20782079bool CompareProductsBestFirst(const CProduct* p1, const CProduct* p2)2080{2081    return (p1->nAtoms > p2->nAtoms);2082}20832084void CProductsDialog::OnButtonSearch(wxCommandEvent& event)2085{2086    string strCategory = (string)m_comboBoxCategory->GetValue();2087    string strSearch = (string)m_textCtrlSearch->GetValue();20882089    // Search products2090    vector<CProduct*> vProductsFound;2091    CRITICAL_BLOCK(cs_mapProducts)2092    {2093        for (map<uint256, CProduct>::iterator mi = mapProducts.begin(); mi != mapProducts.end(); ++mi)2094        {2095            CProduct& product = (*mi).second;2096            if (product.mapValue["category"].find(strCategory) != -1)2097            {2098                if (product.mapValue["title"].find(strSearch) != -1 ||2099                    product.mapValue["description"].find(strSearch) != -1 ||2100                    product.mapValue["seller"].find(strSearch) != -1)2101                {2102                    vProductsFound.push_back(&product);2103                }2104            }2105        }2106    }21072108    // Sort2109    sort(vProductsFound.begin(), vProductsFound.end(), CompareProductsBestFirst);21102111    // Display2112    foreach(CProduct* pproduct, vProductsFound)2113    {2114        InsertLine(m_listCtrl,2115                   pproduct->mapValue["title"],2116                   pproduct->mapValue["price"],2117                   pproduct->mapValue["seller"],2118                   pproduct->mapValue["stars"],2119                   itostr(pproduct->nAtoms));2120    }2121}21222123void CProductsDialog::OnListItemActivated(wxListEvent& event)2124{2125    // Doubleclick opens product2126    CViewProductDialog* pdialog = new CViewProductDialog(this, m_vProduct[event.GetIndex()]);2127    pdialog->Show();2128}21292130213121322133213421352136//////////////////////////////////////////////////////////////////////////////2137//2138// CEditProductDialog2139//21402141CEditProductDialog::CEditProductDialog(wxWindow* parent) : CEditProductDialogBase(parent)2142{2143    m_textCtrlLabel[0 ] = m_textCtrlLabel0;2144    m_textCtrlLabel[1 ] = m_textCtrlLabel1;2145    m_textCtrlLabel[2 ] = m_textCtrlLabel2;2146    m_textCtrlLabel[3 ] = m_textCtrlLabel3;2147    m_textCtrlLabel[4 ] = m_textCtrlLabel4;2148    m_textCtrlLabel[5 ] = m_textCtrlLabel5;2149    m_textCtrlLabel[6 ] = m_textCtrlLabel6;2150    m_textCtrlLabel[7 ] = m_textCtrlLabel7;2151    m_textCtrlLabel[8 ] = m_textCtrlLabel8;2152    m_textCtrlLabel[9 ] = m_textCtrlLabel9;2153    m_textCtrlLabel[10] = m_textCtrlLabel10;2154    m_textCtrlLabel[11] = m_textCtrlLabel11;2155    m_textCtrlLabel[12] = m_textCtrlLabel12;2156    m_textCtrlLabel[13] = m_textCtrlLabel13;2157    m_textCtrlLabel[14] = m_textCtrlLabel14;2158    m_textCtrlLabel[15] = m_textCtrlLabel15;2159    m_textCtrlLabel[16] = m_textCtrlLabel16;2160    m_textCtrlLabel[17] = m_textCtrlLabel17;2161    m_textCtrlLabel[18] = m_textCtrlLabel18;2162    m_textCtrlLabel[19] = m_textCtrlLabel19;21632164    m_textCtrlField[0 ] = m_textCtrlField0;2165    m_textCtrlField[1 ] = m_textCtrlField1;2166    m_textCtrlField[2 ] = m_textCtrlField2;2167    m_textCtrlField[3 ] = m_textCtrlField3;2168    m_textCtrlField[4 ] = m_textCtrlField4;2169    m_textCtrlField[5 ] = m_textCtrlField5;2170    m_textCtrlField[6 ] = m_textCtrlField6;2171    m_textCtrlField[7 ] = m_textCtrlField7;2172    m_textCtrlField[8 ] = m_textCtrlField8;2173    m_textCtrlField[9 ] = m_textCtrlField9;2174    m_textCtrlField[10] = m_textCtrlField10;2175    m_textCtrlField[11] = m_textCtrlField11;2176    m_textCtrlField[12] = m_textCtrlField12;2177    m_textCtrlField[13] = m_textCtrlField13;2178    m_textCtrlField[14] = m_textCtrlField14;2179    m_textCtrlField[15] = m_textCtrlField15;2180    m_textCtrlField[16] = m_textCtrlField16;2181    m_textCtrlField[17] = m_textCtrlField17;2182    m_textCtrlField[18] = m_textCtrlField18;2183    m_textCtrlField[19] = m_textCtrlField19;21842185    m_buttonDel[0 ] = m_buttonDel0;2186    m_buttonDel[1 ] = m_buttonDel1;2187    m_buttonDel[2 ] = m_buttonDel2;2188    m_buttonDel[3 ] = m_buttonDel3;2189    m_buttonDel[4 ] = m_buttonDel4;2190    m_buttonDel[5 ] = m_buttonDel5;2191    m_buttonDel[6 ] = m_buttonDel6;2192    m_buttonDel[7 ] = m_buttonDel7;2193    m_buttonDel[8 ] = m_buttonDel8;2194    m_buttonDel[9 ] = m_buttonDel9;2195    m_buttonDel[10] = m_buttonDel10;2196    m_buttonDel[11] = m_buttonDel11;2197    m_buttonDel[12] = m_buttonDel12;2198    m_buttonDel[13] = m_buttonDel13;2199    m_buttonDel[14] = m_buttonDel14;2200    m_buttonDel[15] = m_buttonDel15;2201    m_buttonDel[16] = m_buttonDel16;2202    m_buttonDel[17] = m_buttonDel17;2203    m_buttonDel[18] = m_buttonDel18;2204    m_buttonDel[19] = m_buttonDel19;22052206    for (int i = 1; i < FIELDS_MAX; i++)2207        ShowLine(i, false);22082209    LayoutAll();2210}22112212void CEditProductDialog::LayoutAll()2213{2214    m_scrolledWindow->Layout();2215    m_scrolledWindow->GetSizer()->Fit(m_scrolledWindow);2216    this->Layout();2217}22182219void CEditProductDialog::ShowLine(int i, bool fShow)2220{2221    m_textCtrlLabel[i]->Show(fShow);2222    m_textCtrlField[i]->Show(fShow);2223    m_buttonDel[i]->Show(fShow);2224}22252226void CEditProductDialog::OnButtonDel0(wxCommandEvent& event)  { OnButtonDel(event, 0); }2227void CEditProductDialog::OnButtonDel1(wxCommandEvent& event)  { OnButtonDel(event, 1); }2228void CEditProductDialog::OnButtonDel2(wxCommandEvent& event)  { OnButtonDel(event, 2); }2229void CEditProductDialog::OnButtonDel3(wxCommandEvent& event)  { OnButtonDel(event, 3); }2230void CEditProductDialog::OnButtonDel4(wxCommandEvent& event)  { OnButtonDel(event, 4); }2231void CEditProductDialog::OnButtonDel5(wxCommandEvent& event)  { OnButtonDel(event, 5); }2232void CEditProductDialog::OnButtonDel6(wxCommandEvent& event)  { OnButtonDel(event, 6); }2233void CEditProductDialog::OnButtonDel7(wxCommandEvent& event)  { OnButtonDel(event, 7); }2234void CEditProductDialog::OnButtonDel8(wxCommandEvent& event)  { OnButtonDel(event, 8); }2235void CEditProductDialog::OnButtonDel9(wxCommandEvent& event)  { OnButtonDel(event, 9); }2236void CEditProductDialog::OnButtonDel10(wxCommandEvent& event) { OnButtonDel(event, 10); }2237void CEditProductDialog::OnButtonDel11(wxCommandEvent& event) { OnButtonDel(event, 11); }2238void CEditProductDialog::OnButtonDel12(wxCommandEvent& event) { OnButtonDel(event, 12); }2239void CEditProductDialog::OnButtonDel13(wxCommandEvent& event) { OnButtonDel(event, 13); }2240void CEditProductDialog::OnButtonDel14(wxCommandEvent& event) { OnButtonDel(event, 14); }2241void CEditProductDialog::OnButtonDel15(wxCommandEvent& event) { OnButtonDel(event, 15); }2242void CEditProductDialog::OnButtonDel16(wxCommandEvent& event) { OnButtonDel(event, 16); }2243void CEditProductDialog::OnButtonDel17(wxCommandEvent& event) { OnButtonDel(event, 17); }2244void CEditProductDialog::OnButtonDel18(wxCommandEvent& event) { OnButtonDel(event, 18); }2245void CEditProductDialog::OnButtonDel19(wxCommandEvent& event) { OnButtonDel(event, 19); }22462247void CEditProductDialog::OnButtonDel(wxCommandEvent& event, int n)2248{2249    Freeze();2250    int x, y;2251    m_scrolledWindow->GetViewStart(&x, &y);2252    int i;2253    for (i = n; i < FIELDS_MAX-1; i++)2254    {2255        m_textCtrlLabel[i]->SetValue(m_textCtrlLabel[i+1]->GetValue());2256        m_textCtrlField[i]->SetValue(m_textCtrlField[i+1]->GetValue());2257        if (!m_buttonDel[i+1]->IsShown())2258            break;2259    }2260    m_textCtrlLabel[i]->SetValue("");2261    m_textCtrlField[i]->SetValue("");2262    ShowLine(i, false);2263    m_buttonAddField->Enable(true);2264    LayoutAll();2265    m_scrolledWindow->Scroll(0, y);2266    Thaw();2267}22682269void CEditProductDialog::OnButtonAddField(wxCommandEvent& event)2270{2271    for (int i = 0; i < FIELDS_MAX; i++)2272    {2273        if (!m_buttonDel[i]->IsShown())2274        {2275            Freeze();2276            ShowLine(i, true);2277            if (i == FIELDS_MAX-1)2278                m_buttonAddField->Enable(false);2279            LayoutAll();2280            m_scrolledWindow->Scroll(0, 99999);2281            Thaw();2282            break;2283        }2284    }2285}22862287void CEditProductDialog::OnButtonSend(wxCommandEvent& event)2288{2289    CProduct product;2290    GetProduct(product);22912292    // Sign the detailed product2293    product.vchPubKeyFrom = keyUser.GetPubKey();2294    if (!keyUser.Sign(product.GetSigHash(), product.vchSig))2295    {2296        wxMessageBox("Error digitally signing the product ");2297        return;2298    }22992300    // Save detailed product2301    AddToMyProducts(product);23022303    // Strip down to summary product2304    product.mapDetails.clear();2305    product.vOrderForm.clear();23062307    // Sign the summary product2308    if (!keyUser.Sign(product.GetSigHash(), product.vchSig))2309    {2310        wxMessageBox("Error digitally signing the product ");2311        return;2312    }23132314    // Verify2315    if (!product.CheckProduct())2316    {2317        wxMessageBox("Errors found in product ");2318        return;2319    }23202321    // Broadcast2322    AdvertStartPublish(pnodeLocalHost, MSG_PRODUCT, 0, product);23232324    Destroy();2325}23262327void CEditProductDialog::OnButtonPreview(wxCommandEvent& event)2328{2329    CProduct product;2330    GetProduct(product);2331    CViewProductDialog* pdialog = new CViewProductDialog(this, product);2332    pdialog->Show();2333}23342335void CEditProductDialog::OnButtonCancel(wxCommandEvent& event)2336{2337    Destroy();2338}23392340void CEditProductDialog::SetProduct(const CProduct& productIn)2341{2342    CProduct product = productIn;23432344    m_comboBoxCategory->SetValue(product.mapValue["category"]);2345    m_textCtrlTitle->SetValue(product.mapValue["title"]);2346    m_textCtrlPrice->SetValue(product.mapValue["price"]);2347    m_textCtrlDescription->SetValue(product.mapValue["description"]);2348    m_textCtrlInstructions->SetValue(product.mapValue["instructions"]);23492350    for (int i = 0; i < FIELDS_MAX; i++)2351    {2352        bool fUsed = i < product.vOrderForm.size();2353        m_buttonDel[i]->Show(fUsed);2354        m_textCtrlLabel[i]->Show(fUsed);2355        m_textCtrlField[i]->Show(fUsed);2356        if (!fUsed)2357            continue;23582359        m_textCtrlLabel[i]->SetValue(product.vOrderForm[i].first);2360        string strControl = product.vOrderForm[i].second;2361        if (strControl.substr(0, 5) == "text=")2362            m_textCtrlField[i]->SetValue("");2363        else if (strControl.substr(0, 7) == "choice=")2364            m_textCtrlField[i]->SetValue(strControl.substr(7));2365        else2366            m_textCtrlField[i]->SetValue(strControl);2367    }2368}23692370void CEditProductDialog::GetProduct(CProduct& product)2371{2372    // map<string, string> mapValue;2373    // vector<pair<string, string> > vOrderForm;23742375    product.mapValue["category"]     = m_comboBoxCategory->GetValue().Trim();2376    product.mapValue["title"]        = m_textCtrlTitle->GetValue().Trim();2377    product.mapValue["price"]        = m_textCtrlPrice->GetValue().Trim();2378    product.mapValue["description"]  = m_textCtrlDescription->GetValue().Trim();2379    product.mapValue["instructions"] = m_textCtrlInstructions->GetValue().Trim();23802381    for (int i = 0; i < FIELDS_MAX; i++)2382    {2383        if (m_buttonDel[i]->IsShown())2384        {2385            string strLabel = (string)m_textCtrlLabel[i]->GetValue().Trim();2386            string strControl = (string)m_textCtrlField[i]->GetValue();2387            if (strControl.empty())2388                strControl = "text=";2389            else2390                strControl = "choice=" + strControl;2391            product.vOrderForm.push_back(make_pair(strLabel, strControl));2392        }2393    }2394}23952396239723982399240024012402//////////////////////////////////////////////////////////////////////////////2403//2404// CViewProductDialog2405//24062407CViewProductDialog::CViewProductDialog(wxWindow* parent, const CProduct& productIn) : CViewProductDialogBase(parent)2408{2409    Connect(wxEVT_REPLY1, wxCommandEventHandler(CViewProductDialog::OnReply1), NULL, this);2410    AddCallbackAvailable(GetEventHandler());24112412    // Fill display with product summary while waiting for details2413    product = productIn;2414    UpdateProductDisplay(false);24152416    m_buttonBack->Enable(false);2417    m_buttonNext->Enable(!product.vOrderForm.empty());2418    m_htmlWinReviews->Show(true);2419    m_scrolledWindow->Show(false);2420    this->Layout();24212422    // Request details from seller2423    _beginthread(ThreadRequestProductDetails, 0, new pair<CProduct, wxEvtHandler*>(product, GetEventHandler()));2424}24252426CViewProductDialog::~CViewProductDialog()2427{2428    RemoveCallbackAvailable(GetEventHandler());2429}24302431void ThreadRequestProductDetails(void* parg)2432{2433    // Extract parameters2434    pair<CProduct, wxEvtHandler*>* pitem = (pair<CProduct, wxEvtHandler*>*)parg;2435    CProduct product = pitem->first;2436    wxEvtHandler* pevthandler = pitem->second;2437    delete pitem;24382439    // Connect to seller2440    CNode* pnode = ConnectNode(product.addr, 5 * 60);2441    if (!pnode)2442    {2443        CDataStream ssEmpty;2444        AddPendingReplyEvent1(pevthandler, ssEmpty);2445        return;2446    }24472448    // Request detailed product, with response going to OnReply1 via dialog's event handler2449    pnode->PushRequest("getdetails", product.GetHash(), AddPendingReplyEvent1, (void*)pevthandler);2450}24512452void CViewProductDialog::OnReply1(wxCommandEvent& event)2453{2454    CDataStream ss = GetStreamFromEvent(event);2455    if (ss.empty())2456    {2457        product.mapValue["description"] = "-- CAN'T CONNECT TO SELLER --\n";2458        UpdateProductDisplay(true);2459        return;2460    }24612462    int nRet;2463    CProduct product2;2464    try2465    {2466        ss >> nRet;2467        if (nRet > 0)2468            throw false;2469        ss >> product2;2470        if (product2.GetHash() != product.GetHash())2471            throw false;2472        if (!product2.CheckSignature())2473            throw false;2474    }2475    catch (...)2476    {2477        product.mapValue["description"] = "-- INVALID RESPONSE --\n";2478        UpdateProductDisplay(true);2479        return;2480    }24812482    product = product2;2483    UpdateProductDisplay(true);2484}24852486bool CompareReviewsBestFirst(const CReview* p1, const CReview* p2)2487{2488    return (p1->nAtoms > p2->nAtoms);2489}24902491void CViewProductDialog::UpdateProductDisplay(bool fDetails)2492{2493    // Product and reviews2494    string strHTML;2495    strHTML.reserve(4000);2496    strHTML += "<html>\n"2497               "<head>\n"2498               "<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">\n"2499               "</head>\n"2500               "<body>\n";2501    strHTML += "<b>Category:</b> " + HtmlEscape(product.mapValue["category"]) + "<br>\n";2502    strHTML += "<b>Title:</b> "    + HtmlEscape(product.mapValue["title"])    + "<br>\n";2503    strHTML += "<b>Price:</b> "    + HtmlEscape(product.mapValue["price"])    + "<br>\n";25042505    if (!fDetails)2506        strHTML += "<b>Loading details...</b><br>\n<br>\n";2507    else2508        strHTML += HtmlEscape(product.mapValue["description"], true) + "<br>\n<br>\n";25092510    strHTML += "<b>Reviews:</b><br>\n<br>\n";25112512    if (!product.vchPubKeyFrom.empty())2513    {2514        CReviewDB reviewdb("r");25152516        // Get reviews2517        vector<CReview> vReviews;2518        reviewdb.ReadReviews(product.GetUserHash(), vReviews);25192520        // Get reviewer's number of atoms2521        vector<CReview*> vSortedReviews;2522        vSortedReviews.reserve(vReviews.size());2523        for (vector<CReview>::reverse_iterator it = vReviews.rbegin(); it != vReviews.rend(); ++it)2524        {2525            CReview& review = *it;2526            CUser user;2527            reviewdb.ReadUser(review.GetUserHash(), user);2528            review.nAtoms = user.GetAtomCount();2529            vSortedReviews.push_back(&review);2530        }25312532        reviewdb.Close();25332534        // Sort2535        stable_sort(vSortedReviews.begin(), vSortedReviews.end(), CompareReviewsBestFirst);25362537        // Format reviews2538        foreach(CReview* preview, vSortedReviews)2539        {2540            CReview& review = *preview;2541            int nStars = atoi(review.mapValue["stars"].c_str());2542            if (nStars < 1 || nStars > 5)2543                continue;25442545            strHTML += "<b>" + itostr(nStars) + (nStars == 1 ? " star" : " stars") + "</b>";2546            strHTML += " &nbsp;&nbsp;&nbsp; ";2547            strHTML += DateStr(atoi64(review.mapValue["date"])) + "<br>\n";2548            strHTML += HtmlEscape(review.mapValue["review"], true);2549            strHTML += "<br>\n<br>\n";2550        }2551    }25522553    strHTML += "</body>\n</html>\n";25542555    // Shrink capacity to fit2556    string(strHTML.begin(), strHTML.end()).swap(strHTML);25572558    m_htmlWinReviews->SetPage(strHTML);25592560    ///// need to find some other indicator to use so can allow empty order form2561    if (product.vOrderForm.empty())2562        return;25632564    // Order form2565    m_staticTextInstructions->SetLabel(product.mapValue["instructions"]);2566    for (int i = 0; i < FIELDS_MAX; i++)2567    {2568        m_staticTextLabel[i] = NULL;2569        m_textCtrlField[i] = NULL;2570        m_choiceField[i] = NULL;2571    }25722573    // Construct flexgridsizer2574    wxBoxSizer* bSizer21 = (wxBoxSizer*)m_scrolledWindow->GetSizer();2575    wxFlexGridSizer* fgSizer;2576    fgSizer = new wxFlexGridSizer(0, 2, 0, 0);2577    fgSizer->AddGrowableCol(1);2578    fgSizer->SetFlexibleDirection(wxBOTH);2579    fgSizer->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED);25802581    // Construct order form fields2582    wxWindow* windowLast = NULL;2583    for (int i = 0; i < product.vOrderForm.size(); i++)2584    {2585        string strLabel = product.vOrderForm[i].first;2586        string strControl = product.vOrderForm[i].second;25872588        if (strLabel.size() < 20)2589            strLabel.insert(strLabel.begin(), 20 - strLabel.size(), ' ');25902591        m_staticTextLabel[i] = new wxStaticText(m_scrolledWindow, wxID_ANY, strLabel, wxDefaultPosition, wxDefaultSize, wxALIGN_RIGHT);2592        m_staticTextLabel[i]->Wrap(-1);2593        fgSizer->Add(m_staticTextLabel[i], 0, wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxALL, 5);25942595        if (strControl.substr(0, 5) == "text=")2596        {2597            m_textCtrlField[i] = new wxTextCtrl(m_scrolledWindow, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0);2598            fgSizer->Add(m_textCtrlField[i], 1, wxALL|wxALIGN_CENTER_VERTICAL|wxEXPAND, 5);2599            windowLast = m_textCtrlField[i];2600        }2601        else if (strControl.substr(0, 7) == "choice=")2602        {2603            vector<string> vChoices;2604            ParseString(strControl.substr(7), ',', vChoices);26052606            wxArrayString arraystring;2607            foreach(const string& str, vChoices)2608                arraystring.Add(str);26092610            m_choiceField[i] = new wxChoice(m_scrolledWindow, wxID_ANY, wxDefaultPosition, wxDefaultSize, arraystring, 0);2611            fgSizer->Add(m_choiceField[i], 0, wxALL|wxALIGN_CENTER_VERTICAL, 5);2612            windowLast = m_choiceField[i];2613        }2614        else2615        {2616            m_textCtrlField[i] = new wxTextCtrl(m_scrolledWindow, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0);2617            fgSizer->Add(m_textCtrlField[i], 1, wxALL|wxALIGN_CENTER_VERTICAL|wxEXPAND, 5);2618            m_staticTextLabel[i]->Show(false);2619            m_textCtrlField[i]->Show(false);2620        }2621    }26222623    // Insert after instructions and before submit/cancel buttons2624    bSizer21->Insert(2, fgSizer, 0, wxEXPAND|wxRIGHT|wxLEFT, 5);2625    m_scrolledWindow->Layout();2626    bSizer21->Fit(m_scrolledWindow);2627    this->Layout();26282629    // Fixup the tab order2630    m_buttonSubmitForm->MoveAfterInTabOrder(windowLast);2631    m_buttonCancelForm->MoveAfterInTabOrder(m_buttonSubmitForm);2632    //m_buttonBack->MoveAfterInTabOrder(m_buttonCancelForm);2633    //m_buttonNext->MoveAfterInTabOrder(m_buttonBack);2634    //m_buttonCancel->MoveAfterInTabOrder(m_buttonNext);2635    this->Layout();2636}26372638void CViewProductDialog::GetOrder(CWalletTx& wtx)2639{2640    wtx.SetNull();2641    for (int i = 0; i < product.vOrderForm.size(); i++)2642    {2643        string strValue;2644        if (m_textCtrlField[i])2645            strValue = m_textCtrlField[i]->GetValue().Trim();2646        else2647            strValue = m_choiceField[i]->GetStringSelection();2648        wtx.vOrderForm.push_back(make_pair(m_staticTextLabel[i]->GetLabel(), strValue));2649    }2650}26512652void CViewProductDialog::OnButtonSubmitForm(wxCommandEvent& event)2653{2654    m_buttonSubmitForm->Enable(false);2655    m_buttonCancelForm->Enable(false);26562657    CWalletTx wtx;2658    GetOrder(wtx);26592660    CSendingDialog* pdialog = new CSendingDialog(this, product.addr, atoi64(product.mapValue["price"]), wtx);2661    if (!pdialog->ShowModal())2662    {2663        m_buttonSubmitForm->Enable(true);2664        m_buttonCancelForm->Enable(true);2665        return;2666    }2667}26682669void CViewProductDialog::OnButtonCancelForm(wxCommandEvent& event)2670{2671    Destroy();2672}26732674void CViewProductDialog::OnButtonBack(wxCommandEvent& event)2675{2676    Freeze();2677    m_htmlWinReviews->Show(true);2678    m_scrolledWindow->Show(false);2679    m_buttonBack->Enable(false);2680    m_buttonNext->Enable(!product.vOrderForm.empty());2681    this->Layout();2682    Thaw();2683}26842685void CViewProductDialog::OnButtonNext(wxCommandEvent& event)2686{2687    if (!product.vOrderForm.empty())2688    {2689        Freeze();2690        m_htmlWinReviews->Show(false);2691        m_scrolledWindow->Show(true);2692        m_buttonBack->Enable(true);2693        m_buttonNext->Enable(false);2694        this->Layout();2695        Thaw();2696    }2697}26982699void CViewProductDialog::OnButtonCancel(wxCommandEvent& event)2700{2701    Destroy();2702}27032704270527062707270827092710//////////////////////////////////////////////////////////////////////////////2711//2712// CViewOrderDialog2713//27142715CViewOrderDialog::CViewOrderDialog(wxWindow* parent, CWalletTx order, bool fReceived) : CViewOrderDialogBase(parent)2716{2717    int64 nPrice = (fReceived ? order.GetCredit() : order.GetDebit());27182719    string strHTML;2720    strHTML.reserve(4000);2721    strHTML += "<html>\n"2722               "<head>\n"2723               "<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">\n"2724               "</head>\n"2725               "<body>\n";2726    strHTML += "<b>Time:</b> "   + HtmlEscape(DateTimeStr(order.nTimeReceived)) + "<br>\n";2727    strHTML += "<b>Price:</b> "  + HtmlEscape(FormatMoney(nPrice)) + "<br>\n";2728    strHTML += "<b>Status:</b> " + HtmlEscape(FormatTxStatus(order)) + "<br>\n";27292730    strHTML += "<table>\n";2731    for (int i = 0; i < order.vOrderForm.size(); i++)2732    {2733        strHTML += " <tr><td><b>" + HtmlEscape(order.vOrderForm[i].first) + ":</b></td>";2734        strHTML += "<td>" + HtmlEscape(order.vOrderForm[i].second) + "</td></tr>\n";2735    }2736    strHTML += "</table>\n";27372738    strHTML += "</body>\n</html>\n";27392740    // Shrink capacity to fit2741    // (strings are ref counted, so it may live on in SetPage)2742    string(strHTML.begin(), strHTML.end()).swap(strHTML);27432744    m_htmlWin->SetPage(strHTML);2745}27462747void CViewOrderDialog::OnButtonOK(wxCommandEvent& event)2748{2749    Destroy();2750}27512752275327542755275627572758//////////////////////////////////////////////////////////////////////////////2759//2760// CEditReviewDialog2761//27622763CEditReviewDialog::CEditReviewDialog(wxWindow* parent) : CEditReviewDialogBase(parent)2764{2765}27662767void CEditReviewDialog::OnButtonSubmit(wxCommandEvent& event)2768{2769    if (m_choiceStars->GetSelection() == -1)2770    {2771        wxMessageBox("Please select a rating ");2772        return;2773    }27742775    CReview review;2776    GetReview(review);27772778    // Sign the review2779    review.vchPubKeyFrom = keyUser.GetPubKey();2780    if (!keyUser.Sign(review.GetSigHash(), review.vchSig))2781    {2782        wxMessageBox("Unable to digitally sign the review ");2783        return;2784    }27852786    // Broadcast2787    if (!review.AcceptReview())2788    {2789        wxMessageBox("Save failed ");2790        return;2791    }2792    RelayMessage(CInv(MSG_REVIEW, review.GetHash()), review);27932794    Destroy();2795}27962797void CEditReviewDialog::OnButtonCancel(wxCommandEvent& event)2798{2799    Destroy();2800}28012802void CEditReviewDialog::GetReview(CReview& review)2803{2804    review.mapValue["time"]   = i64tostr(GetAdjustedTime());2805    review.mapValue["stars"]  = itostr(m_choiceStars->GetSelection()+1);2806    review.mapValue["review"] = m_textCtrlReview->GetValue();2807}2808280928102811281228132814281528162817281828192820//////////////////////////////////////////////////////////////////////////////2821//2822// CMyApp2823//28242825// Define a new application2826class CMyApp: public wxApp2827{2828  public:2829    CMyApp(){};2830    ~CMyApp(){};2831    bool OnInit();2832    bool OnInit2();2833    int OnExit();28342835    // 2nd-level exception handling: we get all the exceptions occurring in any2836    // event handler here2837    virtual bool OnExceptionInMainLoop();28382839    // 3rd, and final, level exception handling: whenever an unhandled2840    // exception is caught, this function is called2841    virtual void OnUnhandledException();28422843    // and now for something different: this function is called in case of a2844    // crash (e.g. dereferencing null pointer, division by 0, ...)2845    virtual void OnFatalException();2846};28472848IMPLEMENT_APP(CMyApp)28492850bool CMyApp::OnInit()2851{2852    try2853    {2854        return OnInit2();2855    }2856    catch (std::exception& e) {2857        PrintException(&e, "OnInit()");2858    } catch (...) {2859        PrintException(NULL, "OnInit()");2860    }2861    return false;2862}28632864map<string, string> ParseParameters(int argc, char* argv[])2865{2866    map<string, string> mapArgs;2867    for (int i = 0; i < argc; i++)2868    {2869        char psz[10000];2870        strcpy(psz, argv[i]);2871        char* pszValue = "";2872        if (strchr(psz, '='))2873        {2874            pszValue = strchr(psz, '=');2875            *pszValue++ = '\0';2876        }2877        strlwr(psz);2878        if (psz[0] == '-')2879            psz[0] = '/';2880        mapArgs[psz] = pszValue;2881    }2882    return mapArgs;2883}28842885bool CMyApp::OnInit2()2886{2887#ifdef _MSC_VER2888    // Turn off microsoft heap dump noise for now2889    _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);2890    _CrtSetReportFile(_CRT_WARN, CreateFile("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));2891#endif28922893    //// debug print2894    printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");2895    printf("Bitcoin CMyApp::OnInit()\n");28962897    //2898    // Limit to single instance per user2899    // Required to protect the database files if we're going to keep deleting log.*2900    //2901    wxString strMutexName = wxString("Bitcoin.") + getenv("HOMEPATH");2902    for (int i = 0; i < strMutexName.size(); i++)2903        if (!isalnum(strMutexName[i]))2904            strMutexName[i] = '.';2905    wxSingleInstanceChecker* psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);2906    if (psingleinstancechecker->IsAnotherRunning())2907    {2908        printf("Existing instance found\n");2909        unsigned int nStart = GetTime();2910        loop2911        {2912            // Show the previous instance and exit2913            HWND hwndPrev = FindWindow("wxWindowClassNR", "Bitcoin");2914            if (hwndPrev)2915            {2916                if (IsIconic(hwndPrev))2917                    ShowWindow(hwndPrev, SW_RESTORE);2918                SetForegroundWindow(hwndPrev);2919                return false;2920            }29212922            if (GetTime() > nStart + 60)2923                return false;29242925            // Resume this instance if the other exits2926            delete psingleinstancechecker;2927            Sleep(1000);2928            psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);2929            if (!psingleinstancechecker->IsAnotherRunning())2930                break;2931        }2932    }29332934    //2935    // Parameters2936    //2937    wxImage::AddHandler(new wxPNGHandler);2938    map<string, string> mapArgs = ParseParameters(argc, argv);29392940    if (mapArgs.count("/datadir"))2941        strSetDataDir = mapArgs["/datadir"];29422943    if (mapArgs.count("/proxy"))2944        addrProxy = CAddress(mapArgs["/proxy"].c_str());29452946    if (mapArgs.count("/debug"))2947        fDebug = true;29482949    if (mapArgs.count("/dropmessages"))2950    {2951        nDropMessagesTest = atoi(mapArgs["/dropmessages"]);2952        if (nDropMessagesTest == 0)2953            nDropMessagesTest = 20;2954    }29552956    if (mapArgs.count("/loadblockindextest"))2957    {2958        CTxDB txdb("r");2959        txdb.LoadBlockIndex();2960        PrintBlockTree();2961        ExitProcess(0);2962    }29632964    //2965    // Load data files2966    //2967    string strErrors;2968    int64 nStart, nEnd;29692970    printf("Loading addresses...\n");2971    QueryPerformanceCounter((LARGE_INTEGER*)&nStart);2972    if (!LoadAddresses())2973        strErrors += "Error loading addr.dat      \n";2974    QueryPerformanceCounter((LARGE_INTEGER*)&nEnd);2975    printf(" addresses   %20I64d\n", nEnd - nStart);29762977    printf("Loading block index...\n");2978    QueryPerformanceCounter((LARGE_INTEGER*)&nStart);2979    if (!LoadBlockIndex())2980        strErrors += "Error loading blkindex.dat      \n";2981    QueryPerformanceCounter((LARGE_INTEGER*)&nEnd);2982    printf(" block index %20I64d\n", nEnd - nStart);29832984    printf("Loading wallet...\n");2985    QueryPerformanceCounter((LARGE_INTEGER*)&nStart);2986    if (!LoadWallet())2987        strErrors += "Error loading wallet.dat      \n";2988    QueryPerformanceCounter((LARGE_INTEGER*)&nEnd);2989    printf(" wallet      %20I64d\n", nEnd - nStart);29902991    printf("Done loading\n");29922993        //// debug print2994        printf("mapBlockIndex.size() = %d\n",   mapBlockIndex.size());2995        printf("nBestHeight = %d\n",            nBestHeight);2996        printf("mapKeys.size() = %d\n",         mapKeys.size());2997        printf("mapPubKeys.size() = %d\n",      mapPubKeys.size());2998        printf("mapWallet.size() = %d\n",       mapWallet.size());2999        printf("mapAddressBook.size() = %d\n",  mapAddressBook.size());30003001    if (!strErrors.empty())3002    {3003        wxMessageBox(strErrors);3004        OnExit();3005        return false;3006    }30073008    // Add wallet transactions that aren't already in a block to mapTransactions3009    ReacceptWalletTransactions();30103011    //3012    // Parameters3013    //3014    if (mapArgs.count("/printblockindex") || mapArgs.count("/printblocktree"))3015    {3016        PrintBlockTree();3017        OnExit();3018        return false;3019    }30203021    if (mapArgs.count("/gen"))3022    {3023        if (mapArgs["/gen"].empty())3024            fGenerateBitcoins = true;3025        else3026            fGenerateBitcoins = atoi(mapArgs["/gen"].c_str());3027    }30283029    //3030    // Create the main frame window3031    //3032    {3033        pframeMain = new CMainFrame(NULL);3034        pframeMain->Show();30353036        if (!StartNode(strErrors))3037            wxMessageBox(strErrors);30383039        if (fGenerateBitcoins)3040            if (_beginthread(ThreadBitcoinMiner, 0, NULL) == -1)3041                printf("Error: _beginthread(ThreadBitcoinMiner) failed\n");30423043        //3044        // Tests3045        //3046        if (argc >= 2 && stricmp(argv[1], "/send") == 0)3047        {3048            int64 nValue = 1;3049            if (argc >= 3)3050                ParseMoney(argv[2], nValue);30513052            string strAddress;3053            if (argc >= 4)3054                strAddress = argv[3];3055            CAddress addr(strAddress.c_str());30563057            CWalletTx wtx;3058            wtx.mapValue["to"] = strAddress;3059            wtx.mapValue["from"] = addrLocalHost.ToString();3060            wtx.mapValue["message"] = "command line send";30613062            // Send to IP address3063            CSendingDialog* pdialog = new CSendingDialog(pframeMain, addr, nValue, wtx);3064            if (!pdialog->ShowModal())3065                return false;3066        }30673068        if (mapArgs.count("/randsendtest"))3069        {3070            if (!mapArgs["/randsendtest"].empty())3071                _beginthread(ThreadRandSendTest, 0, new string(mapArgs["/randsendtest"]));3072            else3073                fRandSendTest = true;3074            fDebug = true;3075        }3076    }30773078    return true;3079}30803081int CMyApp::OnExit()3082{3083    Shutdown(NULL);3084    return wxApp::OnExit();3085}30863087bool CMyApp::OnExceptionInMainLoop()3088{3089    try3090    {3091        throw;3092    }3093    catch (std::exception& e)3094    {3095        PrintException(&e, "CMyApp::OnExceptionInMainLoop()");3096        wxLogWarning(_T("Exception %s %s"), typeid(e).name(), e.what());3097        Sleep(1000);3098        throw;3099    }3100    catch (...)3101    {3102        PrintException(NULL, "CMyApp::OnExceptionInMainLoop()");3103        wxLogWarning(_T("Unknown exception"));3104        Sleep(1000);3105        throw;3106    }31073108    return true;3109}31103111void CMyApp::OnUnhandledException()3112{3113    // this shows how we may let some exception propagate uncaught3114    try3115    {3116        throw;3117    }3118    catch (std::exception& e)3119    {3120        PrintException(&e, "CMyApp::OnUnhandledException()");3121        wxLogWarning(_T("Exception %s %s"), typeid(e).name(), e.what());3122        Sleep(1000);3123        throw;3124    }3125    catch (...)3126    {3127        PrintException(NULL, "CMyApp::OnUnhandledException()");3128        wxLogWarning(_T("Unknown exception"));3129        Sleep(1000);3130        throw;3131    }3132}31333134void CMyApp::OnFatalException()3135{3136    wxMessageBox("Program has crashed and will terminate. ", "", wxOK | wxICON_ERROR);3137}3138313931403141void MainFrameRepaint()3142{3143    if (pframeMain)3144    {3145        printf("MainFrameRepaint()\n");3146        wxPaintEvent event;3147        pframeMain->Refresh();3148        pframeMain->AddPendingEvent(event);3149    }3150}31513152315331543155315631573158// randsendtest to bitcoin address3159void ThreadRandSendTest(void* parg)3160{3161    string strAddress = *(string*)parg;3162    uint160 hash160;3163    if (!AddressToHash160(strAddress, hash160))3164    {3165        wxMessageBox(strprintf("ThreadRandSendTest: Bitcoin address '%s' not valid ", strAddress.c_str()));3166        return;3167    }31683169    loop3170    {3171        Sleep(GetRand(30) * 1000 + 100);31723173        // Message3174        CWalletTx wtx;3175        wtx.mapValue["to"] = strAddress;3176        wtx.mapValue["from"] = addrLocalHost.ToString();3177        static int nRep;3178        wtx.mapValue["message"] = strprintf("randsendtest %d\n", ++nRep);31793180        // Value3181        int64 nValue = (GetRand(9) + 1) * 100 * CENT;3182        if (GetBalance() < nValue)3183        {3184            wxMessageBox("Out of money ");3185            return;3186        }3187        nValue += (nRep % 100) * CENT;31883189        // Send to bitcoin address3190        CScript scriptPubKey;3191        scriptPubKey << OP_DUP << OP_HASH160 << hash160 << OP_EQUALVERIFY << OP_CHECKSIG;31923193        if (!SendMoney(scriptPubKey, nValue, wtx))3194            return;3195    }3196}319731983199// randsendtest to any connected node3200void RandSend()3201{3202    CWalletTx wtx;32033204    while (vNodes.empty())3205        Sleep(1000);3206    CAddress addr;3207    CRITICAL_BLOCK(cs_vNodes)3208        addr = vNodes[GetRand(vNodes.size())]->addr;32093210    // Message3211    wtx.mapValue["to"] = addr.ToString();3212    wtx.mapValue["from"] = addrLocalHost.ToString();3213    static int nRep;3214    wtx.mapValue["message"] = strprintf("randsendtest %d\n", ++nRep);32153216    // Value3217    int64 nValue = (GetRand(999) + 1) * CENT;3218    if (GetBalance() < nValue)3219    {3220        wxMessageBox("Out of money ");3221        return;3222    }32233224    // Send to IP address3225    CSendingDialog* pdialog = new CSendingDialog(pframeMain, addr, nValue, wtx);3226    if (!pdialog->Show())3227        wxMessageBox("ShowModal Failed ");3228}

Click a line number to link to it; use #L10-L20 for a range. "=" next to a version means the file is identical there.

0:000:00