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.5 · 2009-02-04

ui.cpp

3,290 lines · plain text · GitHub · 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();28extern int g_isPainting;29303132333435//////////////////////////////////////////////////////////////////////////////36//37// Util38//3940void HandleCtrlA(wxKeyEvent& event)41{42    // Ctrl-a select all43    wxTextCtrl* textCtrl = (wxTextCtrl*)event.GetEventObject();44    if (event.GetModifiers() == wxMOD_CONTROL && event.GetKeyCode() == 'A')45        textCtrl->SetSelection(-1, -1);46    event.Skip();47}4849bool Is24HourTime()50{51    //char pszHourFormat[256];52    //pszHourFormat[0] = '\0';53    //GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_ITIME, pszHourFormat, 256);54    //return (pszHourFormat[0] != '0');55    return true;56}5758string DateStr(int64 nTime)59{60    return (string)wxDateTime((time_t)nTime).FormatDate();61}6263string DateTimeStr(int64 nTime)64{65    wxDateTime datetime((time_t)nTime);66    if (Is24HourTime())67        return (string)datetime.Format("%x %H:%M");68    else69        return (string)datetime.Format("%x ") + itostr((datetime.GetHour() + 11) % 12 + 1) + (string)datetime.Format(":%M %p");70}7172wxString GetItemText(wxListCtrl* listCtrl, int nIndex, int nColumn)73{74    // Helper to simplify access to listctrl75    wxListItem item;76    item.m_itemId = nIndex;77    item.m_col = nColumn;78    item.m_mask = wxLIST_MASK_TEXT;79    if (!listCtrl->GetItem(item))80        return "";81    return item.GetText();82}8384int InsertLine(wxListCtrl* listCtrl, const wxString& str0, const wxString& str1)85{86    int nIndex = listCtrl->InsertItem(listCtrl->GetItemCount(), str0);87    listCtrl->SetItem(nIndex, 1, str1);88    return nIndex;89}9091int InsertLine(wxListCtrl* listCtrl, const wxString& str0, const wxString& str1, const wxString& str2, const wxString& str3, const wxString& str4)92{93    int nIndex = listCtrl->InsertItem(listCtrl->GetItemCount(), str0);94    listCtrl->SetItem(nIndex, 1, str1);95    listCtrl->SetItem(nIndex, 2, str2);96    listCtrl->SetItem(nIndex, 3, str3);97    listCtrl->SetItem(nIndex, 4, str4);98    return nIndex;99}100101int InsertLine(wxListCtrl* listCtrl, void* pdata, const wxString& str0, const wxString& str1, const wxString& str2, const wxString& str3, const wxString& str4)102{103    int nIndex = listCtrl->InsertItem(listCtrl->GetItemCount(), str0);104    listCtrl->SetItemPtrData(nIndex, (wxUIntPtr)pdata);105    listCtrl->SetItem(nIndex, 1, str1);106    listCtrl->SetItem(nIndex, 2, str2);107    listCtrl->SetItem(nIndex, 3, str3);108    listCtrl->SetItem(nIndex, 4, str4);109    return nIndex;110}111112void SetSelection(wxListCtrl* listCtrl, int nIndex)113{114    int nSize = listCtrl->GetItemCount();115    long nState = (wxLIST_STATE_SELECTED|wxLIST_STATE_FOCUSED);116    for (int i = 0; i < nSize; i++)117        listCtrl->SetItemState(i, (i == nIndex ? nState : 0), nState);118}119120int GetSelection(wxListCtrl* listCtrl)121{122    int nSize = listCtrl->GetItemCount();123    for (int i = 0; i < nSize; i++)124        if (listCtrl->GetItemState(i, wxLIST_STATE_FOCUSED))125            return i;126    return -1;127}128129130string HtmlEscape(const char* psz, bool fMultiLine=false)131{132    int len = 0;133    for (const char* p = psz; *p; p++)134    {135             if (*p == '<') len += 4;136        else if (*p == '>') len += 4;137        else if (*p == '&') len += 5;138        else if (*p == '"') len += 6;139        else if (*p == ' ' && p > psz && p[-1] == ' ' && p[1] == ' ') len += 6;140        else if (*p == '\n' && fMultiLine) len += 5;141        else142            len++;143    }144    string str;145    str.reserve(len);146    for (const char* p = psz; *p; p++)147    {148             if (*p == '<') str += "&lt;";149        else if (*p == '>') str += "&gt;";150        else if (*p == '&') str += "&amp;";151        else if (*p == '"') str += "&quot;";152        else if (*p == ' ' && p > psz && p[-1] == ' ' && p[1] == ' ') str += "&nbsp;";153        else if (*p == '\n' && fMultiLine) str += "<br>\n";154        else155            str += *p;156    }157    return str;158}159160string HtmlEscape(const string& str, bool fMultiLine=false)161{162    return HtmlEscape(str.c_str(), fMultiLine);163}164165void AddToMyProducts(CProduct product)166{167    CProduct& productInsert = mapMyProducts[product.GetHash()];168    productInsert = product;169    InsertLine(pframeMain->m_listCtrlProductsSent, &productInsert,170                product.mapValue["category"],171                product.mapValue["title"].substr(0, 100),172                product.mapValue["description"].substr(0, 100),173                product.mapValue["price"],174                "");175}176177178179180181182//////////////////////////////////////////////////////////////////////////////183//184// Custom events185//186187set<void*> setCallbackAvailable;188CCriticalSection cs_setCallbackAvailable;189190void AddCallbackAvailable(void* p)191{192    CRITICAL_BLOCK(cs_setCallbackAvailable)193        setCallbackAvailable.insert(p);194}195196void RemoveCallbackAvailable(void* p)197{198    CRITICAL_BLOCK(cs_setCallbackAvailable)199        setCallbackAvailable.erase(p);200}201202bool IsCallbackAvailable(void* p)203{204    CRITICAL_BLOCK(cs_setCallbackAvailable)205        return setCallbackAvailable.count(p);206    return false;207}208209template<typename T>210void AddPendingCustomEvent(wxEvtHandler* pevthandler, int nEventID, const T pbeginIn, const T pendIn)211{212    if (!pevthandler)213        return;214215    const char* pbegin = (pendIn != pbeginIn) ? &pbeginIn[0] : NULL;216    const char* pend = pbegin + (pendIn - pbeginIn) * sizeof(pbeginIn[0]);217    wxCommandEvent event(nEventID);218    wxString strData(wxChar(0), (pend - pbegin) / sizeof(wxChar) + 1);219    memcpy(&strData[0], pbegin, pend - pbegin);220    event.SetString(strData);221    event.SetInt(pend - pbegin);222223    pevthandler->AddPendingEvent(event);224}225226template<class T>227void AddPendingCustomEvent(wxEvtHandler* pevthandler, int nEventID, const T& obj)228{229    CDataStream ss;230    ss << obj;231    AddPendingCustomEvent(pevthandler, nEventID, ss.begin(), ss.end());232}233234void AddPendingReplyEvent1(void* pevthandler, CDataStream& vRecv)235{236    if (IsCallbackAvailable(pevthandler))237        AddPendingCustomEvent((wxEvtHandler*)pevthandler, wxEVT_REPLY1, vRecv.begin(), vRecv.end());238}239240void AddPendingReplyEvent2(void* pevthandler, CDataStream& vRecv)241{242    if (IsCallbackAvailable(pevthandler))243        AddPendingCustomEvent((wxEvtHandler*)pevthandler, wxEVT_REPLY2, vRecv.begin(), vRecv.end());244}245246void AddPendingReplyEvent3(void* pevthandler, CDataStream& vRecv)247{248    if (IsCallbackAvailable(pevthandler))249        AddPendingCustomEvent((wxEvtHandler*)pevthandler, wxEVT_REPLY3, vRecv.begin(), vRecv.end());250}251252CDataStream GetStreamFromEvent(const wxCommandEvent& event)253{254    wxString strData = event.GetString();255    return CDataStream(strData.begin(), strData.begin() + event.GetInt(), SER_NETWORK);256}257258259260261262263264//////////////////////////////////////////////////////////////////////////////265//266// CMainFrame267//268269CMainFrame::CMainFrame(wxWindow* parent) : CMainFrameBase(parent)270{271    Connect(wxEVT_CROSSTHREADCALL, wxCommandEventHandler(CMainFrame::OnCrossThreadCall), NULL, this);272273    // Init274    fRefreshListCtrl = false;275    fRefreshListCtrlRunning = false;276    fOnSetFocusAddress = false;277    pindexBestLast = NULL;278    m_choiceFilter->SetSelection(0);279    m_staticTextBalance->SetLabel(FormatMoney(GetBalance()) + "  ");280    m_listCtrl->SetFocus();281    SetIcon(wxICON(bitcoin));282    m_menuOptions->Check(wxID_OPTIONSGENERATEBITCOINS, fGenerateBitcoins);283284    // Init toolbar with transparency masked bitmaps285    m_toolBar->ClearTools();286287    //// shouldn't have to do mask separately anymore, bitmap alpha support added in wx 2.8.9,288    wxBitmap bmpSend(wxT("send20"), wxBITMAP_TYPE_RESOURCE);289    bmpSend.SetMask(new wxMask(wxBitmap(wxT("send20mask"), wxBITMAP_TYPE_RESOURCE)));290    m_toolBar->AddTool(wxID_BUTTONSEND, wxT("&Send Coins"), bmpSend, wxNullBitmap, wxITEM_NORMAL, wxEmptyString, wxEmptyString);291292    wxBitmap bmpAddressBook(wxT("addressbook20"), wxBITMAP_TYPE_RESOURCE);293    bmpAddressBook.SetMask(new wxMask(wxBitmap(wxT("addressbook20mask"), wxBITMAP_TYPE_RESOURCE)));294    m_toolBar->AddTool(wxID_BUTTONRECEIVE, wxT("&Address Book"), bmpAddressBook, wxNullBitmap, wxITEM_NORMAL, wxEmptyString, wxEmptyString);295296    m_toolBar->Realize();297298    // Init column headers299    int nDateWidth = DateTimeStr(1229413914).size() * 6 + 8;300    m_listCtrl->InsertColumn(0, "",             wxLIST_FORMAT_LEFT,     0);301    m_listCtrl->InsertColumn(1, "",             wxLIST_FORMAT_LEFT,     0);302    m_listCtrl->InsertColumn(2, "Status",       wxLIST_FORMAT_LEFT,    90);303    m_listCtrl->InsertColumn(3, "Date",         wxLIST_FORMAT_LEFT,   nDateWidth);304    m_listCtrl->InsertColumn(4, "Description",  wxLIST_FORMAT_LEFT,   409 - nDateWidth);305    m_listCtrl->InsertColumn(5, "Debit",        wxLIST_FORMAT_RIGHT,   79);306    m_listCtrl->InsertColumn(6, "Credit",       wxLIST_FORMAT_RIGHT,   79);307308    //m_listCtrlProductsSent->InsertColumn(0, "Category",      wxLIST_FORMAT_LEFT,  100);309    //m_listCtrlProductsSent->InsertColumn(1, "Title",         wxLIST_FORMAT_LEFT,  100);310    //m_listCtrlProductsSent->InsertColumn(2, "Description",   wxLIST_FORMAT_LEFT,  100);311    //m_listCtrlProductsSent->InsertColumn(3, "Price",         wxLIST_FORMAT_LEFT,  100);312    //m_listCtrlProductsSent->InsertColumn(4, "",              wxLIST_FORMAT_LEFT,  100);313314    //m_listCtrlOrdersSent->InsertColumn(0, "Time",          wxLIST_FORMAT_LEFT,  100);315    //m_listCtrlOrdersSent->InsertColumn(1, "Price",         wxLIST_FORMAT_LEFT,  100);316    //m_listCtrlOrdersSent->InsertColumn(2, "",              wxLIST_FORMAT_LEFT,  100);317    //m_listCtrlOrdersSent->InsertColumn(3, "",              wxLIST_FORMAT_LEFT,  100);318    //m_listCtrlOrdersSent->InsertColumn(4, "",              wxLIST_FORMAT_LEFT,  100);319320    //m_listCtrlOrdersReceived->InsertColumn(0, "Time",            wxLIST_FORMAT_LEFT,  100);321    //m_listCtrlOrdersReceived->InsertColumn(1, "Price",           wxLIST_FORMAT_LEFT,  100);322    //m_listCtrlOrdersReceived->InsertColumn(2, "Payment Status",  wxLIST_FORMAT_LEFT,  100);323    //m_listCtrlOrdersReceived->InsertColumn(3, "",                wxLIST_FORMAT_LEFT,  100);324    //m_listCtrlOrdersReceived->InsertColumn(4, "",                wxLIST_FORMAT_LEFT,  100);325326    // Init status bar327    int pnWidths[3] = { -100, 81, 286 };328    m_statusBar->SetFieldsCount(3, pnWidths);329330    // Fill your address text box331    vector<unsigned char> vchPubKey;332    if (CWalletDB("r").ReadDefaultKey(vchPubKey))333        m_textCtrlAddress->SetValue(PubKeyToAddress(vchPubKey));334335    // Fill listctrl with wallet transactions336    RefreshListCtrl();337}338339CMainFrame::~CMainFrame()340{341    pframeMain = NULL;342}343344void Shutdown(void* parg)345{346    static CCriticalSection cs_Shutdown;347    CRITICAL_BLOCK(cs_Shutdown)348    {349        fShutdown = true;350        nTransactionsUpdated++;351        DBFlush(false);352        StopNode();353        DBFlush(true);354355        printf("Bitcoin exiting\n");356        exit(0);357    }358}359360void CMainFrame::OnClose(wxCloseEvent& event)361{362    Destroy();363    _beginthread(Shutdown, 0, NULL);364}365366void CMainFrame::OnMouseEvents(wxMouseEvent& event)367{368    RandAddSeed();369    RAND_add(&event.m_x, sizeof(event.m_x), 0.25);370    RAND_add(&event.m_y, sizeof(event.m_y), 0.25);371}372373void CMainFrame::OnListColBeginDrag(wxListEvent& event)374{375     // Hidden columns not resizeable376     if (event.GetColumn() <= 1 && !fDebug)377        event.Veto();378}379380void 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)381{382    string str0 = strSort;383    long nData = *(long*)&hashKey;384385    if (fNew)386    {387        nIndex = m_listCtrl->InsertItem(0, str0);388    }389    else390    {391        if (nIndex == -1)392        {393            // Find item394            while ((nIndex = m_listCtrl->FindItem(nIndex, nData)) != -1)395                if (GetItemText(m_listCtrl, nIndex, 1) == hashKey.ToString())396                    break;397            if (nIndex == -1)398            {399                printf("CMainFrame::InsertLine : Couldn't find item to be updated\n");400                return;401            }402        }403404        // If sort key changed, must delete and reinsert to make it relocate405        if (GetItemText(m_listCtrl, nIndex, 0) != str0)406        {407            m_listCtrl->DeleteItem(nIndex);408            nIndex = m_listCtrl->InsertItem(0, str0);409        }410    }411412    m_listCtrl->SetItem(nIndex, 1, hashKey.ToString());413    m_listCtrl->SetItem(nIndex, 2, str2);414    m_listCtrl->SetItem(nIndex, 3, str3);415    m_listCtrl->SetItem(nIndex, 4, str4);416    m_listCtrl->SetItem(nIndex, 5, str5);417    m_listCtrl->SetItem(nIndex, 6, str6);418    m_listCtrl->SetItemData(nIndex, nData);419}420421string FormatTxStatus(const CWalletTx& wtx)422{423    // Status424    int nDepth = wtx.GetDepthInMainChain();425    if (!wtx.IsFinal())426        return strprintf("Open for %d blocks", nBestHeight - wtx.nLockTime);427    else if (nDepth < 6)428        return strprintf("%d/unconfirmed", nDepth);429    else430        return strprintf("%d blocks", nDepth);431}432433string SingleLine(const string& strIn)434{435    string strOut;436    bool fOneSpace = false;437    foreach(int c, strIn)438    {439        if (isspace(c))440        {441            fOneSpace = true;442        }443        else if (c > ' ')444        {445            if (fOneSpace && !strOut.empty())446                strOut += ' ';447            strOut += c;448            fOneSpace = false;449        }450    }451    return strOut;452}453454void CMainFrame::InsertTransaction(const CWalletTx& wtx, bool fNew, int nIndex)455{456    int64 nTime = wtx.nTimeDisplayed = wtx.GetTxTime();457    int64 nCredit = wtx.GetCredit();458    int64 nDebit = wtx.GetDebit();459    int64 nNet = nCredit - nDebit;460    uint256 hash = wtx.GetHash();461    string strStatus = FormatTxStatus(wtx);462    map<string, string> mapValue = wtx.mapValue;463464    // Find the block the tx is in465    CBlockIndex* pindex = NULL;466    map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(wtx.hashBlock);467    if (mi != mapBlockIndex.end())468        pindex = (*mi).second;469470    // Sort order, unrecorded transactions sort to the top471    string strSort = strprintf("%010d-%01d-%010u",472        (pindex ? pindex->nHeight : INT_MAX),473        (wtx.IsCoinBase() ? 1 : 0),474        wtx.nTimeReceived);475476    // Insert line477    if (nNet > 0 || wtx.IsCoinBase())478    {479        //480        // Credit481        //482        string strDescription;483484        if (wtx.IsCoinBase())485        {486            // Coinbase487            strDescription = "Generated";488            if (nCredit == 0)489            {490                int64 nUnmatured = 0;491                foreach(const CTxOut& txout, wtx.vout)492                    nUnmatured += txout.GetCredit();493                if (wtx.IsInMainChain())494                    strDescription += strprintf(" (%s matures in %d more blocks)", FormatMoney(nUnmatured).c_str(), wtx.GetBlocksToMaturity());495                else496                    strDescription += " (not accepted)";497            }498        }499        else if (!mapValue["from"].empty() || !mapValue["message"].empty())500        {501            // Online transaction502            if (!mapValue["from"].empty())503                strDescription += "From: " + mapValue["from"];504            if (!mapValue["message"].empty())505            {506                if (!strDescription.empty())507                    strDescription += " - ";508                strDescription += mapValue["message"];509            }510        }511        else512        {513            // Offline transaction514            foreach(const CTxOut& txout, wtx.vout)515            {516                if (txout.IsMine())517                {518                    vector<unsigned char> vchPubKey;519                    if (ExtractPubKey(txout.scriptPubKey, true, vchPubKey))520                    {521                        string strAddress = PubKeyToAddress(vchPubKey);522                        if (mapAddressBook.count(strAddress))523                        {524                            //strDescription += "Received payment to ";525                            //strDescription += "Received with address ";526                            strDescription += "From: unknown, To: ";527                            strDescription += strAddress;528                            /// The labeling feature is just too confusing, so I hid it529                            /// by putting it at the end where it runs off the screen.530                            /// It can still be seen by widening the column, or in the531                            /// details dialog.532                            if (!mapAddressBook[strAddress].empty())533                                strDescription += " (" + mapAddressBook[strAddress] + ")";534                        }535                    }536                    break;537                }538            }539        }540541        InsertLine(fNew, nIndex, hash, strSort,542                   strStatus,543                   nTime ? DateTimeStr(nTime) : "",544                   SingleLine(strDescription),545                   "",546                   FormatMoney(nNet, true));547    }548    else549    {550        bool fAllFromMe = true;551        foreach(const CTxIn& txin, wtx.vin)552            fAllFromMe = fAllFromMe && txin.IsMine();553554        bool fAllToMe = true;555        foreach(const CTxOut& txout, wtx.vout)556            fAllToMe = fAllToMe && txout.IsMine();557558        if (fAllFromMe && fAllToMe)559        {560            // Payment to self561            int64 nValue = wtx.vout[0].nValue;562            InsertLine(fNew, nIndex, hash, strSort,563                       strStatus,564                       nTime ? DateTimeStr(nTime) : "",565                       "Payment to yourself",566                       FormatMoney(nNet - nValue, true),567                       FormatMoney(nValue, true));568        }569        else if (fAllFromMe)570        {571            //572            // Debit573            //574            int64 nTxFee = nDebit - wtx.GetValueOut();575            for (int nOut = 0; nOut < wtx.vout.size(); nOut++)576            {577                const CTxOut& txout = wtx.vout[nOut];578                if (txout.IsMine())579                    continue;580581                string strAddress;582                if (!mapValue["to"].empty())583                {584                    // Online transaction585                    strAddress = mapValue["to"];586                }587                else588                {589                    // Offline transaction590                    uint160 hash160;591                    if (ExtractHash160(txout.scriptPubKey, hash160))592                        strAddress = Hash160ToAddress(hash160);593                }594595                string strDescription = "To: ";596                if (mapAddressBook.count(strAddress) && !mapAddressBook[strAddress].empty())597                    strDescription += mapAddressBook[strAddress] + " ";598                strDescription += strAddress;599                if (!mapValue["message"].empty())600                {601                    if (!strDescription.empty())602                        strDescription += " - ";603                    strDescription += mapValue["message"];604                }605606                int64 nValue = txout.nValue;607                if (nOut == 0 && nTxFee > 0)608                    nValue += nTxFee;609610                InsertLine(fNew, nIndex, hash, strprintf("%s-%d", strSort.c_str(), nOut),611                           strStatus,612                           nTime ? DateTimeStr(nTime) : "",613                           SingleLine(strDescription),614                           FormatMoney(-nValue, true),615                           "");616            }617        }618        else619        {620            //621            // Mixed debit transaction, can't break down payees622            //623            bool fAllMine = true;624            foreach(const CTxOut& txout, wtx.vout)625                fAllMine = fAllMine && txout.IsMine();626            foreach(const CTxIn& txin, wtx.vin)627                fAllMine = fAllMine && txin.IsMine();628629            InsertLine(fNew, nIndex, hash, strSort,630                       strStatus,631                       nTime ? DateTimeStr(nTime) : "",632                       "",633                       FormatMoney(nNet, true),634                       "");635        }636    }637}638639void CMainFrame::RefreshStatus()640{641    static int nLastTop;642    int nTop = m_listCtrl->GetTopItem();643    if (nTop == nLastTop && pindexBestLast == pindexBest)644        return;645646    TRY_CRITICAL_BLOCK(cs_mapWallet)647    {648        int nStart = nTop;649        int nEnd = min(nStart + 100, m_listCtrl->GetItemCount());650        if (pindexBestLast == pindexBest)651        {652            if (nStart >= nLastTop && nStart < nLastTop + 100)653                nStart = nLastTop + 100;654            if (nEnd >= nLastTop && nEnd < nLastTop + 100)655                nEnd = nLastTop;656        }657        nLastTop = nTop;658        pindexBestLast = pindexBest;659660        for (int nIndex = nStart; nIndex < nEnd; nIndex++)661        {662            uint256 hash((string)GetItemText(m_listCtrl, nIndex, 1));663            map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash);664            if (mi == mapWallet.end())665            {666                printf("CMainFrame::RefreshStatus() : tx not found in mapWallet\n");667                continue;668            }669            const CWalletTx& wtx = (*mi).second;670            if (wtx.IsCoinBase() || wtx.GetTxTime() != wtx.nTimeDisplayed)671                InsertTransaction(wtx, false, nIndex);672            else673                m_listCtrl->SetItem(nIndex, 2, FormatTxStatus(wtx));674        }675    }676}677678void CMainFrame::RefreshListCtrl()679{680    fRefreshListCtrl = true;681    ::wxWakeUpIdle();682}683684void CMainFrame::OnIdle(wxIdleEvent& event)685{686    if (fRefreshListCtrl)687    {688        // Collect list of wallet transactions and sort newest first689        bool fEntered = false;690        vector<pair<unsigned int, uint256> > vSorted;691        TRY_CRITICAL_BLOCK(cs_mapWallet)692        {693            printf("RefreshListCtrl starting\n");694            fEntered = true;695            fRefreshListCtrl = false;696            vWalletUpdated.clear();697698            // Do the newest transactions first699            vSorted.reserve(mapWallet.size());700            for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)701            {702                const CWalletTx& wtx = (*it).second;703                unsigned int nTime = UINT_MAX - wtx.GetTxTime();704                vSorted.push_back(make_pair(nTime, (*it).first));705            }706            m_listCtrl->DeleteAllItems();707        }708        if (!fEntered)709            return;710711        sort(vSorted.begin(), vSorted.end());712713        // Fill list control714        for (int i = 0; i < vSorted.size();)715        {716            if (fShutdown)717                return;718            bool fEntered = false;719            TRY_CRITICAL_BLOCK(cs_mapWallet)720            {721                fEntered = true;722                uint256& hash = vSorted[i++].second;723                map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash);724                if (mi != mapWallet.end())725                    InsertTransaction((*mi).second, true);726            }727            if (!fEntered || i == 100 || i % 500 == 0)728                wxYield();729        }730731        printf("RefreshListCtrl done\n");732    }733    else734    {735        // Check for time updates736        static int64 nLastTime;737        if (GetTime() > nLastTime + 30)738        {739            TRY_CRITICAL_BLOCK(cs_mapWallet)740            {741                nLastTime = GetTime();742                for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)743                {744                    CWalletTx& wtx = (*it).second;745                    if (wtx.nTimeDisplayed && wtx.nTimeDisplayed != wtx.GetTxTime())746                        InsertTransaction(wtx, false);747                }748            }749        }750    }751}752753void CMainFrame::OnPaint(wxPaintEvent& event)754{755    event.Skip();756}757758void CMainFrame::OnPaintListCtrl(wxPaintEvent& event)759{760    // Update listctrl contents761    if (!vWalletUpdated.empty())762    {763        TRY_CRITICAL_BLOCK(cs_mapWallet)764        {765            pair<uint256, bool> item;766            foreach(item, vWalletUpdated)767            {768                bool fNew = item.second;769                map<uint256, CWalletTx>::iterator mi = mapWallet.find(item.first);770                if (mi != mapWallet.end())771                {772                    printf("vWalletUpdated: %s %s\n", (*mi).second.GetHash().ToString().substr(0,6).c_str(), fNew ? "new" : "");773                    InsertTransaction((*mi).second, fNew);774                }775            }776            m_listCtrl->ScrollList(0, INT_MAX);777            vWalletUpdated.clear();778        }779    }780781    // Update status column of visible items only782    RefreshStatus();783784    // Update status bar785    string strGen = "";786    if (fGenerateBitcoins)787        strGen = "    Generating";788    if (fGenerateBitcoins && vNodes.empty())789        strGen = "(not connected)";790    m_statusBar->SetStatusText(strGen, 1);791792    string strStatus = strprintf("     %d connections     %d blocks     %d transactions", vNodes.size(), nBestHeight + 1, m_listCtrl->GetItemCount());793    m_statusBar->SetStatusText(strStatus, 2);794795    // Balance total796    TRY_CRITICAL_BLOCK(cs_mapWallet)797        m_staticTextBalance->SetLabel(FormatMoney(GetBalance()) + "  ");798799    m_listCtrl->OnPaint(event);800}801802void CrossThreadCall(wxCommandEvent& event)803{804    if (pframeMain)805        pframeMain->GetEventHandler()->AddPendingEvent(event);806}807808void CrossThreadCall(int nID, void* pdata)809{810    wxCommandEvent event;811    event.SetInt(nID);812    event.SetClientData(pdata);813    if (pframeMain)814        pframeMain->GetEventHandler()->AddPendingEvent(event);815}816817void CMainFrame::OnCrossThreadCall(wxCommandEvent& event)818{819    void* pdata = event.GetClientData();820    switch (event.GetInt())821    {822        case UICALL_ADDORDER:823        {824            break;825        }826827        case UICALL_UPDATEORDER:828        {829            break;830        }831    }832}833834void CMainFrame::OnMenuFileExit(wxCommandEvent& event)835{836    Close(true);837}838839void CMainFrame::OnMenuOptionsGenerate(wxCommandEvent& event)840{841    fGenerateBitcoins = event.IsChecked();842    nTransactionsUpdated++;843    CWalletDB().WriteSetting("fGenerateBitcoins", fGenerateBitcoins);844845    if (fGenerateBitcoins)846        if (_beginthread(ThreadBitcoinMiner, 0, NULL) == -1)847            printf("Error: _beginthread(ThreadBitcoinMiner) failed\n");848849    Refresh();850    wxPaintEvent eventPaint;851    AddPendingEvent(eventPaint);852}853854void CMainFrame::OnMenuOptionsChangeYourAddress(wxCommandEvent& event)855{856    OnButtonChange(event);857}858859void CMainFrame::OnMenuOptionsOptions(wxCommandEvent& event)860{861    COptionsDialog dialog(this);862    dialog.ShowModal();863}864865void CMainFrame::OnMenuHelpAbout(wxCommandEvent& event)866{867    CAboutDialog dialog(this);868    dialog.ShowModal();869}870871void CMainFrame::OnButtonSend(wxCommandEvent& event)872{873    /// debug test874    if (fRandSendTest)875    {876        RandSend();877        return;878    }879880    // Toolbar: Send881    CSendDialog dialog(this);882    dialog.ShowModal();883}884885void CMainFrame::OnButtonAddressBook(wxCommandEvent& event)886{887    // Toolbar: Address Book888    CAddressBookDialog dialogAddr(this, "", false);889    if (dialogAddr.ShowModal() == 2)890    {891        // Send892        CSendDialog dialogSend(this, dialogAddr.GetAddress());893        dialogSend.ShowModal();894    }895}896897void CMainFrame::OnSetFocusAddress(wxFocusEvent& event)898{899    // Automatically select-all when entering window900    m_textCtrlAddress->SetSelection(-1, -1);901    fOnSetFocusAddress = true;902    event.Skip();903}904905void CMainFrame::OnMouseEventsAddress(wxMouseEvent& event)906{907    if (fOnSetFocusAddress)908        m_textCtrlAddress->SetSelection(-1, -1);909    fOnSetFocusAddress = false;910    event.Skip();911}912913void CMainFrame::OnButtonCopy(wxCommandEvent& event)914{915    // Copy address box to clipboard916    if (wxTheClipboard->Open())917    {918        wxTheClipboard->SetData(new wxTextDataObject(m_textCtrlAddress->GetValue()));919        wxTheClipboard->Close();920    }921}922923void CMainFrame::OnButtonChange(wxCommandEvent& event)924{925    CYourAddressDialog dialog(this, string(m_textCtrlAddress->GetValue()));926    if (!dialog.ShowModal())927        return;928    string strAddress = (string)dialog.GetAddress();929    if (strAddress != m_textCtrlAddress->GetValue())930    {931        uint160 hash160;932        if (!AddressToHash160(strAddress, hash160))933            return;934        if (!mapPubKeys.count(hash160))935            return;936        CWalletDB().WriteDefaultKey(mapPubKeys[hash160]);937        m_textCtrlAddress->SetValue(strAddress);938    }939}940941void CMainFrame::OnListItemActivatedAllTransactions(wxListEvent& event)942{943    uint256 hash((string)GetItemText(m_listCtrl, event.GetIndex(), 1));944    CWalletTx wtx;945    CRITICAL_BLOCK(cs_mapWallet)946    {947        map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash);948        if (mi == mapWallet.end())949        {950            printf("CMainFrame::OnListItemActivatedAllTransactions() : tx not found in mapWallet\n");951            return;952        }953        wtx = (*mi).second;954    }955    CTxDetailsDialog dialog(this, wtx);956    dialog.ShowModal();957    //CTxDetailsDialog* pdialog = new CTxDetailsDialog(this, wtx);958    //pdialog->Show();959}960961void CMainFrame::OnListItemActivatedProductsSent(wxListEvent& event)962{963    CProduct& product = *(CProduct*)event.GetItem().GetData();964    CEditProductDialog* pdialog = new CEditProductDialog(this);965    pdialog->SetProduct(product);966    pdialog->Show();967}968969void CMainFrame::OnListItemActivatedOrdersSent(wxListEvent& event)970{971    CWalletTx& order = *(CWalletTx*)event.GetItem().GetData();972    CViewOrderDialog* pdialog = new CViewOrderDialog(this, order, false);973    pdialog->Show();974}975976void CMainFrame::OnListItemActivatedOrdersReceived(wxListEvent& event)977{978    CWalletTx& order = *(CWalletTx*)event.GetItem().GetData();979    CViewOrderDialog* pdialog = new CViewOrderDialog(this, order, true);980    pdialog->Show();981}982983984985986987988989//////////////////////////////////////////////////////////////////////////////990//991// CTxDetailsDialog992//993994CTxDetailsDialog::CTxDetailsDialog(wxWindow* parent, CWalletTx wtx) : CTxDetailsDialogBase(parent)995{996    string strHTML;997    strHTML.reserve(4000);998    strHTML += "<html><font face='verdana, arial, helvetica, sans-serif'>";9991000    int64 nTime = wtx.GetTxTime();1001    int64 nCredit = wtx.GetCredit();1002    int64 nDebit = wtx.GetDebit();1003    int64 nNet = nCredit - nDebit;1004100510061007    strHTML += "<b>Status:</b> " + FormatTxStatus(wtx) + "<br>";1008    strHTML += "<b>Date:</b> " + (nTime ? DateTimeStr(nTime) : "") + "<br>";100910101011    //1012    // From1013    //1014    if (wtx.IsCoinBase())1015    {1016        strHTML += "<b>Source:</b> Generated<br>";1017    }1018    else if (!wtx.mapValue["from"].empty())1019    {1020        // Online transaction1021        if (!wtx.mapValue["from"].empty())1022            strHTML += "<b>From:</b> " + HtmlEscape(wtx.mapValue["from"]) + "<br>";1023    }1024    else1025    {1026        // Offline transaction1027        if (nNet > 0)1028        {1029            // Credit1030            foreach(const CTxOut& txout, wtx.vout)1031            {1032                if (txout.IsMine())1033                {1034                    vector<unsigned char> vchPubKey;1035                    if (ExtractPubKey(txout.scriptPubKey, true, vchPubKey))1036                    {1037                        string strAddress = PubKeyToAddress(vchPubKey);1038                        if (mapAddressBook.count(strAddress))1039                        {1040                            strHTML += "<b>From:</b> unknown<br>";1041                            strHTML += "<b>To:</b> ";1042                            strHTML += HtmlEscape(strAddress);1043                            if (!mapAddressBook[strAddress].empty())1044                                strHTML += " (yours, label: " + mapAddressBook[strAddress] + ")";1045                            else1046                                strHTML += " (yours)";1047                            strHTML += "<br>";1048                        }1049                    }1050                    break;1051                }1052            }1053        }1054    }105510561057    //1058    // To1059    //1060    string strAddress;1061    if (!wtx.mapValue["to"].empty())1062    {1063        // Online transaction1064        strAddress = wtx.mapValue["to"];1065        strHTML += "<b>To:</b> ";1066        if (mapAddressBook.count(strAddress) && !mapAddressBook[strAddress].empty())1067            strHTML += mapAddressBook[strAddress] + " ";1068        strHTML += HtmlEscape(strAddress) + "<br>";1069    }107010711072    //1073    // Amount1074    //1075    if (wtx.IsCoinBase() && nCredit == 0)1076    {1077        //1078        // Coinbase1079        //1080        int64 nUnmatured = 0;1081        foreach(const CTxOut& txout, wtx.vout)1082            nUnmatured += txout.GetCredit();1083        if (wtx.IsInMainChain())1084            strHTML += strprintf("<b>Credit:</b> (%s matures in %d more blocks)<br>", FormatMoney(nUnmatured).c_str(), wtx.GetBlocksToMaturity());1085        else1086            strHTML += "<b>Credit:</b> (not accepted)<br>";1087    }1088    else if (nNet > 0)1089    {1090        //1091        // Credit1092        //1093        strHTML += "<b>Credit:</b> " + FormatMoney(nNet) + "<br>";1094    }1095    else1096    {1097        bool fAllFromMe = true;1098        foreach(const CTxIn& txin, wtx.vin)1099            fAllFromMe = fAllFromMe && txin.IsMine();11001101        bool fAllToMe = true;1102        foreach(const CTxOut& txout, wtx.vout)1103            fAllToMe = fAllToMe && txout.IsMine();11041105        if (fAllFromMe)1106        {1107            //1108            // Debit1109            //1110            foreach(const CTxOut& txout, wtx.vout)1111            {1112                if (txout.IsMine())1113                    continue;11141115                if (wtx.mapValue["to"].empty())1116                {1117                    // Offline transaction1118                    uint160 hash160;1119                    if (ExtractHash160(txout.scriptPubKey, hash160))1120                    {1121                        string strAddress = Hash160ToAddress(hash160);1122                        strHTML += "<b>To:</b> ";1123                        if (mapAddressBook.count(strAddress) && !mapAddressBook[strAddress].empty())1124                            strHTML += mapAddressBook[strAddress] + " ";1125                        strHTML += strAddress;1126                        strHTML += "<br>";1127                    }1128                }11291130                strHTML += "<b>Debit:</b> " + FormatMoney(-txout.nValue) + "<br>";1131            }11321133            if (fAllToMe)1134            {1135                // Payment to self1136                int64 nValue = wtx.vout[0].nValue;1137                strHTML += "<b>Debit:</b> " + FormatMoney(-nValue) + "<br>";1138                strHTML += "<b>Credit:</b> " + FormatMoney(nValue) + "<br>";1139            }11401141            int64 nTxFee = nDebit - wtx.GetValueOut();1142            if (nTxFee > 0)1143                strHTML += "<b>Transaction fee:</b> " + FormatMoney(-nTxFee) + "<br>";1144        }1145        else1146        {1147            //1148            // Mixed debit transaction1149            //1150            foreach(const CTxIn& txin, wtx.vin)1151                if (txin.IsMine())1152                    strHTML += "<b>Debit:</b> " + FormatMoney(-txin.GetDebit()) + "<br>";1153            foreach(const CTxOut& txout, wtx.vout)1154                if (txout.IsMine())1155                    strHTML += "<b>Credit:</b> " + FormatMoney(txout.GetCredit()) + "<br>";1156        }1157    }11581159    strHTML += "<b>Net amount:</b> " + FormatMoney(nNet, true) + "<br>";116011611162    //1163    // Message1164    //1165    if (!wtx.mapValue["message"].empty())1166        strHTML += "<br><b>Message:</b><br>" + HtmlEscape(wtx.mapValue["message"], true) + "<br>";11671168    if (wtx.IsCoinBase())1169        strHTML += "<br>Generated coins must wait 120 blocks before they can be spent.  When you generated this block, it was broadcast to the network to be added to the block chain.  If it fails to get into the chain, it will change to \"not accepted\" and not be spendable.  This may occasionally happen if another node generates a block within a few seconds of yours.<br>";117011711172    //1173    // Debug view1174    //1175    if (fDebug)1176    {1177        strHTML += "<hr><br>debug print<br><br>";1178        foreach(const CTxIn& txin, wtx.vin)1179            if (txin.IsMine())1180                strHTML += "<b>Debit:</b> " + FormatMoney(-txin.GetDebit()) + "<br>";1181        foreach(const CTxOut& txout, wtx.vout)1182            if (txout.IsMine())1183                strHTML += "<b>Credit:</b> " + FormatMoney(txout.GetCredit()) + "<br>";11841185        strHTML += "<b>Inputs:</b><br>";1186        CRITICAL_BLOCK(cs_mapWallet)1187        {1188            foreach(const CTxIn& txin, wtx.vin)1189            {1190                COutPoint prevout = txin.prevout;1191                map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);1192                if (mi != mapWallet.end())1193                {1194                    const CWalletTx& prev = (*mi).second;1195                    if (prevout.n < prev.vout.size())1196                    {1197                        strHTML += HtmlEscape(prev.ToString(), true);1198                        strHTML += " &nbsp;&nbsp; " + FormatTxStatus(prev) + ", ";1199                        strHTML = strHTML + "IsMine=" + (prev.vout[prevout.n].IsMine() ? "true" : "false") + "<br>";1200                    }1201                }1202            }1203        }12041205        strHTML += "<br><hr><br><b>Transaction:</b><br>";1206        strHTML += HtmlEscape(wtx.ToString(), true);1207    }1208120912101211    strHTML += "</font></html>";1212    string(strHTML.begin(), strHTML.end()).swap(strHTML);1213    m_htmlWin->SetPage(strHTML);1214    m_buttonOK->SetFocus();1215}12161217void CTxDetailsDialog::OnButtonOK(wxCommandEvent& event)1218{1219    Close();1220    //Destroy();1221}122212231224122512261227//////////////////////////////////////////////////////////////////////////////1228//1229// COptionsDialog1230//12311232COptionsDialog::COptionsDialog(wxWindow* parent) : COptionsDialogBase(parent)1233{1234    m_textCtrlTransactionFee->SetValue(FormatMoney(nTransactionFee));1235    m_buttonOK->SetFocus();1236}12371238void COptionsDialog::OnKillFocusTransactionFee(wxFocusEvent& event)1239{1240    int64 nTmp = nTransactionFee;1241    ParseMoney(m_textCtrlTransactionFee->GetValue(), nTmp);1242    m_textCtrlTransactionFee->SetValue(FormatMoney(nTmp));1243}12441245void COptionsDialog::OnButtonOK(wxCommandEvent& event)1246{1247    // nTransactionFee1248    int64 nPrevTransactionFee = nTransactionFee;1249    if (ParseMoney(m_textCtrlTransactionFee->GetValue(), nTransactionFee) && nTransactionFee != nPrevTransactionFee)1250        CWalletDB().WriteSetting("nTransactionFee", nTransactionFee);12511252    Close();1253}12541255void COptionsDialog::OnButtonCancel(wxCommandEvent& event)1256{1257    Close();1258}1259126012611262126312641265//////////////////////////////////////////////////////////////////////////////1266//1267// CAboutDialog1268//12691270CAboutDialog::CAboutDialog(wxWindow* parent) : CAboutDialogBase(parent)1271{1272    m_staticTextVersion->SetLabel(strprintf("version 0.%d.%d Alpha", VERSION/100, VERSION%100));12731274    // Workaround until upgrade to wxWidgets supporting UTF-81275    wxString str = m_staticTextMain->GetLabel();1276    if (str.Find('Â') != wxNOT_FOUND)1277        str.Remove(str.Find('Â'), 1);1278    m_staticTextMain->SetLabel(str);1279}12801281void CAboutDialog::OnButtonOK(wxCommandEvent& event)1282{1283    Close();1284}1285128612871288128912901291//////////////////////////////////////////////////////////////////////////////1292//1293// CSendDialog1294//12951296CSendDialog::CSendDialog(wxWindow* parent, const wxString& strAddress) : CSendDialogBase(parent)1297{1298    // Init1299    m_textCtrlAddress->SetValue(strAddress);1300    m_choiceTransferType->SetSelection(0);1301    m_bitmapCheckMark->Show(false);1302    //// todo: should add a display of your balance for convenience13031304    // Set Icon1305    wxBitmap bmpSend(wxT("send16"), wxBITMAP_TYPE_RESOURCE);1306    bmpSend.SetMask(new wxMask(wxBitmap(wxT("send16masknoshadow"), wxBITMAP_TYPE_RESOURCE)));1307    wxIcon iconSend;1308    iconSend.CopyFromBitmap(bmpSend);1309    SetIcon(iconSend);13101311    wxCommandEvent event;1312    OnTextAddress(event);13131314    // Fixup the tab order1315    m_buttonPaste->MoveAfterInTabOrder(m_buttonCancel);1316    m_buttonAddress->MoveAfterInTabOrder(m_buttonPaste);1317    this->Layout();1318}13191320void CSendDialog::OnTextAddress(wxCommandEvent& event)1321{1322    // Check mark1323    bool fBitcoinAddress = IsValidBitcoinAddress(m_textCtrlAddress->GetValue());1324    m_bitmapCheckMark->Show(fBitcoinAddress);13251326    // Grey out message if bitcoin address1327    bool fEnable = !fBitcoinAddress;1328    m_staticTextFrom->Enable(fEnable);1329    m_textCtrlFrom->Enable(fEnable);1330    m_staticTextMessage->Enable(fEnable);1331    m_textCtrlMessage->Enable(fEnable);1332    m_textCtrlMessage->SetBackgroundColour(wxSystemSettings::GetColour(fEnable ? wxSYS_COLOUR_WINDOW : wxSYS_COLOUR_BTNFACE));1333}13341335void CSendDialog::OnKillFocusAmount(wxFocusEvent& event)1336{1337    // Reformat the amount1338    if (m_textCtrlAmount->GetValue().Trim().empty())1339        return;1340    int64 nTmp;1341    if (ParseMoney(m_textCtrlAmount->GetValue(), nTmp))1342        m_textCtrlAmount->SetValue(FormatMoney(nTmp));1343}13441345void CSendDialog::OnButtonAddressBook(wxCommandEvent& event)1346{1347    // Open address book1348    CAddressBookDialog dialog(this, m_textCtrlAddress->GetValue(), true);1349    if (dialog.ShowModal())1350        m_textCtrlAddress->SetValue(dialog.GetAddress());1351}13521353void CSendDialog::OnButtonPaste(wxCommandEvent& event)1354{1355    // Copy clipboard to address box1356    if (wxTheClipboard->Open())1357    {1358        if (wxTheClipboard->IsSupported(wxDF_TEXT))1359        {1360            wxTextDataObject data;1361            wxTheClipboard->GetData(data);1362            m_textCtrlAddress->SetValue(data.GetText());1363        }1364        wxTheClipboard->Close();1365    }1366}13671368void CSendDialog::OnButtonSend(wxCommandEvent& event)1369{1370    CWalletTx wtx;1371    string strAddress = (string)m_textCtrlAddress->GetValue();13721373    // Parse amount1374    int64 nValue = 0;1375    if (!ParseMoney(m_textCtrlAmount->GetValue(), nValue) || nValue <= 0)1376    {1377        wxMessageBox("Error in amount  ", "Send Coins");1378        return;1379    }1380    if (nValue > GetBalance())1381    {1382        wxMessageBox("Amount exceeds your balance  ", "Send Coins");1383        return;1384    }1385    if (nValue + nTransactionFee > GetBalance())1386    {1387        wxMessageBox(string("Total exceeds your balance when the ") + FormatMoney(nTransactionFee) + " transaction fee is included  ", "Send Coins");1388        return;1389    }13901391    // Parse bitcoin address1392    uint160 hash160;1393    bool fBitcoinAddress = AddressToHash160(strAddress, hash160);13941395    if (fBitcoinAddress)1396    {1397        // Send to bitcoin address1398        CScript scriptPubKey;1399        scriptPubKey << OP_DUP << OP_HASH160 << hash160 << OP_EQUALVERIFY << OP_CHECKSIG;14001401        if (!SendMoney(scriptPubKey, nValue, wtx))1402            return;14031404        wxMessageBox("Payment sent  ", "Sending...");1405    }1406    else1407    {1408        // Parse IP address1409        CAddress addr(strAddress.c_str());1410        if (addr.ip == 0)1411        {1412            wxMessageBox("Invalid address  ", "Send Coins");1413            return;1414        }14151416        // Message1417        wtx.mapValue["to"] = strAddress;1418        wtx.mapValue["from"] = m_textCtrlFrom->GetValue();1419        wtx.mapValue["message"] = m_textCtrlMessage->GetValue();14201421        // Send to IP address1422        CSendingDialog* pdialog = new CSendingDialog(this, addr, nValue, wtx);1423        if (!pdialog->ShowModal())1424            return;1425    }14261427    if (!mapAddressBook.count(strAddress))1428        SetAddressBookName(strAddress, "");14291430    EndModal(true);1431}14321433void CSendDialog::OnButtonCancel(wxCommandEvent& event)1434{1435    // Cancel1436    EndModal(false);1437}1438143914401441144214431444//////////////////////////////////////////////////////////////////////////////1445//1446// CSendingDialog1447//14481449CSendingDialog::CSendingDialog(wxWindow* parent, const CAddress& addrIn, int64 nPriceIn, const CWalletTx& wtxIn) : CSendingDialogBase(NULL) // we have to give null so parent can't destroy us1450{1451    addr = addrIn;1452    nPrice = nPriceIn;1453    wtx = wtxIn;1454    start = wxDateTime::UNow();1455    strStatus = "";1456    fCanCancel = true;1457    fAbort = false;1458    fSuccess = false;1459    fUIDone = false;1460    fWorkDone = false;14611462    SetTitle(strprintf("Sending %s to %s...", FormatMoney(nPrice).c_str(), wtx.mapValue["to"].c_str()));1463    m_textCtrlStatus->SetValue("");14641465    _beginthread(SendingDialogStartTransfer, 0, this);1466}14671468CSendingDialog::~CSendingDialog()1469{1470    printf("~CSendingDialog()\n");1471}14721473void CSendingDialog::Close()1474{1475    // Last one out turn out the lights.1476    // fWorkDone signals that work side is done and UI thread should call destroy.1477    // fUIDone signals that UI window has closed and work thread should call destroy.1478    // This allows the window to disappear and end modality when cancelled1479    // without making the user wait for ConnectNode to return.  The dialog object1480    // hangs around in the background until the work thread exits.1481    if (IsModal())1482        EndModal(fSuccess);1483    else1484        Show(false);1485    if (fWorkDone)1486        Destroy();1487    else1488        fUIDone = true;1489}14901491void CSendingDialog::OnClose(wxCloseEvent& event)1492{1493    if (!event.CanVeto() || fWorkDone || fAbort || !fCanCancel)1494    {1495        Close();1496    }1497    else1498    {1499        event.Veto();1500        wxCommandEvent cmdevent;1501        OnButtonCancel(cmdevent);1502    }1503}15041505void CSendingDialog::OnButtonOK(wxCommandEvent& event)1506{1507    if (fWorkDone)1508        Close();1509}15101511void CSendingDialog::OnButtonCancel(wxCommandEvent& event)1512{1513    if (fCanCancel)1514        fAbort = true;1515}15161517void CSendingDialog::OnPaint(wxPaintEvent& event)1518{1519    if (strStatus.size() > 130)1520        m_textCtrlStatus->SetValue(string("\n") + strStatus);1521    else1522        m_textCtrlStatus->SetValue(string("\n\n") + strStatus);1523    m_staticTextSending->SetFocus();1524    if (!fCanCancel)1525        m_buttonCancel->Enable(false);1526    if (fWorkDone)1527    {1528        m_buttonOK->Enable(true);1529        m_buttonOK->SetFocus();1530        m_buttonCancel->Enable(false);1531    }1532    if (fAbort && fCanCancel && IsShown())1533    {1534        strStatus = "CANCELLED";1535        m_buttonOK->Enable(true);1536        m_buttonOK->SetFocus();1537        m_buttonCancel->Enable(false);1538        m_buttonCancel->SetLabel("Cancelled");1539        Close();1540        wxMessageBox("Transfer cancelled  ", "Sending...", wxOK, this);1541    }1542    event.Skip();15431544    /// debug test1545    if (fRandSendTest && fWorkDone && fSuccess)1546    {1547        Close();1548        Sleep(1000);1549        RandSend();1550    }1551}155215531554//1555// Everything from here on is not in the UI thread and must only communicate1556// with the rest of the dialog through variables and calling repaint.1557//15581559void CSendingDialog::Repaint()1560{1561    Refresh();1562    wxPaintEvent event;1563    AddPendingEvent(event);1564}15651566bool CSendingDialog::Status()1567{1568    if (fUIDone)1569    {1570        Destroy();1571        return false;1572    }1573    if (fAbort && fCanCancel)1574    {1575        strStatus = "CANCELLED";1576        Repaint();1577        fWorkDone = true;1578        return false;1579    }1580    return true;1581}15821583bool CSendingDialog::Status(const string& str)1584{1585    if (!Status())1586        return false;1587    strStatus = str;1588    Repaint();1589    return true;1590}15911592bool CSendingDialog::Error(const string& str)1593{1594    fCanCancel = false;1595    fWorkDone = true;1596    Status(string("Error: ") + str);1597    return false;1598}15991600void SendingDialogStartTransfer(void* parg)1601{1602    ((CSendingDialog*)parg)->StartTransfer();1603}16041605void CSendingDialog::StartTransfer()1606{1607    // Make sure we have enough money1608    if (nPrice + nTransactionFee > GetBalance())1609    {1610        Error("You don't have enough money");1611        return;1612    }16131614    // We may have connected already for product details1615    if (!Status("Connecting..."))1616        return;1617    CNode* pnode = ConnectNode(addr, 5 * 60);1618    if (!pnode)1619    {1620        Error("Unable to connect");1621        return;1622    }16231624    // Send order to seller, with response going to OnReply2 via event handler1625    if (!Status("Requesting public key..."))1626        return;1627    pnode->PushRequest("checkorder", wtx, SendingDialogOnReply2, this);1628}16291630void SendingDialogOnReply2(void* parg, CDataStream& vRecv)1631{1632    ((CSendingDialog*)parg)->OnReply2(vRecv);1633}16341635void CSendingDialog::OnReply2(CDataStream& vRecv)1636{1637    if (!Status("Received public key..."))1638        return;16391640    CScript scriptPubKey;1641    int nRet;1642    try1643    {1644        vRecv >> nRet;1645        if (nRet > 0)1646        {1647            string strMessage;1648            vRecv >> strMessage;1649            Error("Transfer was not accepted");1650            //// todo: enlarge the window and enable a hidden white box to put seller's message1651            return;1652        }1653        vRecv >> scriptPubKey;1654    }1655    catch (...)1656    {1657        //// what do we want to do about this?1658        Error("Invalid response received");1659        return;1660    }16611662    // Should already be connected1663    CNode* pnode = ConnectNode(addr, 5 * 60);1664    if (!pnode)1665    {1666        Error("Lost connection");1667        return;1668    }16691670    // Pause to give the user a chance to cancel1671    while (wxDateTime::UNow() < start + wxTimeSpan(0, 0, 0, 2 * 1000))1672    {1673        Sleep(200);1674        if (!Status())1675            return;1676    }16771678    CRITICAL_BLOCK(cs_main)1679    {1680        // Pay1681        if (!Status("Creating transaction..."))1682            return;1683        if (nPrice + nTransactionFee > GetBalance())1684        {1685            Error("You don't have enough money");1686            return;1687        }1688        int64 nFeeRequired;1689        if (!CreateTransaction(scriptPubKey, nPrice, wtx, nFeeRequired))1690        {1691            if (nPrice + nFeeRequired > GetBalance())1692                Error(strprintf("This is an oversized transaction that requires a transaction fee of %s", FormatMoney(nFeeRequired).c_str()));1693            else1694                Error("Transaction creation failed");1695            return;1696        }16971698        // Last chance to cancel1699        Sleep(50);1700        if (!Status())1701            return;1702        fCanCancel = false;1703        if (fAbort)1704        {1705            fCanCancel = true;1706            if (!Status())1707                return;1708            fCanCancel = false;1709        }1710        if (!Status("Sending payment..."))1711            return;17121713        // Commit1714        if (!CommitTransactionSpent(wtx))1715        {1716            Error("Error finalizing payment");1717            return;1718        }17191720        // Send payment tx to seller, with response going to OnReply3 via event handler1721        pnode->PushRequest("submitorder", wtx, SendingDialogOnReply3, this);17221723        // Accept and broadcast transaction1724        if (!wtx.AcceptTransaction())1725            printf("ERROR: CSendingDialog : wtxNew.AcceptTransaction() %s failed\n", wtx.GetHash().ToString().c_str());1726        wtx.RelayWalletTransaction();17271728        Status("Waiting for confirmation...");1729        MainFrameRepaint();1730    }1731}17321733void SendingDialogOnReply3(void* parg, CDataStream& vRecv)1734{1735    ((CSendingDialog*)parg)->OnReply3(vRecv);1736}17371738void CSendingDialog::OnReply3(CDataStream& vRecv)1739{1740    int nRet;1741    try1742    {1743        vRecv >> nRet;1744        if (nRet > 0)1745        {1746            Error("The payment was sent, but the recipient was unable to verify it.\n"1747                  "The transaction is recorded and will credit to the recipient if it is valid,\n"1748                  "but without comment information.");1749            return;1750        }1751    }1752    catch (...)1753    {1754        //// what do we want to do about this?1755        Error("Payment was sent, but an invalid response was received");1756        return;1757    }17581759    fSuccess = true;1760    fWorkDone = true;1761    Status("Payment completed");1762}1763176417651766176717681769//////////////////////////////////////////////////////////////////////////////1770//1771// CYourAddressDialog1772//17731774CYourAddressDialog::CYourAddressDialog(wxWindow* parent, const string& strInitSelected) : CYourAddressDialogBase(parent)1775{1776    // Init column headers1777    m_listCtrl->InsertColumn(0, "Label", wxLIST_FORMAT_LEFT, 200);1778    m_listCtrl->InsertColumn(1, "Bitcoin Address", wxLIST_FORMAT_LEFT, 350);1779    m_listCtrl->SetFocus();17801781    // Fill listctrl with address book data1782    CRITICAL_BLOCK(cs_mapKeys)1783    {1784        foreach(const PAIRTYPE(string, string)& item, mapAddressBook)1785        {1786            string strAddress = item.first;1787            string strName = item.second;1788            uint160 hash160;1789            bool fMine = (AddressToHash160(strAddress, hash160) && mapPubKeys.count(hash160));1790            if (fMine)1791            {1792                int nIndex = InsertLine(m_listCtrl, strName, strAddress);1793                if (strAddress == strInitSelected)1794                    m_listCtrl->SetItemState(nIndex, wxLIST_STATE_SELECTED|wxLIST_STATE_FOCUSED, wxLIST_STATE_SELECTED|wxLIST_STATE_FOCUSED);1795            }1796        }1797    }1798}17991800wxString CYourAddressDialog::GetAddress()1801{1802    int nIndex = GetSelection(m_listCtrl);1803    if (nIndex == -1)1804        return "";1805    return GetItemText(m_listCtrl, nIndex, 1);1806}18071808void CYourAddressDialog::OnListEndLabelEdit(wxListEvent& event)1809{1810    // Update address book with edited name1811    if (event.IsEditCancelled())1812        return;1813    string strAddress = (string)GetItemText(m_listCtrl, event.GetIndex(), 1);1814    SetAddressBookName(strAddress, string(event.GetText()));1815    pframeMain->RefreshListCtrl();1816}18171818void CYourAddressDialog::OnListItemSelected(wxListEvent& event)1819{1820}18211822void CYourAddressDialog::OnListItemActivated(wxListEvent& event)1823{1824    // Doubleclick edits item1825    wxCommandEvent event2;1826    OnButtonRename(event2);1827}18281829void CYourAddressDialog::OnButtonRename(wxCommandEvent& event)1830{1831    // Ask new name1832    int nIndex = GetSelection(m_listCtrl);1833    if (nIndex == -1)1834        return;1835    string strName = (string)m_listCtrl->GetItemText(nIndex);1836    string strAddress = (string)GetItemText(m_listCtrl, nIndex, 1);1837    CGetTextFromUserDialog dialog(this, "Edit Address Label", "New Label", strName);1838    if (!dialog.ShowModal())1839        return;1840    strName = dialog.GetValue();18411842    // Change name1843    SetAddressBookName(strAddress, strName);1844    m_listCtrl->SetItemText(nIndex, strName);1845    pframeMain->RefreshListCtrl();1846}18471848void CYourAddressDialog::OnButtonNew(wxCommandEvent& event)1849{1850    // Ask name1851    CGetTextFromUserDialog dialog(this, "New Bitcoin Address", "Label", "");1852    if (!dialog.ShowModal())1853        return;1854    string strName = dialog.GetValue();18551856    // Generate new key1857    string strAddress = PubKeyToAddress(GenerateNewKey());1858    SetAddressBookName(strAddress, strName);18591860    // Add to list and select it1861    int nIndex = InsertLine(m_listCtrl, strName, strAddress);1862    SetSelection(m_listCtrl, nIndex);1863    m_listCtrl->SetFocus();1864}18651866void CYourAddressDialog::OnButtonCopy(wxCommandEvent& event)1867{1868    // Copy address box to clipboard1869    if (wxTheClipboard->Open())1870    {1871        wxTheClipboard->SetData(new wxTextDataObject(GetAddress()));1872        wxTheClipboard->Close();1873    }1874}18751876void CYourAddressDialog::OnButtonOK(wxCommandEvent& event)1877{1878    // OK1879    EndModal(true);1880}18811882void CYourAddressDialog::OnButtonCancel(wxCommandEvent& event)1883{1884    // Cancel1885    EndModal(false);1886}18871888void CYourAddressDialog::OnClose(wxCloseEvent& event)1889{1890    // Close1891    EndModal(false);1892}1893189418951896189718981899//////////////////////////////////////////////////////////////////////////////1900//1901// CAddressBookDialog1902//19031904CAddressBookDialog::CAddressBookDialog(wxWindow* parent, const wxString& strInitSelected, bool fSendingIn) : CAddressBookDialogBase(parent)1905{1906    fSending = fSendingIn;1907    if (!fSending)1908        m_buttonCancel->Show(false);19091910    // Init column headers1911    m_listCtrl->InsertColumn(0, "Name", wxLIST_FORMAT_LEFT, 200);1912    m_listCtrl->InsertColumn(1, "Address", wxLIST_FORMAT_LEFT, 350);1913    m_listCtrl->SetFocus();19141915    // Set Icon1916    wxBitmap bmpAddressBook(wxT("addressbook16"), wxBITMAP_TYPE_RESOURCE);1917    bmpAddressBook.SetMask(new wxMask(wxBitmap(wxT("addressbook16mask"), wxBITMAP_TYPE_RESOURCE)));1918    wxIcon iconAddressBook;1919    iconAddressBook.CopyFromBitmap(bmpAddressBook);1920    SetIcon(iconAddressBook);19211922    // Fill listctrl with address book data1923    CRITICAL_BLOCK(cs_mapKeys)1924    {1925        foreach(const PAIRTYPE(string, string)& item, mapAddressBook)1926        {1927            string strAddress = item.first;1928            string strName = item.second;1929            uint160 hash160;1930            bool fMine = (AddressToHash160(strAddress, hash160) && mapPubKeys.count(hash160));1931            if (!fMine)1932            {1933                int nIndex = InsertLine(m_listCtrl, strName, strAddress);1934                if (strAddress == strInitSelected)1935                    m_listCtrl->SetItemState(nIndex, wxLIST_STATE_SELECTED|wxLIST_STATE_FOCUSED, wxLIST_STATE_SELECTED|wxLIST_STATE_FOCUSED);1936            }1937        }1938    }1939}19401941wxString CAddressBookDialog::GetAddress()1942{1943    int nIndex = GetSelection(m_listCtrl);1944    if (nIndex == -1)1945        return "";1946    return GetItemText(m_listCtrl, nIndex, 1);1947}19481949void CAddressBookDialog::OnListEndLabelEdit(wxListEvent& event)1950{1951    // Update address book with edited name1952    if (event.IsEditCancelled())1953        return;1954    string strAddress = (string)GetItemText(m_listCtrl, event.GetIndex(), 1);1955    SetAddressBookName(strAddress, string(event.GetText()));1956    pframeMain->RefreshListCtrl();1957}19581959void CAddressBookDialog::OnListItemSelected(wxListEvent& event)1960{1961}19621963void CAddressBookDialog::OnListItemActivated(wxListEvent& event)1964{1965    if (fSending)1966    {1967        // Doubleclick returns selection1968        EndModal(GetAddress() != "" ? 2 : 0);1969    }1970    else1971    {1972        // Doubleclick edits item1973        wxCommandEvent event2;1974        OnButtonEdit(event2);1975    }1976}19771978bool CAddressBookDialog::CheckIfMine(const string& strAddress, const string& strTitle)1979{1980    uint160 hash160;1981    bool fMine = (AddressToHash160(strAddress, hash160) && mapPubKeys.count(hash160));1982    if (fMine)1983        wxMessageBox("This is one of your own addresses for receiving payments and cannot be entered in the address book.  ", strTitle);1984    return fMine;1985}19861987void CAddressBookDialog::OnButtonEdit(wxCommandEvent& event)1988{1989    // Ask new name1990    int nIndex = GetSelection(m_listCtrl);1991    if (nIndex == -1)1992        return;1993    string strName = (string)m_listCtrl->GetItemText(nIndex);1994    string strAddress = (string)GetItemText(m_listCtrl, nIndex, 1);1995    string strAddressOrg = strAddress;1996    do1997    {1998        CGetTextFromUserDialog dialog(this, "Edit Address", "Name", strName, "Address", strAddress);1999        if (!dialog.ShowModal())2000            return;2001        strName = dialog.GetValue1();2002        strAddress = dialog.GetValue2();2003    }2004    while (CheckIfMine(strAddress, "Edit Address"));20052006    // Change name2007    if (strAddress != strAddressOrg)2008        CWalletDB().EraseName(strAddressOrg);2009    SetAddressBookName(strAddress, strName);2010    m_listCtrl->SetItem(nIndex, 1, strAddress);2011    m_listCtrl->SetItemText(nIndex, strName);2012    pframeMain->RefreshListCtrl();2013}20142015void CAddressBookDialog::OnButtonNew(wxCommandEvent& event)2016{2017    // Ask name2018    string strName;2019    string strAddress;2020    do2021    {2022        CGetTextFromUserDialog dialog(this, "New Address", "Name", strName, "Address", strAddress);2023        if (!dialog.ShowModal())2024            return;2025        strName = dialog.GetValue1();2026        strAddress = dialog.GetValue2();2027    }2028    while (CheckIfMine(strAddress, "New Address"));20292030    // Add to list and select it2031    SetAddressBookName(strAddress, strName);2032    int nIndex = InsertLine(m_listCtrl, strName, strAddress);2033    SetSelection(m_listCtrl, nIndex);2034    m_listCtrl->SetFocus();2035    pframeMain->RefreshListCtrl();2036}20372038void CAddressBookDialog::OnButtonDelete(wxCommandEvent& event)2039{2040    for (int nIndex = m_listCtrl->GetItemCount()-1; nIndex >= 0; nIndex--)2041    {2042        if (m_listCtrl->GetItemState(nIndex, wxLIST_STATE_SELECTED))2043        {2044            string strAddress = (string)GetItemText(m_listCtrl, nIndex, 1);2045            CWalletDB().EraseName(strAddress);2046            m_listCtrl->DeleteItem(nIndex);2047        }2048    }2049    pframeMain->RefreshListCtrl();2050}20512052void CAddressBookDialog::OnButtonCopy(wxCommandEvent& event)2053{2054    // Copy address box to clipboard2055    if (wxTheClipboard->Open())2056    {2057        wxTheClipboard->SetData(new wxTextDataObject(GetAddress()));2058        wxTheClipboard->Close();2059    }2060}20612062void CAddressBookDialog::OnButtonOK(wxCommandEvent& event)2063{2064    // OK2065    EndModal(GetAddress() != "" ? 1 : 0);2066}20672068void CAddressBookDialog::OnButtonCancel(wxCommandEvent& event)2069{2070    // Cancel2071    EndModal(0);2072}20732074void CAddressBookDialog::OnClose(wxCloseEvent& event)2075{2076    // Close2077    EndModal(0);2078}2079208020812082208320842085//////////////////////////////////////////////////////////////////////////////2086//2087// CProductsDialog2088//20892090bool CompareIntStringPairBestFirst(const pair<int, string>& item1, const pair<int, string>& item2)2091{2092    return (item1.first > item2.first);2093}20942095CProductsDialog::CProductsDialog(wxWindow* parent) : CProductsDialogBase(parent)2096{2097    // Init column headers2098    m_listCtrl->InsertColumn(0, "Title",  wxLIST_FORMAT_LEFT, 200);2099    m_listCtrl->InsertColumn(1, "Price",  wxLIST_FORMAT_LEFT, 80);2100    m_listCtrl->InsertColumn(2, "Seller", wxLIST_FORMAT_LEFT, 80);2101    m_listCtrl->InsertColumn(3, "Stars",  wxLIST_FORMAT_LEFT, 50);2102    m_listCtrl->InsertColumn(4, "Power",  wxLIST_FORMAT_LEFT, 50);21032104    // Tally top categories2105    map<string, int> mapTopCategories;2106    CRITICAL_BLOCK(cs_mapProducts)2107        for (map<uint256, CProduct>::iterator mi = mapProducts.begin(); mi != mapProducts.end(); ++mi)2108            mapTopCategories[(*mi).second.mapValue["category"]]++;21092110    // Sort top categories2111    vector<pair<int, string> > vTopCategories;2112    for (map<string, int>::iterator mi = mapTopCategories.begin(); mi != mapTopCategories.end(); ++mi)2113        vTopCategories.push_back(make_pair((*mi).second, (*mi).first));2114    sort(vTopCategories.begin(), vTopCategories.end(), CompareIntStringPairBestFirst);21152116    // Fill categories combo box2117    int nLimit = 250;2118    for (vector<pair<int, string> >::iterator it = vTopCategories.begin(); it != vTopCategories.end() && nLimit-- > 0; ++it)2119        m_comboBoxCategory->Append((*it).second);21202121    // Fill window with initial search2122    //wxCommandEvent event;2123    //OnButtonSearch(event);2124}21252126void CProductsDialog::OnCombobox(wxCommandEvent& event)2127{2128    OnButtonSearch(event);2129}21302131bool CompareProductsBestFirst(const CProduct* p1, const CProduct* p2)2132{2133    return (p1->nAtoms > p2->nAtoms);2134}21352136void CProductsDialog::OnButtonSearch(wxCommandEvent& event)2137{2138    string strCategory = (string)m_comboBoxCategory->GetValue();2139    string strSearch = (string)m_textCtrlSearch->GetValue();21402141    // Search products2142    vector<CProduct*> vProductsFound;2143    CRITICAL_BLOCK(cs_mapProducts)2144    {2145        for (map<uint256, CProduct>::iterator mi = mapProducts.begin(); mi != mapProducts.end(); ++mi)2146        {2147            CProduct& product = (*mi).second;2148            if (product.mapValue["category"].find(strCategory) != -1)2149            {2150                if (product.mapValue["title"].find(strSearch) != -1 ||2151                    product.mapValue["description"].find(strSearch) != -1 ||2152                    product.mapValue["seller"].find(strSearch) != -1)2153                {2154                    vProductsFound.push_back(&product);2155                }2156            }2157        }2158    }21592160    // Sort2161    sort(vProductsFound.begin(), vProductsFound.end(), CompareProductsBestFirst);21622163    // Display2164    foreach(CProduct* pproduct, vProductsFound)2165    {2166        InsertLine(m_listCtrl,2167                   pproduct->mapValue["title"],2168                   pproduct->mapValue["price"],2169                   pproduct->mapValue["seller"],2170                   pproduct->mapValue["stars"],2171                   itostr(pproduct->nAtoms));2172    }2173}21742175void CProductsDialog::OnListItemActivated(wxListEvent& event)2176{2177    // Doubleclick opens product2178    CViewProductDialog* pdialog = new CViewProductDialog(this, m_vProduct[event.GetIndex()]);2179    pdialog->Show();2180}21812182218321842185218621872188//////////////////////////////////////////////////////////////////////////////2189//2190// CEditProductDialog2191//21922193CEditProductDialog::CEditProductDialog(wxWindow* parent) : CEditProductDialogBase(parent)2194{2195    m_textCtrlLabel[0 ] = m_textCtrlLabel0;2196    m_textCtrlLabel[1 ] = m_textCtrlLabel1;2197    m_textCtrlLabel[2 ] = m_textCtrlLabel2;2198    m_textCtrlLabel[3 ] = m_textCtrlLabel3;2199    m_textCtrlLabel[4 ] = m_textCtrlLabel4;2200    m_textCtrlLabel[5 ] = m_textCtrlLabel5;2201    m_textCtrlLabel[6 ] = m_textCtrlLabel6;2202    m_textCtrlLabel[7 ] = m_textCtrlLabel7;2203    m_textCtrlLabel[8 ] = m_textCtrlLabel8;2204    m_textCtrlLabel[9 ] = m_textCtrlLabel9;2205    m_textCtrlLabel[10] = m_textCtrlLabel10;2206    m_textCtrlLabel[11] = m_textCtrlLabel11;2207    m_textCtrlLabel[12] = m_textCtrlLabel12;2208    m_textCtrlLabel[13] = m_textCtrlLabel13;2209    m_textCtrlLabel[14] = m_textCtrlLabel14;2210    m_textCtrlLabel[15] = m_textCtrlLabel15;2211    m_textCtrlLabel[16] = m_textCtrlLabel16;2212    m_textCtrlLabel[17] = m_textCtrlLabel17;2213    m_textCtrlLabel[18] = m_textCtrlLabel18;2214    m_textCtrlLabel[19] = m_textCtrlLabel19;22152216    m_textCtrlField[0 ] = m_textCtrlField0;2217    m_textCtrlField[1 ] = m_textCtrlField1;2218    m_textCtrlField[2 ] = m_textCtrlField2;2219    m_textCtrlField[3 ] = m_textCtrlField3;2220    m_textCtrlField[4 ] = m_textCtrlField4;2221    m_textCtrlField[5 ] = m_textCtrlField5;2222    m_textCtrlField[6 ] = m_textCtrlField6;2223    m_textCtrlField[7 ] = m_textCtrlField7;2224    m_textCtrlField[8 ] = m_textCtrlField8;2225    m_textCtrlField[9 ] = m_textCtrlField9;2226    m_textCtrlField[10] = m_textCtrlField10;2227    m_textCtrlField[11] = m_textCtrlField11;2228    m_textCtrlField[12] = m_textCtrlField12;2229    m_textCtrlField[13] = m_textCtrlField13;2230    m_textCtrlField[14] = m_textCtrlField14;2231    m_textCtrlField[15] = m_textCtrlField15;2232    m_textCtrlField[16] = m_textCtrlField16;2233    m_textCtrlField[17] = m_textCtrlField17;2234    m_textCtrlField[18] = m_textCtrlField18;2235    m_textCtrlField[19] = m_textCtrlField19;22362237    m_buttonDel[0 ] = m_buttonDel0;2238    m_buttonDel[1 ] = m_buttonDel1;2239    m_buttonDel[2 ] = m_buttonDel2;2240    m_buttonDel[3 ] = m_buttonDel3;2241    m_buttonDel[4 ] = m_buttonDel4;2242    m_buttonDel[5 ] = m_buttonDel5;2243    m_buttonDel[6 ] = m_buttonDel6;2244    m_buttonDel[7 ] = m_buttonDel7;2245    m_buttonDel[8 ] = m_buttonDel8;2246    m_buttonDel[9 ] = m_buttonDel9;2247    m_buttonDel[10] = m_buttonDel10;2248    m_buttonDel[11] = m_buttonDel11;2249    m_buttonDel[12] = m_buttonDel12;2250    m_buttonDel[13] = m_buttonDel13;2251    m_buttonDel[14] = m_buttonDel14;2252    m_buttonDel[15] = m_buttonDel15;2253    m_buttonDel[16] = m_buttonDel16;2254    m_buttonDel[17] = m_buttonDel17;2255    m_buttonDel[18] = m_buttonDel18;2256    m_buttonDel[19] = m_buttonDel19;22572258    for (int i = 1; i < FIELDS_MAX; i++)2259        ShowLine(i, false);22602261    LayoutAll();2262}22632264void CEditProductDialog::LayoutAll()2265{2266    m_scrolledWindow->Layout();2267    m_scrolledWindow->GetSizer()->Fit(m_scrolledWindow);2268    this->Layout();2269}22702271void CEditProductDialog::ShowLine(int i, bool fShow)2272{2273    m_textCtrlLabel[i]->Show(fShow);2274    m_textCtrlField[i]->Show(fShow);2275    m_buttonDel[i]->Show(fShow);2276}22772278void CEditProductDialog::OnButtonDel0(wxCommandEvent& event)  { OnButtonDel(event, 0); }2279void CEditProductDialog::OnButtonDel1(wxCommandEvent& event)  { OnButtonDel(event, 1); }2280void CEditProductDialog::OnButtonDel2(wxCommandEvent& event)  { OnButtonDel(event, 2); }2281void CEditProductDialog::OnButtonDel3(wxCommandEvent& event)  { OnButtonDel(event, 3); }2282void CEditProductDialog::OnButtonDel4(wxCommandEvent& event)  { OnButtonDel(event, 4); }2283void CEditProductDialog::OnButtonDel5(wxCommandEvent& event)  { OnButtonDel(event, 5); }2284void CEditProductDialog::OnButtonDel6(wxCommandEvent& event)  { OnButtonDel(event, 6); }2285void CEditProductDialog::OnButtonDel7(wxCommandEvent& event)  { OnButtonDel(event, 7); }2286void CEditProductDialog::OnButtonDel8(wxCommandEvent& event)  { OnButtonDel(event, 8); }2287void CEditProductDialog::OnButtonDel9(wxCommandEvent& event)  { OnButtonDel(event, 9); }2288void CEditProductDialog::OnButtonDel10(wxCommandEvent& event) { OnButtonDel(event, 10); }2289void CEditProductDialog::OnButtonDel11(wxCommandEvent& event) { OnButtonDel(event, 11); }2290void CEditProductDialog::OnButtonDel12(wxCommandEvent& event) { OnButtonDel(event, 12); }2291void CEditProductDialog::OnButtonDel13(wxCommandEvent& event) { OnButtonDel(event, 13); }2292void CEditProductDialog::OnButtonDel14(wxCommandEvent& event) { OnButtonDel(event, 14); }2293void CEditProductDialog::OnButtonDel15(wxCommandEvent& event) { OnButtonDel(event, 15); }2294void CEditProductDialog::OnButtonDel16(wxCommandEvent& event) { OnButtonDel(event, 16); }2295void CEditProductDialog::OnButtonDel17(wxCommandEvent& event) { OnButtonDel(event, 17); }2296void CEditProductDialog::OnButtonDel18(wxCommandEvent& event) { OnButtonDel(event, 18); }2297void CEditProductDialog::OnButtonDel19(wxCommandEvent& event) { OnButtonDel(event, 19); }22982299void CEditProductDialog::OnButtonDel(wxCommandEvent& event, int n)2300{2301    Freeze();2302    int x, y;2303    m_scrolledWindow->GetViewStart(&x, &y);2304    int i;2305    for (i = n; i < FIELDS_MAX-1; i++)2306    {2307        m_textCtrlLabel[i]->SetValue(m_textCtrlLabel[i+1]->GetValue());2308        m_textCtrlField[i]->SetValue(m_textCtrlField[i+1]->GetValue());2309        if (!m_buttonDel[i+1]->IsShown())2310            break;2311    }2312    m_textCtrlLabel[i]->SetValue("");2313    m_textCtrlField[i]->SetValue("");2314    ShowLine(i, false);2315    m_buttonAddField->Enable(true);2316    LayoutAll();2317    m_scrolledWindow->Scroll(0, y);2318    Thaw();2319}23202321void CEditProductDialog::OnButtonAddField(wxCommandEvent& event)2322{2323    for (int i = 0; i < FIELDS_MAX; i++)2324    {2325        if (!m_buttonDel[i]->IsShown())2326        {2327            Freeze();2328            ShowLine(i, true);2329            if (i == FIELDS_MAX-1)2330                m_buttonAddField->Enable(false);2331            LayoutAll();2332            m_scrolledWindow->Scroll(0, 99999);2333            Thaw();2334            break;2335        }2336    }2337}23382339void CEditProductDialog::OnButtonSend(wxCommandEvent& event)2340{2341    CProduct product;2342    GetProduct(product);23432344    // Sign the detailed product2345    product.vchPubKeyFrom = keyUser.GetPubKey();2346    if (!keyUser.Sign(product.GetSigHash(), product.vchSig))2347    {2348        wxMessageBox("Error digitally signing the product  ");2349        return;2350    }23512352    // Save detailed product2353    AddToMyProducts(product);23542355    // Strip down to summary product2356    product.mapDetails.clear();2357    product.vOrderForm.clear();23582359    // Sign the summary product2360    if (!keyUser.Sign(product.GetSigHash(), product.vchSig))2361    {2362        wxMessageBox("Error digitally signing the product  ");2363        return;2364    }23652366    // Verify2367    if (!product.CheckProduct())2368    {2369        wxMessageBox("Errors found in product  ");2370        return;2371    }23722373    // Broadcast2374    AdvertStartPublish(pnodeLocalHost, MSG_PRODUCT, 0, product);23752376    Destroy();2377}23782379void CEditProductDialog::OnButtonPreview(wxCommandEvent& event)2380{2381    CProduct product;2382    GetProduct(product);2383    CViewProductDialog* pdialog = new CViewProductDialog(this, product);2384    pdialog->Show();2385}23862387void CEditProductDialog::OnButtonCancel(wxCommandEvent& event)2388{2389    Destroy();2390}23912392void CEditProductDialog::SetProduct(const CProduct& productIn)2393{2394    CProduct product = productIn;23952396    m_comboBoxCategory->SetValue(product.mapValue["category"]);2397    m_textCtrlTitle->SetValue(product.mapValue["title"]);2398    m_textCtrlPrice->SetValue(product.mapValue["price"]);2399    m_textCtrlDescription->SetValue(product.mapValue["description"]);2400    m_textCtrlInstructions->SetValue(product.mapValue["instructions"]);24012402    for (int i = 0; i < FIELDS_MAX; i++)2403    {2404        bool fUsed = i < product.vOrderForm.size();2405        m_buttonDel[i]->Show(fUsed);2406        m_textCtrlLabel[i]->Show(fUsed);2407        m_textCtrlField[i]->Show(fUsed);2408        if (!fUsed)2409            continue;24102411        m_textCtrlLabel[i]->SetValue(product.vOrderForm[i].first);2412        string strControl = product.vOrderForm[i].second;2413        if (strControl.substr(0, 5) == "text=")2414            m_textCtrlField[i]->SetValue("");2415        else if (strControl.substr(0, 7) == "choice=")2416            m_textCtrlField[i]->SetValue(strControl.substr(7));2417        else2418            m_textCtrlField[i]->SetValue(strControl);2419    }2420}24212422void CEditProductDialog::GetProduct(CProduct& product)2423{2424    // map<string, string> mapValue;2425    // vector<pair<string, string> > vOrderForm;24262427    product.mapValue["category"]     = m_comboBoxCategory->GetValue().Trim();2428    product.mapValue["title"]        = m_textCtrlTitle->GetValue().Trim();2429    product.mapValue["price"]        = m_textCtrlPrice->GetValue().Trim();2430    product.mapValue["description"]  = m_textCtrlDescription->GetValue().Trim();2431    product.mapValue["instructions"] = m_textCtrlInstructions->GetValue().Trim();24322433    for (int i = 0; i < FIELDS_MAX; i++)2434    {2435        if (m_buttonDel[i]->IsShown())2436        {2437            string strLabel = (string)m_textCtrlLabel[i]->GetValue().Trim();2438            string strControl = (string)m_textCtrlField[i]->GetValue();2439            if (strControl.empty())2440                strControl = "text=";2441            else2442                strControl = "choice=" + strControl;2443            product.vOrderForm.push_back(make_pair(strLabel, strControl));2444        }2445    }2446}24472448244924502451245224532454//////////////////////////////////////////////////////////////////////////////2455//2456// CViewProductDialog2457//24582459CViewProductDialog::CViewProductDialog(wxWindow* parent, const CProduct& productIn) : CViewProductDialogBase(parent)2460{2461    Connect(wxEVT_REPLY1, wxCommandEventHandler(CViewProductDialog::OnReply1), NULL, this);2462    AddCallbackAvailable(GetEventHandler());24632464    // Fill display with product summary while waiting for details2465    product = productIn;2466    UpdateProductDisplay(false);24672468    m_buttonBack->Enable(false);2469    m_buttonNext->Enable(!product.vOrderForm.empty());2470    m_htmlWinReviews->Show(true);2471    m_scrolledWindow->Show(false);2472    this->Layout();24732474    // Request details from seller2475    _beginthread(ThreadRequestProductDetails, 0, new pair<CProduct, wxEvtHandler*>(product, GetEventHandler()));2476}24772478CViewProductDialog::~CViewProductDialog()2479{2480    RemoveCallbackAvailable(GetEventHandler());2481}24822483void ThreadRequestProductDetails(void* parg)2484{2485    // Extract parameters2486    pair<CProduct, wxEvtHandler*>* pitem = (pair<CProduct, wxEvtHandler*>*)parg;2487    CProduct product = pitem->first;2488    wxEvtHandler* pevthandler = pitem->second;2489    delete pitem;24902491    // Connect to seller2492    CNode* pnode = ConnectNode(product.addr, 5 * 60);2493    if (!pnode)2494    {2495        CDataStream ssEmpty;2496        AddPendingReplyEvent1(pevthandler, ssEmpty);2497        return;2498    }24992500    // Request detailed product, with response going to OnReply1 via dialog's event handler2501    pnode->PushRequest("getdetails", product.GetHash(), AddPendingReplyEvent1, (void*)pevthandler);2502}25032504void CViewProductDialog::OnReply1(wxCommandEvent& event)2505{2506    CDataStream ss = GetStreamFromEvent(event);2507    if (ss.empty())2508    {2509        product.mapValue["description"] = "-- CAN'T CONNECT TO SELLER --\n";2510        UpdateProductDisplay(true);2511        return;2512    }25132514    int nRet;2515    CProduct product2;2516    try2517    {2518        ss >> nRet;2519        if (nRet > 0)2520            throw false;2521        ss >> product2;2522        if (product2.GetHash() != product.GetHash())2523            throw false;2524        if (!product2.CheckSignature())2525            throw false;2526    }2527    catch (...)2528    {2529        product.mapValue["description"] = "-- INVALID RESPONSE --\n";2530        UpdateProductDisplay(true);2531        return;2532    }25332534    product = product2;2535    UpdateProductDisplay(true);2536}25372538bool CompareReviewsBestFirst(const CReview* p1, const CReview* p2)2539{2540    return (p1->nAtoms > p2->nAtoms);2541}25422543void CViewProductDialog::UpdateProductDisplay(bool fDetails)2544{2545    // Product and reviews2546    string strHTML;2547    strHTML.reserve(4000);2548    strHTML += "<html>\n"2549               "<head>\n"2550               "<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">\n"2551               "</head>\n"2552               "<body>\n";2553    strHTML += "<b>Category:</b> " + HtmlEscape(product.mapValue["category"]) + "<br>\n";2554    strHTML += "<b>Title:</b> "    + HtmlEscape(product.mapValue["title"])    + "<br>\n";2555    strHTML += "<b>Price:</b> "    + HtmlEscape(product.mapValue["price"])    + "<br>\n";25562557    if (!fDetails)2558        strHTML += "<b>Loading details...</b><br>\n<br>\n";2559    else2560        strHTML += HtmlEscape(product.mapValue["description"], true) + "<br>\n<br>\n";25612562    strHTML += "<b>Reviews:</b><br>\n<br>\n";25632564    if (!product.vchPubKeyFrom.empty())2565    {2566        CReviewDB reviewdb("r");25672568        // Get reviews2569        vector<CReview> vReviews;2570        reviewdb.ReadReviews(product.GetUserHash(), vReviews);25712572        // Get reviewer's number of atoms2573        vector<CReview*> vSortedReviews;2574        vSortedReviews.reserve(vReviews.size());2575        for (vector<CReview>::reverse_iterator it = vReviews.rbegin(); it != vReviews.rend(); ++it)2576        {2577            CReview& review = *it;2578            CUser user;2579            reviewdb.ReadUser(review.GetUserHash(), user);2580            review.nAtoms = user.GetAtomCount();2581            vSortedReviews.push_back(&review);2582        }25832584        reviewdb.Close();25852586        // Sort2587        stable_sort(vSortedReviews.begin(), vSortedReviews.end(), CompareReviewsBestFirst);25882589        // Format reviews2590        foreach(CReview* preview, vSortedReviews)2591        {2592            CReview& review = *preview;2593            int nStars = atoi(review.mapValue["stars"].c_str());2594            if (nStars < 1 || nStars > 5)2595                continue;25962597            strHTML += "<b>" + itostr(nStars) + (nStars == 1 ? " star" : " stars") + "</b>";2598            strHTML += " &nbsp;&nbsp;&nbsp; ";2599            strHTML += DateStr(atoi64(review.mapValue["date"])) + "<br>\n";2600            strHTML += HtmlEscape(review.mapValue["review"], true);2601            strHTML += "<br>\n<br>\n";2602        }2603    }26042605    strHTML += "</body>\n</html>\n";26062607    // Shrink capacity to fit2608    string(strHTML.begin(), strHTML.end()).swap(strHTML);26092610    m_htmlWinReviews->SetPage(strHTML);26112612    ///// need to find some other indicator to use so can allow empty order form2613    if (product.vOrderForm.empty())2614        return;26152616    // Order form2617    m_staticTextInstructions->SetLabel(product.mapValue["instructions"]);2618    for (int i = 0; i < FIELDS_MAX; i++)2619    {2620        m_staticTextLabel[i] = NULL;2621        m_textCtrlField[i] = NULL;2622        m_choiceField[i] = NULL;2623    }26242625    // Construct flexgridsizer2626    wxBoxSizer* bSizer21 = (wxBoxSizer*)m_scrolledWindow->GetSizer();2627    wxFlexGridSizer* fgSizer;2628    fgSizer = new wxFlexGridSizer(0, 2, 0, 0);2629    fgSizer->AddGrowableCol(1);2630    fgSizer->SetFlexibleDirection(wxBOTH);2631    fgSizer->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED);26322633    // Construct order form fields2634    wxWindow* windowLast = NULL;2635    for (int i = 0; i < product.vOrderForm.size(); i++)2636    {2637        string strLabel = product.vOrderForm[i].first;2638        string strControl = product.vOrderForm[i].second;26392640        if (strLabel.size() < 20)2641            strLabel.insert(strLabel.begin(), 20 - strLabel.size(), ' ');26422643        m_staticTextLabel[i] = new wxStaticText(m_scrolledWindow, wxID_ANY, strLabel, wxDefaultPosition, wxDefaultSize, wxALIGN_RIGHT);2644        m_staticTextLabel[i]->Wrap(-1);2645        fgSizer->Add(m_staticTextLabel[i], 0, wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxALL, 5);26462647        if (strControl.substr(0, 5) == "text=")2648        {2649            m_textCtrlField[i] = new wxTextCtrl(m_scrolledWindow, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0);2650            fgSizer->Add(m_textCtrlField[i], 1, wxALL|wxALIGN_CENTER_VERTICAL|wxEXPAND, 5);2651            windowLast = m_textCtrlField[i];2652        }2653        else if (strControl.substr(0, 7) == "choice=")2654        {2655            vector<string> vChoices;2656            ParseString(strControl.substr(7), ',', vChoices);26572658            wxArrayString arraystring;2659            foreach(const string& str, vChoices)2660                arraystring.Add(str);26612662            m_choiceField[i] = new wxChoice(m_scrolledWindow, wxID_ANY, wxDefaultPosition, wxDefaultSize, arraystring, 0);2663            fgSizer->Add(m_choiceField[i], 0, wxALL|wxALIGN_CENTER_VERTICAL, 5);2664            windowLast = m_choiceField[i];2665        }2666        else2667        {2668            m_textCtrlField[i] = new wxTextCtrl(m_scrolledWindow, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0);2669            fgSizer->Add(m_textCtrlField[i], 1, wxALL|wxALIGN_CENTER_VERTICAL|wxEXPAND, 5);2670            m_staticTextLabel[i]->Show(false);2671            m_textCtrlField[i]->Show(false);2672        }2673    }26742675    // Insert after instructions and before submit/cancel buttons2676    bSizer21->Insert(2, fgSizer, 0, wxEXPAND|wxRIGHT|wxLEFT, 5);2677    m_scrolledWindow->Layout();2678    bSizer21->Fit(m_scrolledWindow);2679    this->Layout();26802681    // Fixup the tab order2682    m_buttonSubmitForm->MoveAfterInTabOrder(windowLast);2683    m_buttonCancelForm->MoveAfterInTabOrder(m_buttonSubmitForm);2684    //m_buttonBack->MoveAfterInTabOrder(m_buttonCancelForm);2685    //m_buttonNext->MoveAfterInTabOrder(m_buttonBack);2686    //m_buttonCancel->MoveAfterInTabOrder(m_buttonNext);2687    this->Layout();2688}26892690void CViewProductDialog::GetOrder(CWalletTx& wtx)2691{2692    wtx.SetNull();2693    for (int i = 0; i < product.vOrderForm.size(); i++)2694    {2695        string strValue;2696        if (m_textCtrlField[i])2697            strValue = m_textCtrlField[i]->GetValue().Trim();2698        else2699            strValue = m_choiceField[i]->GetStringSelection();2700        wtx.vOrderForm.push_back(make_pair(m_staticTextLabel[i]->GetLabel(), strValue));2701    }2702}27032704void CViewProductDialog::OnButtonSubmitForm(wxCommandEvent& event)2705{2706    m_buttonSubmitForm->Enable(false);2707    m_buttonCancelForm->Enable(false);27082709    CWalletTx wtx;2710    GetOrder(wtx);27112712    CSendingDialog* pdialog = new CSendingDialog(this, product.addr, atoi64(product.mapValue["price"]), wtx);2713    if (!pdialog->ShowModal())2714    {2715        m_buttonSubmitForm->Enable(true);2716        m_buttonCancelForm->Enable(true);2717        return;2718    }2719}27202721void CViewProductDialog::OnButtonCancelForm(wxCommandEvent& event)2722{2723    Destroy();2724}27252726void CViewProductDialog::OnButtonBack(wxCommandEvent& event)2727{2728    Freeze();2729    m_htmlWinReviews->Show(true);2730    m_scrolledWindow->Show(false);2731    m_buttonBack->Enable(false);2732    m_buttonNext->Enable(!product.vOrderForm.empty());2733    this->Layout();2734    Thaw();2735}27362737void CViewProductDialog::OnButtonNext(wxCommandEvent& event)2738{2739    if (!product.vOrderForm.empty())2740    {2741        Freeze();2742        m_htmlWinReviews->Show(false);2743        m_scrolledWindow->Show(true);2744        m_buttonBack->Enable(true);2745        m_buttonNext->Enable(false);2746        this->Layout();2747        Thaw();2748    }2749}27502751void CViewProductDialog::OnButtonCancel(wxCommandEvent& event)2752{2753    Destroy();2754}27552756275727582759276027612762//////////////////////////////////////////////////////////////////////////////2763//2764// CViewOrderDialog2765//27662767CViewOrderDialog::CViewOrderDialog(wxWindow* parent, CWalletTx order, bool fReceived) : CViewOrderDialogBase(parent)2768{2769    int64 nPrice = (fReceived ? order.GetCredit() : order.GetDebit());27702771    string strHTML;2772    strHTML.reserve(4000);2773    strHTML += "<html>\n"2774               "<head>\n"2775               "<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">\n"2776               "</head>\n"2777               "<body>\n";2778    strHTML += "<b>Time:</b> "   + HtmlEscape(DateTimeStr(order.nTimeReceived)) + "<br>\n";2779    strHTML += "<b>Price:</b> "  + HtmlEscape(FormatMoney(nPrice)) + "<br>\n";2780    strHTML += "<b>Status:</b> " + HtmlEscape(FormatTxStatus(order)) + "<br>\n";27812782    strHTML += "<table>\n";2783    for (int i = 0; i < order.vOrderForm.size(); i++)2784    {2785        strHTML += " <tr><td><b>" + HtmlEscape(order.vOrderForm[i].first) + ":</b></td>";2786        strHTML += "<td>" + HtmlEscape(order.vOrderForm[i].second) + "</td></tr>\n";2787    }2788    strHTML += "</table>\n";27892790    strHTML += "</body>\n</html>\n";27912792    // Shrink capacity to fit2793    // (strings are ref counted, so it may live on in SetPage)2794    string(strHTML.begin(), strHTML.end()).swap(strHTML);27952796    m_htmlWin->SetPage(strHTML);2797}27982799void CViewOrderDialog::OnButtonOK(wxCommandEvent& event)2800{2801    Destroy();2802}28032804280528062807280828092810//////////////////////////////////////////////////////////////////////////////2811//2812// CEditReviewDialog2813//28142815CEditReviewDialog::CEditReviewDialog(wxWindow* parent) : CEditReviewDialogBase(parent)2816{2817}28182819void CEditReviewDialog::OnButtonSubmit(wxCommandEvent& event)2820{2821    if (m_choiceStars->GetSelection() == -1)2822    {2823        wxMessageBox("Please select a rating  ");2824        return;2825    }28262827    CReview review;2828    GetReview(review);28292830    // Sign the review2831    review.vchPubKeyFrom = keyUser.GetPubKey();2832    if (!keyUser.Sign(review.GetSigHash(), review.vchSig))2833    {2834        wxMessageBox("Unable to digitally sign the review  ");2835        return;2836    }28372838    // Broadcast2839    if (!review.AcceptReview())2840    {2841        wxMessageBox("Save failed  ");2842        return;2843    }2844    RelayMessage(CInv(MSG_REVIEW, review.GetHash()), review);28452846    Destroy();2847}28482849void CEditReviewDialog::OnButtonCancel(wxCommandEvent& event)2850{2851    Destroy();2852}28532854void CEditReviewDialog::GetReview(CReview& review)2855{2856    review.mapValue["time"]   = i64tostr(GetAdjustedTime());2857    review.mapValue["stars"]  = itostr(m_choiceStars->GetSelection()+1);2858    review.mapValue["review"] = m_textCtrlReview->GetValue();2859}2860286128622863286428652866286728682869287028712872//////////////////////////////////////////////////////////////////////////////2873//2874// CMyApp2875//28762877// Define a new application2878class CMyApp: public wxApp2879{2880  public:2881    CMyApp(){};2882    ~CMyApp(){};2883    bool OnInit();2884    bool OnInit2();2885    int OnExit();28862887    // 2nd-level exception handling: we get all the exceptions occurring in any2888    // event handler here2889    virtual bool OnExceptionInMainLoop();28902891    // 3rd, and final, level exception handling: whenever an unhandled2892    // exception is caught, this function is called2893    virtual void OnUnhandledException();28942895    // and now for something different: this function is called in case of a2896    // crash (e.g. dereferencing null pointer, division by 0, ...)2897    virtual void OnFatalException();2898};28992900IMPLEMENT_APP(CMyApp)29012902bool CMyApp::OnInit()2903{2904    try2905    {2906        return OnInit2();2907    }2908    catch (std::exception& e) {2909        PrintException(&e, "OnInit()");2910    } catch (...) {2911        PrintException(NULL, "OnInit()");2912    }2913    return false;2914}29152916map<string, string> ParseParameters(int argc, char* argv[])2917{2918    map<string, string> mapArgs;2919    for (int i = 0; i < argc; i++)2920    {2921        char psz[10000];2922        strcpy(psz, argv[i]);2923        char* pszValue = "";2924        if (strchr(psz, '='))2925        {2926            pszValue = strchr(psz, '=');2927            *pszValue++ = '\0';2928        }2929        strlwr(psz);2930        if (psz[0] == '-')2931            psz[0] = '/';2932        mapArgs[psz] = pszValue;2933    }2934    return mapArgs;2935}29362937bool CMyApp::OnInit2()2938{2939#ifdef _MSC_VER2940    // Turn off microsoft heap dump noise for now2941    _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);2942    _CrtSetReportFile(_CRT_WARN, CreateFile("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));2943#endif2944#ifdef __WXDEBUG__2945    // Disable malfunctioning wxWidgets debug assertion2946    g_isPainting = 10000;2947#endif29482949    //// debug print2950    printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");2951    printf("Bitcoin version %d, Windows version %08x\n", VERSION, GetVersion());29522953    //2954    // Limit to single instance per user2955    // Required to protect the database files if we're going to keep deleting log.*2956    //2957    wxString strMutexName = wxString("Bitcoin.") + getenv("HOMEPATH");2958    for (int i = 0; i < strMutexName.size(); i++)2959        if (!isalnum(strMutexName[i]))2960            strMutexName[i] = '.';2961    wxSingleInstanceChecker* psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);2962    if (psingleinstancechecker->IsAnotherRunning())2963    {2964        printf("Existing instance found\n");2965        unsigned int nStart = GetTime();2966        loop2967        {2968            // Show the previous instance and exit2969            HWND hwndPrev = FindWindow("wxWindowClassNR", "Bitcoin");2970            if (hwndPrev)2971            {2972                if (IsIconic(hwndPrev))2973                    ShowWindow(hwndPrev, SW_RESTORE);2974                SetForegroundWindow(hwndPrev);2975                return false;2976            }29772978            if (GetTime() > nStart + 60)2979                return false;29802981            // Resume this instance if the other exits2982            delete psingleinstancechecker;2983            Sleep(1000);2984            psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);2985            if (!psingleinstancechecker->IsAnotherRunning())2986                break;2987        }2988    }29892990    //2991    // Parameters2992    //2993    wxImage::AddHandler(new wxPNGHandler);2994    map<string, string> mapArgs = ParseParameters(argc, argv);29952996    if (mapArgs.count("/datadir"))2997        strSetDataDir = mapArgs["/datadir"];29982999    if (mapArgs.count("/proxy"))3000        addrProxy = CAddress(mapArgs["/proxy"].c_str());30013002    if (mapArgs.count("/debug"))3003        fDebug = true;30043005    if (mapArgs.count("/dropmessages"))3006    {3007        nDropMessagesTest = atoi(mapArgs["/dropmessages"]);3008        if (nDropMessagesTest == 0)3009            nDropMessagesTest = 20;3010    }30113012    if (mapArgs.count("/loadblockindextest"))3013    {3014        CTxDB txdb("r");3015        txdb.LoadBlockIndex();3016        PrintBlockTree();3017        ExitProcess(0);3018    }30193020    //3021    // Load data files3022    //3023    string strErrors;3024    int64 nStart, nEnd;30253026    printf("Loading addresses...\n");3027    QueryPerformanceCounter((LARGE_INTEGER*)&nStart);3028    if (!LoadAddresses())3029        strErrors += "Error loading addr.dat      \n";3030    QueryPerformanceCounter((LARGE_INTEGER*)&nEnd);3031    printf(" addresses   %20I64d\n", nEnd - nStart);30323033    printf("Loading block index...\n");3034    QueryPerformanceCounter((LARGE_INTEGER*)&nStart);3035    if (!LoadBlockIndex())3036        strErrors += "Error loading blkindex.dat      \n";3037    QueryPerformanceCounter((LARGE_INTEGER*)&nEnd);3038    printf(" block index %20I64d\n", nEnd - nStart);30393040    printf("Loading wallet...\n");3041    QueryPerformanceCounter((LARGE_INTEGER*)&nStart);3042    if (!LoadWallet())3043        strErrors += "Error loading wallet.dat      \n";3044    QueryPerformanceCounter((LARGE_INTEGER*)&nEnd);3045    printf(" wallet      %20I64d\n", nEnd - nStart);30463047    printf("Done loading\n");30483049        //// debug print3050        printf("mapBlockIndex.size() = %d\n",   mapBlockIndex.size());3051        printf("nBestHeight = %d\n",            nBestHeight);3052        printf("mapKeys.size() = %d\n",         mapKeys.size());3053        printf("mapPubKeys.size() = %d\n",      mapPubKeys.size());3054        printf("mapWallet.size() = %d\n",       mapWallet.size());3055        printf("mapAddressBook.size() = %d\n",  mapAddressBook.size());30563057    if (!strErrors.empty())3058    {3059        wxMessageBox(strErrors, "Bitcoin");3060        OnExit();3061        return false;3062    }30633064    // Add wallet transactions that aren't already in a block to mapTransactions3065    ReacceptWalletTransactions();30663067    //3068    // Parameters3069    //3070    if (mapArgs.count("/printblockindex") || mapArgs.count("/printblocktree"))3071    {3072        PrintBlockTree();3073        OnExit();3074        return false;3075    }30763077    if (mapArgs.count("/gen"))3078    {3079        if (mapArgs["/gen"].empty())3080            fGenerateBitcoins = true;3081        else3082            fGenerateBitcoins = atoi(mapArgs["/gen"].c_str());3083    }30843085    //3086    // Create the main frame window3087    //3088    {3089        pframeMain = new CMainFrame(NULL);3090        pframeMain->Show();30913092        if (!CheckDiskSpace())3093        {3094            OnExit();3095            return false;3096        }30973098        if (!StartNode(strErrors))3099            wxMessageBox(strErrors, "Bitcoin");31003101        if (fGenerateBitcoins)3102            if (_beginthread(ThreadBitcoinMiner, 0, NULL) == -1)3103                printf("Error: _beginthread(ThreadBitcoinMiner) failed\n");31043105        //3106        // Tests3107        //3108        if (argc >= 2 && stricmp(argv[1], "/send") == 0)3109        {3110            int64 nValue = 1;3111            if (argc >= 3)3112                ParseMoney(argv[2], nValue);31133114            string strAddress;3115            if (argc >= 4)3116                strAddress = argv[3];3117            CAddress addr(strAddress.c_str());31183119            CWalletTx wtx;3120            wtx.mapValue["to"] = strAddress;3121            wtx.mapValue["from"] = addrLocalHost.ToString();3122            wtx.mapValue["message"] = "command line send";31233124            // Send to IP address3125            CSendingDialog* pdialog = new CSendingDialog(pframeMain, addr, nValue, wtx);3126            if (!pdialog->ShowModal())3127                return false;3128        }31293130        if (mapArgs.count("/randsendtest"))3131        {3132            if (!mapArgs["/randsendtest"].empty())3133                _beginthread(ThreadRandSendTest, 0, new string(mapArgs["/randsendtest"]));3134            else3135                fRandSendTest = true;3136            fDebug = true;3137        }3138    }31393140    return true;3141}31423143int CMyApp::OnExit()3144{3145    Shutdown(NULL);3146    return wxApp::OnExit();3147}31483149bool CMyApp::OnExceptionInMainLoop()3150{3151    try3152    {3153        throw;3154    }3155    catch (std::exception& e)3156    {3157        PrintException(&e, "CMyApp::OnExceptionInMainLoop()");3158        wxLogWarning(_T("Exception %s %s"), typeid(e).name(), e.what());3159        Sleep(1000);3160        throw;3161    }3162    catch (...)3163    {3164        PrintException(NULL, "CMyApp::OnExceptionInMainLoop()");3165        wxLogWarning(_T("Unknown exception"));3166        Sleep(1000);3167        throw;3168    }31693170    return true;3171}31723173void CMyApp::OnUnhandledException()3174{3175    // this shows how we may let some exception propagate uncaught3176    try3177    {3178        throw;3179    }3180    catch (std::exception& e)3181    {3182        PrintException(&e, "CMyApp::OnUnhandledException()");3183        wxLogWarning(_T("Exception %s %s"), typeid(e).name(), e.what());3184        Sleep(1000);3185        throw;3186    }3187    catch (...)3188    {3189        PrintException(NULL, "CMyApp::OnUnhandledException()");3190        wxLogWarning(_T("Unknown exception"));3191        Sleep(1000);3192        throw;3193    }3194}31953196void CMyApp::OnFatalException()3197{3198    wxMessageBox("Program has crashed and will terminate.  ", "Bitcoin", wxOK | wxICON_ERROR);3199}3200320132023203void MainFrameRepaint()3204{3205    if (pframeMain)3206    {3207        printf("MainFrameRepaint()\n");3208        wxPaintEvent event;3209        pframeMain->Refresh();3210        pframeMain->AddPendingEvent(event);3211    }3212}32133214321532163217321832193220// randsendtest to bitcoin address3221void ThreadRandSendTest(void* parg)3222{3223    string strAddress = *(string*)parg;3224    uint160 hash160;3225    if (!AddressToHash160(strAddress, hash160))3226    {3227        wxMessageBox(strprintf("ThreadRandSendTest: Bitcoin address '%s' not valid  ", strAddress.c_str()));3228        return;3229    }32303231    loop3232    {3233        Sleep(GetRand(30) * 1000 + 100);32343235        // Message3236        CWalletTx wtx;3237        wtx.mapValue["to"] = strAddress;3238        wtx.mapValue["from"] = addrLocalHost.ToString();3239        static int nRep;3240        wtx.mapValue["message"] = strprintf("randsendtest %d\n", ++nRep);32413242        // Value3243        int64 nValue = (GetRand(9) + 1) * 100 * CENT;3244        if (GetBalance() < nValue)3245        {3246            wxMessageBox("Out of money  ");3247            return;3248        }3249        nValue += (nRep % 100) * CENT;32503251        // Send to bitcoin address3252        CScript scriptPubKey;3253        scriptPubKey << OP_DUP << OP_HASH160 << hash160 << OP_EQUALVERIFY << OP_CHECKSIG;32543255        if (!SendMoney(scriptPubKey, nValue, wtx))3256            return;3257    }3258}325932603261// randsendtest to any connected node3262void RandSend()3263{3264    CWalletTx wtx;32653266    while (vNodes.empty())3267        Sleep(1000);3268    CAddress addr;3269    CRITICAL_BLOCK(cs_vNodes)3270        addr = vNodes[GetRand(vNodes.size())]->addr;32713272    // Message3273    wtx.mapValue["to"] = addr.ToString();3274    wtx.mapValue["from"] = addrLocalHost.ToString();3275    static int nRep;3276    wtx.mapValue["message"] = strprintf("randsendtest %d\n", ++nRep);32773278    // Value3279    int64 nValue = (GetRand(999) + 1) * CENT;3280    if (GetBalance() < nValue)3281    {3282        wxMessageBox("Out of money  ");3283        return;3284    }32853286    // Send to IP address3287    CSendingDialog* pdialog = new CSendingDialog(pframeMain, addr, nValue, wtx);3288    if (!pdialog->Show())3289        wxMessageBox("ShowModal Failed  ");3290}

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