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.2.0 · 2009-12-16

ui.cpp

3,940 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#endif910void ThreadRequestProductDetails(void* parg);11void ThreadRandSendTest(void* parg);12bool GetStartOnSystemStartup();13void SetStartOnSystemStartup(bool fAutoStart);14151617DEFINE_EVENT_TYPE(wxEVT_UITHREADCALL)18DEFINE_EVENT_TYPE(wxEVT_REPLY1)19DEFINE_EVENT_TYPE(wxEVT_REPLY2)20DEFINE_EVENT_TYPE(wxEVT_REPLY3)2122CMainFrame* pframeMain = NULL;23CMyTaskBarIcon* ptaskbaricon = NULL;24map<string, string> mapAddressBook;25bool fRandSendTest = false;26void RandSend();27extern int g_isPainting;28bool fClosedToTray = false;2930// Settings31int fShowGenerated = true;32int fMinimizeToTray = true;33int fMinimizeOnClose = true;3435363738394041//////////////////////////////////////////////////////////////////////////////42//43// Util44//4546void HandleCtrlA(wxKeyEvent& event)47{48    // Ctrl-a select all49    wxTextCtrl* textCtrl = (wxTextCtrl*)event.GetEventObject();50    if (event.GetModifiers() == wxMOD_CONTROL && event.GetKeyCode() == 'A')51        textCtrl->SetSelection(-1, -1);52    event.Skip();53}5455bool Is24HourTime()56{57    //char pszHourFormat[256];58    //pszHourFormat[0] = '\0';59    //GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_ITIME, pszHourFormat, 256);60    //return (pszHourFormat[0] != '0');61    return true;62}6364string DateStr(int64 nTime)65{66    // Can only be used safely here in the UI67    return (string)wxDateTime((time_t)nTime).FormatDate();68}6970string DateTimeStr(int64 nTime)71{72    // Can only be used safely here in the UI73    wxDateTime datetime((time_t)nTime);74    if (Is24HourTime())75        return (string)datetime.Format("%x %H:%M");76    else77        return (string)datetime.Format("%x ") + itostr((datetime.GetHour() + 11) % 12 + 1) + (string)datetime.Format(":%M %p");78}7980wxString GetItemText(wxListCtrl* listCtrl, int nIndex, int nColumn)81{82    // Helper to simplify access to listctrl83    wxListItem item;84    item.m_itemId = nIndex;85    item.m_col = nColumn;86    item.m_mask = wxLIST_MASK_TEXT;87    if (!listCtrl->GetItem(item))88        return "";89    return item.GetText();90}9192int InsertLine(wxListCtrl* listCtrl, const wxString& str0, const wxString& str1)93{94    int nIndex = listCtrl->InsertItem(listCtrl->GetItemCount(), str0);95    listCtrl->SetItem(nIndex, 1, str1);96    return nIndex;97}9899int InsertLine(wxListCtrl* listCtrl, const wxString& str0, const wxString& str1, const wxString& str2, const wxString& str3, const wxString& str4)100{101    int nIndex = listCtrl->InsertItem(listCtrl->GetItemCount(), str0);102    listCtrl->SetItem(nIndex, 1, str1);103    listCtrl->SetItem(nIndex, 2, str2);104    listCtrl->SetItem(nIndex, 3, str3);105    listCtrl->SetItem(nIndex, 4, str4);106    return nIndex;107}108109int InsertLine(wxListCtrl* listCtrl, void* pdata, const wxString& str0, const wxString& str1, const wxString& str2, const wxString& str3, const wxString& str4)110{111    int nIndex = listCtrl->InsertItem(listCtrl->GetItemCount(), str0);112    listCtrl->SetItemPtrData(nIndex, (wxUIntPtr)pdata);113    listCtrl->SetItem(nIndex, 1, str1);114    listCtrl->SetItem(nIndex, 2, str2);115    listCtrl->SetItem(nIndex, 3, str3);116    listCtrl->SetItem(nIndex, 4, str4);117    return nIndex;118}119120void SetSelection(wxListCtrl* listCtrl, int nIndex)121{122    int nSize = listCtrl->GetItemCount();123    long nState = (wxLIST_STATE_SELECTED|wxLIST_STATE_FOCUSED);124    for (int i = 0; i < nSize; i++)125        listCtrl->SetItemState(i, (i == nIndex ? nState : 0), nState);126}127128int GetSelection(wxListCtrl* listCtrl)129{130    int nSize = listCtrl->GetItemCount();131    for (int i = 0; i < nSize; i++)132        if (listCtrl->GetItemState(i, wxLIST_STATE_FOCUSED))133            return i;134    return -1;135}136137138string HtmlEscape(const char* psz, bool fMultiLine=false)139{140    int len = 0;141    for (const char* p = psz; *p; p++)142    {143             if (*p == '<') len += 4;144        else if (*p == '>') len += 4;145        else if (*p == '&') len += 5;146        else if (*p == '"') len += 6;147        else if (*p == ' ' && p > psz && p[-1] == ' ' && p[1] == ' ') len += 6;148        else if (*p == '\n' && fMultiLine) len += 5;149        else150            len++;151    }152    string str;153    str.reserve(len);154    for (const char* p = psz; *p; p++)155    {156             if (*p == '<') str += "&lt;";157        else if (*p == '>') str += "&gt;";158        else if (*p == '&') str += "&amp;";159        else if (*p == '"') str += "&quot;";160        else if (*p == ' ' && p > psz && p[-1] == ' ' && p[1] == ' ') str += "&nbsp;";161        else if (*p == '\n' && fMultiLine) str += "<br>\n";162        else163            str += *p;164    }165    return str;166}167168string HtmlEscape(const string& str, bool fMultiLine=false)169{170    return HtmlEscape(str.c_str(), fMultiLine);171}172173void AddToMyProducts(CProduct product)174{175    CProduct& productInsert = mapMyProducts[product.GetHash()];176    productInsert = product;177    InsertLine(pframeMain->m_listCtrlProductsSent, &productInsert,178                product.mapValue["category"],179                product.mapValue["title"].substr(0, 100),180                product.mapValue["description"].substr(0, 100),181                product.mapValue["price"],182                "");183}184185void CalledMessageBox(const string& message, const string& caption, int style, wxWindow* parent, int x, int y, int* pnRet, bool* pfDone)186{187    *pnRet = wxMessageBox(message, caption, style, parent, x, y);188    *pfDone = true;189}190191int ThreadSafeMessageBox(const string& message, const string& caption, int style, wxWindow* parent, int x, int y)192{193#ifdef __WXMSW__194    return wxMessageBox(message, caption, style, parent, x, y);195#else196    if (wxThread::IsMain())197    {198        return wxMessageBox(message, caption, style, parent, x, y);199    }200    else201    {202        int nRet = 0;203        bool fDone = false;204        UIThreadCall(bind(CalledMessageBox, message, caption, style, parent, x, y, &nRet, &fDone));205        while (!fDone)206            Sleep(100);207        return nRet;208    }209#endif210}211212213214215216217218219220221//////////////////////////////////////////////////////////////////////////////222//223// Custom events224//225// If this code gets used again, it should be replaced with something like UIThreadCall226227set<void*> setCallbackAvailable;228CCriticalSection cs_setCallbackAvailable;229230void AddCallbackAvailable(void* p)231{232    CRITICAL_BLOCK(cs_setCallbackAvailable)233        setCallbackAvailable.insert(p);234}235236void RemoveCallbackAvailable(void* p)237{238    CRITICAL_BLOCK(cs_setCallbackAvailable)239        setCallbackAvailable.erase(p);240}241242bool IsCallbackAvailable(void* p)243{244    CRITICAL_BLOCK(cs_setCallbackAvailable)245        return setCallbackAvailable.count(p);246    return false;247}248249template<typename T>250void AddPendingCustomEvent(wxEvtHandler* pevthandler, int nEventID, const T pbeginIn, const T pendIn)251{252    if (!pevthandler)253        return;254255    const char* pbegin = (pendIn != pbeginIn) ? &pbeginIn[0] : NULL;256    const char* pend = pbegin + (pendIn - pbeginIn) * sizeof(pbeginIn[0]);257    wxCommandEvent event(nEventID);258    wxString strData(wxChar(0), (pend - pbegin) / sizeof(wxChar) + 1);259    memcpy(&strData[0], pbegin, pend - pbegin);260    event.SetString(strData);261    event.SetInt(pend - pbegin);262263    pevthandler->AddPendingEvent(event);264}265266template<class T>267void AddPendingCustomEvent(wxEvtHandler* pevthandler, int nEventID, const T& obj)268{269    CDataStream ss;270    ss << obj;271    AddPendingCustomEvent(pevthandler, nEventID, ss.begin(), ss.end());272}273274void AddPendingReplyEvent1(void* pevthandler, CDataStream& vRecv)275{276    if (IsCallbackAvailable(pevthandler))277        AddPendingCustomEvent((wxEvtHandler*)pevthandler, wxEVT_REPLY1, vRecv.begin(), vRecv.end());278}279280void AddPendingReplyEvent2(void* pevthandler, CDataStream& vRecv)281{282    if (IsCallbackAvailable(pevthandler))283        AddPendingCustomEvent((wxEvtHandler*)pevthandler, wxEVT_REPLY2, vRecv.begin(), vRecv.end());284}285286void AddPendingReplyEvent3(void* pevthandler, CDataStream& vRecv)287{288    if (IsCallbackAvailable(pevthandler))289        AddPendingCustomEvent((wxEvtHandler*)pevthandler, wxEVT_REPLY3, vRecv.begin(), vRecv.end());290}291292CDataStream GetStreamFromEvent(const wxCommandEvent& event)293{294    wxString strData = event.GetString();295    const char* pszBegin = strData.c_str();296    return CDataStream(pszBegin, pszBegin + event.GetInt(), SER_NETWORK);297}298299300301302303304305//////////////////////////////////////////////////////////////////////////////306//307// CMainFrame308//309310CMainFrame::CMainFrame(wxWindow* parent) : CMainFrameBase(parent)311{312    Connect(wxEVT_UITHREADCALL, wxCommandEventHandler(CMainFrame::OnUIThreadCall), NULL, this);313314    // Init315    fRefreshListCtrl = false;316    fRefreshListCtrlRunning = false;317    fOnSetFocusAddress = false;318    fRefresh = false;319    m_choiceFilter->SetSelection(0);320    double dResize = 1.0;321#ifdef __WXMSW__322    SetIcon(wxICON(bitcoin));323#else324    SetIcon(bitcoin16_xpm);325    wxFont fontTmp = m_staticText41->GetFont();326    fontTmp.SetFamily(wxFONTFAMILY_TELETYPE);327    m_staticTextBalance->SetFont(fontTmp);328    m_staticTextBalance->SetSize(140, 17);329    // & underlines don't work on the toolbar buttons on gtk330    m_toolBar->ClearTools();331    m_toolBar->AddTool(wxID_BUTTONSEND, "Send Coins", wxBitmap(send20_xpm), wxNullBitmap, wxITEM_NORMAL, wxEmptyString, wxEmptyString);332    m_toolBar->AddTool(wxID_BUTTONRECEIVE, "Address Book", wxBitmap(addressbook20_xpm), wxNullBitmap, wxITEM_NORMAL, wxEmptyString, wxEmptyString);333    m_toolBar->Realize();334    // resize to fit ubuntu's huge default font335    dResize = 1.19;336    SetSize(dResize * GetSize().GetWidth(), 1.1 * GetSize().GetHeight());337    dResize = 1.20;338#endif339    m_staticTextBalance->SetLabel(FormatMoney(GetBalance()) + "  ");340    m_listCtrl->SetFocus();341    ptaskbaricon = new CMyTaskBarIcon();342343    // Init column headers344    int nDateWidth = DateTimeStr(1229413914).size() * 6 + 8;345    if (!strstr(DateTimeStr(1229413914).c_str(), "2008"))346        nDateWidth += 12;347    m_listCtrl->InsertColumn(0, "",             wxLIST_FORMAT_LEFT,  dResize * 0);348    m_listCtrl->InsertColumn(1, "",             wxLIST_FORMAT_LEFT,  dResize * 0);349    m_listCtrl->InsertColumn(2, "Status",       wxLIST_FORMAT_LEFT,  dResize * 90);350    m_listCtrl->InsertColumn(3, "Date",         wxLIST_FORMAT_LEFT,  dResize * nDateWidth);351    m_listCtrl->InsertColumn(4, "Description",  wxLIST_FORMAT_LEFT,  dResize * 409 - nDateWidth);352    m_listCtrl->InsertColumn(5, "Debit",        wxLIST_FORMAT_RIGHT, dResize * 79);353    m_listCtrl->InsertColumn(6, "Credit",       wxLIST_FORMAT_RIGHT, dResize * 79);354355    //m_listCtrlProductsSent->InsertColumn(0, "Category",      wxLIST_FORMAT_LEFT,  100);356    //m_listCtrlProductsSent->InsertColumn(1, "Title",         wxLIST_FORMAT_LEFT,  100);357    //m_listCtrlProductsSent->InsertColumn(2, "Description",   wxLIST_FORMAT_LEFT,  100);358    //m_listCtrlProductsSent->InsertColumn(3, "Price",         wxLIST_FORMAT_LEFT,  100);359    //m_listCtrlProductsSent->InsertColumn(4, "",              wxLIST_FORMAT_LEFT,  100);360361    //m_listCtrlOrdersSent->InsertColumn(0, "Time",          wxLIST_FORMAT_LEFT,  100);362    //m_listCtrlOrdersSent->InsertColumn(1, "Price",         wxLIST_FORMAT_LEFT,  100);363    //m_listCtrlOrdersSent->InsertColumn(2, "",              wxLIST_FORMAT_LEFT,  100);364    //m_listCtrlOrdersSent->InsertColumn(3, "",              wxLIST_FORMAT_LEFT,  100);365    //m_listCtrlOrdersSent->InsertColumn(4, "",              wxLIST_FORMAT_LEFT,  100);366367    //m_listCtrlOrdersReceived->InsertColumn(0, "Time",            wxLIST_FORMAT_LEFT,  100);368    //m_listCtrlOrdersReceived->InsertColumn(1, "Price",           wxLIST_FORMAT_LEFT,  100);369    //m_listCtrlOrdersReceived->InsertColumn(2, "Payment Status",  wxLIST_FORMAT_LEFT,  100);370    //m_listCtrlOrdersReceived->InsertColumn(3, "",                wxLIST_FORMAT_LEFT,  100);371    //m_listCtrlOrdersReceived->InsertColumn(4, "",                wxLIST_FORMAT_LEFT,  100);372373    // Init status bar374    int pnWidths[3] = { -100, 88, 290 };375#ifndef __WXMSW__376    pnWidths[1] = pnWidths[1] * 1.1 * dResize;377    pnWidths[2] = pnWidths[2] * 1.1 * dResize;378#endif379    m_statusBar->SetFieldsCount(3, pnWidths);380381    // Fill your address text box382    vector<unsigned char> vchPubKey;383    if (CWalletDB("r").ReadDefaultKey(vchPubKey))384        m_textCtrlAddress->SetValue(PubKeyToAddress(vchPubKey));385386    // Fill listctrl with wallet transactions387    RefreshListCtrl();388}389390CMainFrame::~CMainFrame()391{392    pframeMain = NULL;393    delete ptaskbaricon;394    ptaskbaricon = NULL;395}396397void ExitTimeout(void* parg)398{399#ifdef __WXMSW__400    Sleep(5000);401    ExitProcess(0);402#endif403}404405void Shutdown(void* parg)406{407    static CCriticalSection cs_Shutdown;408    static bool fTaken;409    bool fFirstThread;410    CRITICAL_BLOCK(cs_Shutdown)411    {412        fFirstThread = !fTaken;413        fTaken = true;414    }415    static bool fExit;416    if (fFirstThread)417    {418        fShutdown = true;419        nTransactionsUpdated++;420        DBFlush(false);421        StopNode();422        DBFlush(true);423        CreateThread(ExitTimeout, NULL);424        Sleep(10);425        printf("Bitcoin exiting\n\n");426        fExit = true;427        exit(0);428    }429    else430    {431        while (!fExit)432            Sleep(500);433        Sleep(100);434        ExitThread(0);435    }436}437438void CMainFrame::OnClose(wxCloseEvent& event)439{440    if (fMinimizeOnClose && event.CanVeto() && !IsIconized())441    {442        // Divert close to minimize443        event.Veto();444        fClosedToTray = true;445        Iconize(true);446    }447    else448    {449        Destroy();450        CreateThread(Shutdown, NULL);451    }452}453454void CMainFrame::OnIconize(wxIconizeEvent& event)455{456    // Hide the task bar button when minimized.457    // Event is sent when the frame is minimized or restored.458    if (!event.Iconized())459        fClosedToTray = false;460#ifndef __WXMSW__461    // Tray is not reliable on Linux gnome462    fClosedToTray = false;463#endif464    if (fMinimizeToTray && event.Iconized())465        fClosedToTray = true;466    Show(!fClosedToTray);467    ptaskbaricon->Show(fMinimizeToTray || fClosedToTray);468}469470void CMainFrame::OnMouseEvents(wxMouseEvent& event)471{472    RandAddSeed();473    RAND_add(&event.m_x, sizeof(event.m_x), 0.25);474    RAND_add(&event.m_y, sizeof(event.m_y), 0.25);475}476477void CMainFrame::OnListColBeginDrag(wxListEvent& event)478{479     // Hidden columns not resizeable480     if (event.GetColumn() <= 1 && !fDebug)481        event.Veto();482}483484int CMainFrame::GetSortIndex(const string& strSort)485{486#ifdef __WXMSW__487    return 0;488#else489    // The wx generic listctrl implementation used on GTK doesn't sort,490    // so we have to do it ourselves.  Remember, we sort in reverse order.491    // In the wx generic implementation, they store the list of items492    // in a vector, so indexed lookups are fast, but inserts are slower493    // the closer they are to the top.494    int low = 0;495    int high = m_listCtrl->GetItemCount();496    while (low < high)497    {498        int mid = low + ((high - low) / 2);499        if (strSort.compare(m_listCtrl->GetItemText(mid).c_str()) >= 0)500            high = mid;501        else502            low = mid + 1;503    }504    return low;505#endif506}507508void 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)509{510    string str0 = strSort;511    long nData = *(long*)&hashKey;512513    // Find item514    if (!fNew && nIndex == -1)515    {516        while ((nIndex = m_listCtrl->FindItem(nIndex, nData)) != -1)517            if (GetItemText(m_listCtrl, nIndex, 1) == hashKey.ToString())518                break;519    }520521    // fNew is for blind insert, only use if you're sure it's new522    if (fNew || nIndex == -1)523    {524        nIndex = m_listCtrl->InsertItem(GetSortIndex(strSort), str0);525    }526    else527    {528        // If sort key changed, must delete and reinsert to make it relocate529        if (GetItemText(m_listCtrl, nIndex, 0) != str0)530        {531            m_listCtrl->DeleteItem(nIndex);532            nIndex = m_listCtrl->InsertItem(GetSortIndex(strSort), str0);533        }534    }535536    m_listCtrl->SetItem(nIndex, 1, hashKey.ToString());537    m_listCtrl->SetItem(nIndex, 2, str2);538    m_listCtrl->SetItem(nIndex, 3, str3);539    m_listCtrl->SetItem(nIndex, 4, str4);540    m_listCtrl->SetItem(nIndex, 5, str5);541    m_listCtrl->SetItem(nIndex, 6, str6);542    m_listCtrl->SetItemData(nIndex, nData);543}544545bool CMainFrame::DeleteLine(uint256 hashKey)546{547    long nData = *(long*)&hashKey;548549    // Find item550    int nIndex = -1;551    while ((nIndex = m_listCtrl->FindItem(nIndex, nData)) != -1)552        if (GetItemText(m_listCtrl, nIndex, 1) == hashKey.ToString())553            break;554555    if (nIndex != -1)556        m_listCtrl->DeleteItem(nIndex);557558    return nIndex != -1;559}560561string FormatTxStatus(const CWalletTx& wtx)562{563    // Status564    if (!wtx.IsFinal())565    {566        if (wtx.nLockTime < 500000000)567            return strprintf("Open for %d blocks", nBestHeight - wtx.nLockTime);568        else569            return strprintf("Open until %s", DateTimeStr(wtx.nLockTime).c_str());570    }571    else572    {573        int nDepth = wtx.GetDepthInMainChain();574        if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)575            return strprintf("%d/offline?", nDepth);576        else if (nDepth < 6)577            return strprintf("%d/unconfirmed", nDepth);578        else579            return strprintf("%d blocks", nDepth);580    }581}582583string SingleLine(const string& strIn)584{585    string strOut;586    bool fOneSpace = false;587    foreach(int c, strIn)588    {589        if (isspace(c))590        {591            fOneSpace = true;592        }593        else if (c > ' ')594        {595            if (fOneSpace && !strOut.empty())596                strOut += ' ';597            strOut += c;598            fOneSpace = false;599        }600    }601    return strOut;602}603604bool CMainFrame::InsertTransaction(const CWalletTx& wtx, bool fNew, int nIndex)605{606    int64 nTime = wtx.nTimeDisplayed = wtx.GetTxTime();607    int64 nCredit = wtx.GetCredit();608    int64 nDebit = wtx.GetDebit();609    int64 nNet = nCredit - nDebit;610    uint256 hash = wtx.GetHash();611    string strStatus = FormatTxStatus(wtx);612    map<string, string> mapValue = wtx.mapValue;613    wtx.nLinesDisplayed = 1;614    nListViewUpdated++;615616    // Filter617    if (wtx.IsCoinBase())618    {619        // Don't show generated coin until confirmed by at least one block after it620        // so we don't get the user's hopes up until it looks like it's probably accepted.621        //622        // It is not an error when generated blocks are not accepted.  By design,623        // some percentage of blocks, like 10% or more, will end up not accepted.624        // This is the normal mechanism by which the network copes with latency.625        //626        // We display regular transactions right away before any confirmation627        // because they can always get into some block eventually.  Generated coins628        // are special because if their block is not accepted, they are not valid.629        //630        if (wtx.GetDepthInMainChain() < 2)631        {632            wtx.nLinesDisplayed = 0;633            return false;634        }635636        // View->Show Generated637        if (!fShowGenerated)638            return false;639    }640641    // Find the block the tx is in642    CBlockIndex* pindex = NULL;643    map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(wtx.hashBlock);644    if (mi != mapBlockIndex.end())645        pindex = (*mi).second;646647    // Sort order, unrecorded transactions sort to the top648    string strSort = strprintf("%010d-%01d-%010u",649        (pindex ? pindex->nHeight : INT_MAX),650        (wtx.IsCoinBase() ? 1 : 0),651        wtx.nTimeReceived);652653    // Insert line654    if (nNet > 0 || wtx.IsCoinBase())655    {656        //657        // Credit658        //659        string strDescription;660661        if (wtx.IsCoinBase())662        {663            // Coinbase664            strDescription = "Generated";665            if (nCredit == 0)666            {667                int64 nUnmatured = 0;668                foreach(const CTxOut& txout, wtx.vout)669                    nUnmatured += txout.GetCredit();670                if (wtx.IsInMainChain())671                {672                    strDescription = strprintf("Generated (%s matures in %d more blocks)", FormatMoney(nUnmatured).c_str(), wtx.GetBlocksToMaturity());673674                    // Check if the block was requested by anyone675                    if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)676                        strDescription = "Generated - Warning: This block was not received by any other nodes and will probably not be accepted!";677                }678                else679                {680                    strDescription = "Generated (not accepted)";681                }682            }683        }684        else if (!mapValue["from"].empty() || !mapValue["message"].empty())685        {686            // Online transaction687            if (!mapValue["from"].empty())688                strDescription += "From: " + mapValue["from"];689            if (!mapValue["message"].empty())690            {691                if (!strDescription.empty())692                    strDescription += " - ";693                strDescription += mapValue["message"];694            }695        }696        else697        {698            // Offline transaction699            foreach(const CTxOut& txout, wtx.vout)700            {701                if (txout.IsMine())702                {703                    vector<unsigned char> vchPubKey;704                    if (ExtractPubKey(txout.scriptPubKey, true, vchPubKey))705                    {706                        string strAddress = PubKeyToAddress(vchPubKey);707                        if (mapAddressBook.count(strAddress))708                        {709                            //strDescription += "Received payment to ";710                            //strDescription += "Received with address ";711                            strDescription += "From: unknown, To: ";712                            strDescription += strAddress;713                            /// The labeling feature is just too confusing, so I hid it714                            /// by putting it at the end where it runs off the screen.715                            /// It can still be seen by widening the column, or in the716                            /// details dialog.717                            if (!mapAddressBook[strAddress].empty())718                                strDescription += " (" + mapAddressBook[strAddress] + ")";719                        }720                    }721                    break;722                }723            }724        }725726        InsertLine(fNew, nIndex, hash, strSort,727                   strStatus,728                   nTime ? DateTimeStr(nTime) : "",729                   SingleLine(strDescription),730                   "",731                   FormatMoney(nNet, true));732    }733    else734    {735        bool fAllFromMe = true;736        foreach(const CTxIn& txin, wtx.vin)737            fAllFromMe = fAllFromMe && txin.IsMine();738739        bool fAllToMe = true;740        foreach(const CTxOut& txout, wtx.vout)741            fAllToMe = fAllToMe && txout.IsMine();742743        if (fAllFromMe && fAllToMe)744        {745            // Payment to self746            int64 nValue = wtx.vout[0].nValue;747            InsertLine(fNew, nIndex, hash, strSort,748                       strStatus,749                       nTime ? DateTimeStr(nTime) : "",750                       "Payment to yourself",751                       "",752                       "");753            /// issue: can't tell which is the payment and which is the change anymore754            //           FormatMoney(nNet - nValue, true),755            //           FormatMoney(nValue, true));756        }757        else if (fAllFromMe)758        {759            //760            // Debit761            //762            int64 nTxFee = nDebit - wtx.GetValueOut();763            wtx.nLinesDisplayed = 0;764            for (int nOut = 0; nOut < wtx.vout.size(); nOut++)765            {766                const CTxOut& txout = wtx.vout[nOut];767                if (txout.IsMine())768                    continue;769770                string strAddress;771                if (!mapValue["to"].empty())772                {773                    // Online transaction774                    strAddress = mapValue["to"];775                }776                else777                {778                    // Offline transaction779                    uint160 hash160;780                    if (ExtractHash160(txout.scriptPubKey, hash160))781                        strAddress = Hash160ToAddress(hash160);782                }783784                string strDescription = "To: ";785                if (mapAddressBook.count(strAddress) && !mapAddressBook[strAddress].empty())786                    strDescription += mapAddressBook[strAddress] + " ";787                strDescription += strAddress;788                if (!mapValue["message"].empty())789                {790                    if (!strDescription.empty())791                        strDescription += " - ";792                    strDescription += mapValue["message"];793                }794795                int64 nValue = txout.nValue;796                if (nOut == 0 && nTxFee > 0)797                    nValue += nTxFee;798799                InsertLine(fNew, nIndex, hash, strprintf("%s-%d", strSort.c_str(), nOut),800                           strStatus,801                           nTime ? DateTimeStr(nTime) : "",802                           SingleLine(strDescription),803                           FormatMoney(-nValue, true),804                           "");805                wtx.nLinesDisplayed++;806            }807        }808        else809        {810            //811            // Mixed debit transaction, can't break down payees812            //813            bool fAllMine = true;814            foreach(const CTxOut& txout, wtx.vout)815                fAllMine = fAllMine && txout.IsMine();816            foreach(const CTxIn& txin, wtx.vin)817                fAllMine = fAllMine && txin.IsMine();818819            InsertLine(fNew, nIndex, hash, strSort,820                       strStatus,821                       nTime ? DateTimeStr(nTime) : "",822                       "",823                       FormatMoney(nNet, true),824                       "");825        }826    }827828    return true;829}830831void CMainFrame::RefreshListCtrl()832{833    fRefreshListCtrl = true;834    ::wxWakeUpIdle();835}836837void CMainFrame::OnIdle(wxIdleEvent& event)838{839    if (fRefreshListCtrl)840    {841        // Collect list of wallet transactions and sort newest first842        bool fEntered = false;843        vector<pair<unsigned int, uint256> > vSorted;844        TRY_CRITICAL_BLOCK(cs_mapWallet)845        {846            printf("RefreshListCtrl starting\n");847            fEntered = true;848            fRefreshListCtrl = false;849            vWalletUpdated.clear();850851            // Do the newest transactions first852            vSorted.reserve(mapWallet.size());853            for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)854            {855                const CWalletTx& wtx = (*it).second;856                unsigned int nTime = UINT_MAX - wtx.GetTxTime();857                vSorted.push_back(make_pair(nTime, (*it).first));858            }859            m_listCtrl->DeleteAllItems();860        }861        if (!fEntered)862            return;863864        sort(vSorted.begin(), vSorted.end());865866        // Fill list control867        for (int i = 0; i < vSorted.size();)868        {869            if (fShutdown)870                return;871            bool fEntered = false;872            TRY_CRITICAL_BLOCK(cs_mapWallet)873            {874                fEntered = true;875                uint256& hash = vSorted[i++].second;876                map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash);877                if (mi != mapWallet.end())878                    InsertTransaction((*mi).second, true);879            }880            if (!fEntered || i == 100 || i % 500 == 0)881                wxYield();882        }883884        printf("RefreshListCtrl done\n");885886        // Update transaction total display887        MainFrameRepaint();888    }889    else890    {891        // Check for time updates892        static int64 nLastTime;893        if (GetTime() > nLastTime + 30)894        {895            TRY_CRITICAL_BLOCK(cs_mapWallet)896            {897                nLastTime = GetTime();898                for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)899                {900                    CWalletTx& wtx = (*it).second;901                    if (wtx.nTimeDisplayed && wtx.nTimeDisplayed != wtx.GetTxTime())902                        InsertTransaction(wtx, false);903                }904            }905        }906    }907}908909void CMainFrame::RefreshStatusColumn()910{911    static int nLastTop;912    static CBlockIndex* pindexLastBest;913    static unsigned int nLastRefreshed;914915    int nTop = max((int)m_listCtrl->GetTopItem(), 0);916    if (nTop == nLastTop && pindexLastBest == pindexBest)917        return;918919    TRY_CRITICAL_BLOCK(cs_mapWallet)920    {921        int nStart = nTop;922        int nEnd = min(nStart + 100, m_listCtrl->GetItemCount());923924        if (pindexLastBest == pindexBest && nLastRefreshed == nListViewUpdated)925        {926            // If no updates, only need to do the part that moved onto the screen927            if (nStart >= nLastTop && nStart < nLastTop + 100)928                nStart = nLastTop + 100;929            if (nEnd >= nLastTop && nEnd < nLastTop + 100)930                nEnd = nLastTop;931        }932        nLastTop = nTop;933        pindexLastBest = pindexBest;934        nLastRefreshed = nListViewUpdated;935936        for (int nIndex = nStart; nIndex < min(nEnd, m_listCtrl->GetItemCount()); nIndex++)937        {938            uint256 hash((string)GetItemText(m_listCtrl, nIndex, 1));939            map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash);940            if (mi == mapWallet.end())941            {942                printf("CMainFrame::RefreshStatusColumn() : tx not found in mapWallet\n");943                continue;944            }945            CWalletTx& wtx = (*mi).second;946            if (wtx.IsCoinBase() || wtx.GetTxTime() != wtx.nTimeDisplayed)947            {948                if (!InsertTransaction(wtx, false, nIndex))949                    m_listCtrl->DeleteItem(nIndex--);950            }951            else952                m_listCtrl->SetItem(nIndex, 2, FormatTxStatus(wtx));953        }954    }955}956957void CMainFrame::OnPaint(wxPaintEvent& event)958{959    if (fRefresh)960    {961        fRefresh = false;962        Refresh();963    }964    event.Skip();965}966967968unsigned int nNeedRepaint = 0;969unsigned int nLastRepaint = 0;970int64 nLastRepaintTime = 0;971int64 nRepaintInterval = 500;972973void ThreadDelayedRepaint(void* parg)974{975    while (!fShutdown)976    {977        if (nLastRepaint != nNeedRepaint && GetTimeMillis() - nLastRepaintTime >= nRepaintInterval)978        {979            nLastRepaint = nNeedRepaint;980            if (pframeMain)981            {982                printf("DelayedRepaint\n");983                wxPaintEvent event;984                pframeMain->fRefresh = true;985                pframeMain->AddPendingEvent(event);986            }987        }988        Sleep(nRepaintInterval);989    }990}991992void MainFrameRepaint()993{994    // This is called by network code that shouldn't access pframeMain995    // directly because it could still be running after the UI is closed.996    if (pframeMain)997    {998        // Don't repaint too often999        static int64 nLastRepaintRequest;1000        if (GetTimeMillis() - nLastRepaintRequest < 100)1001        {1002            nNeedRepaint++;1003            return;1004        }1005        nLastRepaintRequest = GetTimeMillis();10061007        printf("MainFrameRepaint\n");1008        wxPaintEvent event;1009        pframeMain->fRefresh = true;1010        pframeMain->AddPendingEvent(event);1011    }1012}10131014void CMainFrame::OnPaintListCtrl(wxPaintEvent& event)1015{1016    if (ptaskbaricon)1017        ptaskbaricon->UpdateTooltip();10181019    //1020    // Slower stuff1021    //1022    static int nTransactionCount;1023    bool fPaintedBalance = false;1024    if (GetTimeMillis() - nLastRepaintTime >= nRepaintInterval)1025    {1026        nLastRepaint = nNeedRepaint;1027        nLastRepaintTime = GetTimeMillis();10281029        // Update listctrl contents1030        if (!vWalletUpdated.empty())1031        {1032            TRY_CRITICAL_BLOCK(cs_mapWallet)1033            {1034                string strTop;1035                if (m_listCtrl->GetItemCount())1036                    strTop = (string)m_listCtrl->GetItemText(0);1037                foreach(uint256 hash, vWalletUpdated)1038                {1039                    map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash);1040                    if (mi != mapWallet.end())1041                        InsertTransaction((*mi).second, false);1042                }1043                vWalletUpdated.clear();1044                if (m_listCtrl->GetItemCount() && strTop != (string)m_listCtrl->GetItemText(0))1045                    m_listCtrl->ScrollList(0, INT_MIN/2);1046            }1047        }10481049        // Balance total1050        TRY_CRITICAL_BLOCK(cs_mapWallet)1051        {1052            fPaintedBalance = true;1053            m_staticTextBalance->SetLabel(FormatMoney(GetBalance()) + "  ");10541055            // Count hidden and multi-line transactions1056            nTransactionCount = 0;1057            for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)1058            {1059                CWalletTx& wtx = (*it).second;1060                nTransactionCount += wtx.nLinesDisplayed;1061            }1062        }1063    }1064    if (!vWalletUpdated.empty() || !fPaintedBalance)1065        nNeedRepaint++;10661067    // Update status column of visible items only1068    RefreshStatusColumn();10691070    // Update status bar1071    string strGen = "";1072    if (fGenerateBitcoins)1073        strGen = "    Generating";1074    if (fGenerateBitcoins && vNodes.empty())1075        strGen = "(not connected)";1076    m_statusBar->SetStatusText(strGen, 1);10771078    string strStatus = strprintf("     %d connections     %d blocks     %d transactions", vNodes.size(), nBestHeight + 1, nTransactionCount);1079    m_statusBar->SetStatusText(strStatus, 2);10801081    if (fDebug && GetTime() - nThreadSocketHandlerHeartbeat > 60)1082        m_statusBar->SetStatusText("     ERROR: ThreadSocketHandler has stopped", 0);10831084    // Pass through to listctrl to actually do the paint, we're just hooking the message1085    m_listCtrl->Disconnect(wxEVT_PAINT, (wxObjectEventFunction)NULL, NULL, this);1086    m_listCtrl->GetEventHandler()->ProcessEvent(event);1087    m_listCtrl->Connect(wxEVT_PAINT, wxPaintEventHandler(CMainFrame::OnPaintListCtrl), NULL, this);1088}108910901091void UIThreadCall(boost::function0<void> fn)1092{1093    // Call this with a function object created with bind.1094    // bind needs all parameters to match the function's expected types1095    // and all default parameters specified.  Some examples:1096    //  UIThreadCall(bind(wxBell));1097    //  UIThreadCall(bind(wxMessageBox, wxT("Message"), wxT("Title"), wxOK, (wxWindow*)NULL, -1, -1));1098    //  UIThreadCall(bind(&CMainFrame::OnMenuHelpAbout, pframeMain, event));1099    if (pframeMain)1100    {1101        wxCommandEvent event(wxEVT_UITHREADCALL);1102        event.SetClientData((void*)new boost::function0<void>(fn));1103        pframeMain->GetEventHandler()->AddPendingEvent(event);1104    }1105}11061107void CMainFrame::OnUIThreadCall(wxCommandEvent& event)1108{1109    boost::function0<void>* pfn = (boost::function0<void>*)event.GetClientData();1110    (*pfn)();1111    delete pfn;1112}11131114void CMainFrame::OnMenuFileExit(wxCommandEvent& event)1115{1116    // File->Exit1117    Close(true);1118}11191120void CMainFrame::OnMenuViewShowGenerated(wxCommandEvent& event)1121{1122    // View->Show Generated1123    fShowGenerated = event.IsChecked();1124    CWalletDB().WriteSetting("fShowGenerated", fShowGenerated);1125    RefreshListCtrl();1126}11271128void CMainFrame::OnUpdateUIViewShowGenerated(wxUpdateUIEvent& event)1129{1130    event.Check(fShowGenerated);1131}11321133void CMainFrame::OnMenuOptionsGenerate(wxCommandEvent& event)1134{1135    // Options->Generate Coins1136    GenerateBitcoins(event.IsChecked());1137}11381139void CMainFrame::OnUpdateUIOptionsGenerate(wxUpdateUIEvent& event)1140{1141    event.Check(fGenerateBitcoins);1142}11431144void CMainFrame::OnMenuOptionsChangeYourAddress(wxCommandEvent& event)1145{1146    // Options->Change Your Address1147    OnButtonChange(event);1148}11491150void CMainFrame::OnMenuOptionsOptions(wxCommandEvent& event)1151{1152    // Options->Options1153    COptionsDialog dialog(this);1154    dialog.ShowModal();1155}11561157void CMainFrame::OnMenuHelpAbout(wxCommandEvent& event)1158{1159    // Help->About1160    CAboutDialog dialog(this);1161    dialog.ShowModal();1162}11631164void CMainFrame::OnButtonSend(wxCommandEvent& event)1165{1166    // Toolbar: Send1167    CSendDialog dialog(this);1168    dialog.ShowModal();1169}11701171void CMainFrame::OnButtonAddressBook(wxCommandEvent& event)1172{1173    // Toolbar: Address Book1174    CAddressBookDialog dialogAddr(this, "", false);1175    if (dialogAddr.ShowModal() == 2)1176    {1177        // Send1178        CSendDialog dialogSend(this, dialogAddr.GetAddress());1179        dialogSend.ShowModal();1180    }1181}11821183void CMainFrame::OnSetFocusAddress(wxFocusEvent& event)1184{1185    // Automatically select-all when entering window1186    m_textCtrlAddress->SetSelection(-1, -1);1187    fOnSetFocusAddress = true;1188    event.Skip();1189}11901191void CMainFrame::OnMouseEventsAddress(wxMouseEvent& event)1192{1193    if (fOnSetFocusAddress)1194        m_textCtrlAddress->SetSelection(-1, -1);1195    fOnSetFocusAddress = false;1196    event.Skip();1197}11981199void CMainFrame::OnButtonCopy(wxCommandEvent& event)1200{1201    // Copy address box to clipboard1202    if (wxTheClipboard->Open())1203    {1204        wxTheClipboard->SetData(new wxTextDataObject(m_textCtrlAddress->GetValue()));1205        wxTheClipboard->Close();1206    }1207}12081209void CMainFrame::OnButtonChange(wxCommandEvent& event)1210{1211    CYourAddressDialog dialog(this, string(m_textCtrlAddress->GetValue()));1212    if (!dialog.ShowModal())1213        return;1214    string strAddress = (string)dialog.GetAddress();1215    if (strAddress != m_textCtrlAddress->GetValue())1216    {1217        uint160 hash160;1218        if (!AddressToHash160(strAddress, hash160))1219            return;1220        if (!mapPubKeys.count(hash160))1221            return;1222        CWalletDB().WriteDefaultKey(mapPubKeys[hash160]);1223        m_textCtrlAddress->SetValue(strAddress);1224    }1225}12261227void CMainFrame::OnListItemActivatedAllTransactions(wxListEvent& event)1228{1229    uint256 hash((string)GetItemText(m_listCtrl, event.GetIndex(), 1));1230    CWalletTx wtx;1231    CRITICAL_BLOCK(cs_mapWallet)1232    {1233        map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash);1234        if (mi == mapWallet.end())1235        {1236            printf("CMainFrame::OnListItemActivatedAllTransactions() : tx not found in mapWallet\n");1237            return;1238        }1239        wtx = (*mi).second;1240    }1241    CTxDetailsDialog dialog(this, wtx);1242    dialog.ShowModal();1243    //CTxDetailsDialog* pdialog = new CTxDetailsDialog(this, wtx);1244    //pdialog->Show();1245}12461247void CMainFrame::OnListItemActivatedProductsSent(wxListEvent& event)1248{1249    CProduct& product = *(CProduct*)event.GetItem().GetData();1250    CEditProductDialog* pdialog = new CEditProductDialog(this);1251    pdialog->SetProduct(product);1252    pdialog->Show();1253}12541255void CMainFrame::OnListItemActivatedOrdersSent(wxListEvent& event)1256{1257    CWalletTx& order = *(CWalletTx*)event.GetItem().GetData();1258    CViewOrderDialog* pdialog = new CViewOrderDialog(this, order, false);1259    pdialog->Show();1260}12611262void CMainFrame::OnListItemActivatedOrdersReceived(wxListEvent& event)1263{1264    CWalletTx& order = *(CWalletTx*)event.GetItem().GetData();1265    CViewOrderDialog* pdialog = new CViewOrderDialog(this, order, true);1266    pdialog->Show();1267}12681269127012711272127312741275//////////////////////////////////////////////////////////////////////////////1276//1277// CTxDetailsDialog1278//12791280CTxDetailsDialog::CTxDetailsDialog(wxWindow* parent, CWalletTx wtx) : CTxDetailsDialogBase(parent)1281{1282    string strHTML;1283    strHTML.reserve(4000);1284    strHTML += "<html><font face='verdana, arial, helvetica, sans-serif'>";12851286    int64 nTime = wtx.GetTxTime();1287    int64 nCredit = wtx.GetCredit();1288    int64 nDebit = wtx.GetDebit();1289    int64 nNet = nCredit - nDebit;1290129112921293    strHTML += "<b>Status:</b> " + FormatTxStatus(wtx);1294    int nRequests = wtx.GetRequestCount();1295    if (nRequests != -1)1296    {1297        if (nRequests == 0)1298            strHTML += ", has not been successfully broadcast yet";1299        else if (nRequests == 1)1300            strHTML += strprintf(", broadcast through %d node", nRequests);1301        else1302            strHTML += strprintf(", broadcast through %d nodes", nRequests);1303    }1304    strHTML += "<br>";13051306    strHTML += "<b>Date:</b> " + (nTime ? DateTimeStr(nTime) : "") + "<br>";130713081309    //1310    // From1311    //1312    if (wtx.IsCoinBase())1313    {1314        strHTML += "<b>Source:</b> Generated<br>";1315    }1316    else if (!wtx.mapValue["from"].empty())1317    {1318        // Online transaction1319        if (!wtx.mapValue["from"].empty())1320            strHTML += "<b>From:</b> " + HtmlEscape(wtx.mapValue["from"]) + "<br>";1321    }1322    else1323    {1324        // Offline transaction1325        if (nNet > 0)1326        {1327            // Credit1328            foreach(const CTxOut& txout, wtx.vout)1329            {1330                if (txout.IsMine())1331                {1332                    vector<unsigned char> vchPubKey;1333                    if (ExtractPubKey(txout.scriptPubKey, true, vchPubKey))1334                    {1335                        string strAddress = PubKeyToAddress(vchPubKey);1336                        if (mapAddressBook.count(strAddress))1337                        {1338                            strHTML += "<b>From:</b> unknown<br>";1339                            strHTML += "<b>To:</b> ";1340                            strHTML += HtmlEscape(strAddress);1341                            if (!mapAddressBook[strAddress].empty())1342                                strHTML += " (yours, label: " + mapAddressBook[strAddress] + ")";1343                            else1344                                strHTML += " (yours)";1345                            strHTML += "<br>";1346                        }1347                    }1348                    break;1349                }1350            }1351        }1352    }135313541355    //1356    // To1357    //1358    string strAddress;1359    if (!wtx.mapValue["to"].empty())1360    {1361        // Online transaction1362        strAddress = wtx.mapValue["to"];1363        strHTML += "<b>To:</b> ";1364        if (mapAddressBook.count(strAddress) && !mapAddressBook[strAddress].empty())1365            strHTML += mapAddressBook[strAddress] + " ";1366        strHTML += HtmlEscape(strAddress) + "<br>";1367    }136813691370    //1371    // Amount1372    //1373    if (wtx.IsCoinBase() && nCredit == 0)1374    {1375        //1376        // Coinbase1377        //1378        int64 nUnmatured = 0;1379        foreach(const CTxOut& txout, wtx.vout)1380            nUnmatured += txout.GetCredit();1381        if (wtx.IsInMainChain())1382            strHTML += strprintf("<b>Credit:</b> (%s matures in %d more blocks)<br>", FormatMoney(nUnmatured).c_str(), wtx.GetBlocksToMaturity());1383        else1384            strHTML += "<b>Credit:</b> (not accepted)<br>";1385    }1386    else if (nNet > 0)1387    {1388        //1389        // Credit1390        //1391        strHTML += "<b>Credit:</b> " + FormatMoney(nNet) + "<br>";1392    }1393    else1394    {1395        bool fAllFromMe = true;1396        foreach(const CTxIn& txin, wtx.vin)1397            fAllFromMe = fAllFromMe && txin.IsMine();13981399        bool fAllToMe = true;1400        foreach(const CTxOut& txout, wtx.vout)1401            fAllToMe = fAllToMe && txout.IsMine();14021403        if (fAllFromMe)1404        {1405            //1406            // Debit1407            //1408            foreach(const CTxOut& txout, wtx.vout)1409            {1410                if (txout.IsMine())1411                    continue;14121413                if (wtx.mapValue["to"].empty())1414                {1415                    // Offline transaction1416                    uint160 hash160;1417                    if (ExtractHash160(txout.scriptPubKey, hash160))1418                    {1419                        string strAddress = Hash160ToAddress(hash160);1420                        strHTML += "<b>To:</b> ";1421                        if (mapAddressBook.count(strAddress) && !mapAddressBook[strAddress].empty())1422                            strHTML += mapAddressBook[strAddress] + " ";1423                        strHTML += strAddress;1424                        strHTML += "<br>";1425                    }1426                }14271428                strHTML += "<b>Debit:</b> " + FormatMoney(-txout.nValue) + "<br>";1429            }14301431            if (fAllToMe)1432            {1433                // Payment to self1434                /// issue: can't tell which is the payment and which is the change anymore1435                //int64 nValue = wtx.vout[0].nValue;1436                //strHTML += "<b>Debit:</b> " + FormatMoney(-nValue) + "<br>";1437                //strHTML += "<b>Credit:</b> " + FormatMoney(nValue) + "<br>";1438            }14391440            int64 nTxFee = nDebit - wtx.GetValueOut();1441            if (nTxFee > 0)1442                strHTML += "<b>Transaction fee:</b> " + FormatMoney(-nTxFee) + "<br>";1443        }1444        else1445        {1446            //1447            // Mixed debit transaction1448            //1449            foreach(const CTxIn& txin, wtx.vin)1450                if (txin.IsMine())1451                    strHTML += "<b>Debit:</b> " + FormatMoney(-txin.GetDebit()) + "<br>";1452            foreach(const CTxOut& txout, wtx.vout)1453                if (txout.IsMine())1454                    strHTML += "<b>Credit:</b> " + FormatMoney(txout.GetCredit()) + "<br>";1455        }1456    }14571458    strHTML += "<b>Net amount:</b> " + FormatMoney(nNet, true) + "<br>";145914601461    //1462    // Message1463    //1464    if (!wtx.mapValue["message"].empty())1465        strHTML += "<br><b>Message:</b><br>" + HtmlEscape(wtx.mapValue["message"], true) + "<br>";14661467    if (wtx.IsCoinBase())1468        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>";146914701471    //1472    // Debug view1473    //1474    if (fDebug)1475    {1476        strHTML += "<hr><br>debug print<br><br>";1477        foreach(const CTxIn& txin, wtx.vin)1478            if (txin.IsMine())1479                strHTML += "<b>Debit:</b> " + FormatMoney(-txin.GetDebit()) + "<br>";1480        foreach(const CTxOut& txout, wtx.vout)1481            if (txout.IsMine())1482                strHTML += "<b>Credit:</b> " + FormatMoney(txout.GetCredit()) + "<br>";14831484        strHTML += "<b>Inputs:</b><br>";1485        CRITICAL_BLOCK(cs_mapWallet)1486        {1487            foreach(const CTxIn& txin, wtx.vin)1488            {1489                COutPoint prevout = txin.prevout;1490                map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);1491                if (mi != mapWallet.end())1492                {1493                    const CWalletTx& prev = (*mi).second;1494                    if (prevout.n < prev.vout.size())1495                    {1496                        strHTML += HtmlEscape(prev.ToString(), true);1497                        strHTML += " &nbsp;&nbsp; " + FormatTxStatus(prev) + ", ";1498                        strHTML = strHTML + "IsMine=" + (prev.vout[prevout.n].IsMine() ? "true" : "false") + "<br>";1499                    }1500                }1501            }1502        }15031504        strHTML += "<br><hr><br><b>Transaction:</b><br>";1505        strHTML += HtmlEscape(wtx.ToString(), true);1506    }1507150815091510    strHTML += "</font></html>";1511    string(strHTML.begin(), strHTML.end()).swap(strHTML);1512    m_htmlWin->SetPage(strHTML);1513    m_buttonOK->SetFocus();1514}15151516void CTxDetailsDialog::OnButtonOK(wxCommandEvent& event)1517{1518    Close();1519    //Destroy();1520}152115221523152415251526//////////////////////////////////////////////////////////////////////////////1527//1528// COptionsDialog1529//15301531COptionsDialog::COptionsDialog(wxWindow* parent) : COptionsDialogBase(parent)1532{1533    // Set up list box of page choices1534    m_listBox->Append("Main");1535    //m_listBox->Append("Test 2");1536    m_listBox->SetSelection(0);1537    SelectPage(0);1538#ifndef __WXMSW__1539    m_checkBoxMinimizeOnClose->SetLabel("&Minimize on close");1540    m_checkBoxStartOnSystemStartup->Enable(false); // not implemented yet1541#endif15421543    // Init values1544    m_textCtrlTransactionFee->SetValue(FormatMoney(nTransactionFee));1545    m_checkBoxLimitProcessors->SetValue(fLimitProcessors);1546    m_spinCtrlLimitProcessors->Enable(fLimitProcessors);1547    m_spinCtrlLimitProcessors->SetValue(nLimitProcessors);1548    int nProcessors = wxThread::GetCPUCount();1549    if (nProcessors < 1)1550        nProcessors = 999;1551    m_spinCtrlLimitProcessors->SetRange(1, nProcessors);1552    m_checkBoxStartOnSystemStartup->SetValue(fTmpStartOnSystemStartup = GetStartOnSystemStartup());1553    m_checkBoxMinimizeToTray->SetValue(fMinimizeToTray);1554    m_checkBoxMinimizeOnClose->SetValue(fMinimizeOnClose);1555    m_checkBoxUseProxy->SetValue(fUseProxy);1556    m_textCtrlProxyIP->Enable(fUseProxy);1557    m_textCtrlProxyPort->Enable(fUseProxy);1558    m_staticTextProxyIP->Enable(fUseProxy);1559    m_staticTextProxyPort->Enable(fUseProxy);1560    m_textCtrlProxyIP->SetValue(addrProxy.ToStringIP());1561    m_textCtrlProxyPort->SetValue(addrProxy.ToStringPort());15621563    m_buttonOK->SetFocus();1564}15651566void COptionsDialog::SelectPage(int nPage)1567{1568    m_panelMain->Show(nPage == 0);1569    m_panelTest2->Show(nPage == 1);15701571    m_scrolledWindow->Layout();1572    m_scrolledWindow->SetScrollbars(0, 0, 0, 0, 0, 0);1573}15741575void COptionsDialog::OnListBox(wxCommandEvent& event)1576{1577    SelectPage(event.GetSelection());1578}15791580void COptionsDialog::OnKillFocusTransactionFee(wxFocusEvent& event)1581{1582    int64 nTmp = nTransactionFee;1583    ParseMoney(m_textCtrlTransactionFee->GetValue(), nTmp);1584    m_textCtrlTransactionFee->SetValue(FormatMoney(nTmp));1585}15861587void COptionsDialog::OnCheckBoxLimitProcessors(wxCommandEvent& event)1588{1589    m_spinCtrlLimitProcessors->Enable(event.IsChecked());1590}15911592void COptionsDialog::OnCheckBoxUseProxy(wxCommandEvent& event)1593{1594    m_textCtrlProxyIP->Enable(event.IsChecked());1595    m_textCtrlProxyPort->Enable(event.IsChecked());1596    m_staticTextProxyIP->Enable(event.IsChecked());1597    m_staticTextProxyPort->Enable(event.IsChecked());1598}15991600CAddress COptionsDialog::GetProxyAddr()1601{1602    // Be careful about byte order, addr.ip and addr.port are big endian1603    CAddress addr(m_textCtrlProxyIP->GetValue() + ":" + m_textCtrlProxyPort->GetValue());1604    if (addr.ip == INADDR_NONE)1605        addr.ip = addrProxy.ip;1606    int nPort = atoi(m_textCtrlProxyPort->GetValue());1607    addr.port = htons(nPort);1608    if (nPort <= 0 || nPort > USHRT_MAX)1609        addr.port = addrProxy.port;1610    return addr;1611}16121613void COptionsDialog::OnKillFocusProxy(wxFocusEvent& event)1614{1615    m_textCtrlProxyIP->SetValue(GetProxyAddr().ToStringIP());1616    m_textCtrlProxyPort->SetValue(GetProxyAddr().ToStringPort());1617}161816191620void COptionsDialog::OnButtonOK(wxCommandEvent& event)1621{1622    OnButtonApply(event);1623    Close();1624}16251626void COptionsDialog::OnButtonCancel(wxCommandEvent& event)1627{1628    Close();1629}16301631void COptionsDialog::OnButtonApply(wxCommandEvent& event)1632{1633    CWalletDB walletdb;16341635    int64 nPrevTransactionFee = nTransactionFee;1636    if (ParseMoney(m_textCtrlTransactionFee->GetValue(), nTransactionFee) && nTransactionFee != nPrevTransactionFee)1637        walletdb.WriteSetting("nTransactionFee", nTransactionFee);16381639    int nPrevMaxProc = (fLimitProcessors ? nLimitProcessors : INT_MAX);1640    if (fLimitProcessors != m_checkBoxLimitProcessors->GetValue())1641    {1642        fLimitProcessors = m_checkBoxLimitProcessors->GetValue();1643        walletdb.WriteSetting("fLimitProcessors", fLimitProcessors);1644    }1645    if (nLimitProcessors != m_spinCtrlLimitProcessors->GetValue())1646    {1647        nLimitProcessors = m_spinCtrlLimitProcessors->GetValue();1648        walletdb.WriteSetting("nLimitProcessors", nLimitProcessors);1649    }1650    if (fGenerateBitcoins && (fLimitProcessors ? nLimitProcessors : INT_MAX) > nPrevMaxProc)1651        GenerateBitcoins(fGenerateBitcoins);16521653    if (fTmpStartOnSystemStartup != m_checkBoxStartOnSystemStartup->GetValue())1654    {1655        fTmpStartOnSystemStartup = m_checkBoxStartOnSystemStartup->GetValue();1656        SetStartOnSystemStartup(fTmpStartOnSystemStartup);1657    }16581659    if (fMinimizeToTray != m_checkBoxMinimizeToTray->GetValue())1660    {1661        fMinimizeToTray = m_checkBoxMinimizeToTray->GetValue();1662        walletdb.WriteSetting("fMinimizeToTray", fMinimizeToTray);1663        ptaskbaricon->Show(fMinimizeToTray || fClosedToTray);1664    }16651666    if (fMinimizeOnClose != m_checkBoxMinimizeOnClose->GetValue())1667    {1668        fMinimizeOnClose = m_checkBoxMinimizeOnClose->GetValue();1669        walletdb.WriteSetting("fMinimizeOnClose", fMinimizeOnClose);1670    }16711672    fUseProxy = m_checkBoxUseProxy->GetValue();1673    walletdb.WriteSetting("fUseProxy", fUseProxy);16741675    addrProxy = GetProxyAddr();1676    walletdb.WriteSetting("addrProxy", addrProxy);1677}1678167916801681168216831684//////////////////////////////////////////////////////////////////////////////1685//1686// CAboutDialog1687//16881689CAboutDialog::CAboutDialog(wxWindow* parent) : CAboutDialogBase(parent)1690{1691    m_staticTextVersion->SetLabel(strprintf("version 0.%d.%d beta", VERSION/100, VERSION%100));16921693    // Workaround until upgrade to wxWidgets supporting UTF-81694    wxString str = m_staticTextMain->GetLabel();1695    if (str.Find('Â') != wxNOT_FOUND)1696        str.Remove(str.Find('Â'), 1);1697    m_staticTextMain->SetLabel(str);1698#ifndef __WXMSW__1699    SetSize(510, 380);1700#endif1701}17021703void CAboutDialog::OnButtonOK(wxCommandEvent& event)1704{1705    Close();1706}1707170817091710171117121713//////////////////////////////////////////////////////////////////////////////1714//1715// CSendDialog1716//17171718CSendDialog::CSendDialog(wxWindow* parent, const wxString& strAddress) : CSendDialogBase(parent)1719{1720    // Init1721    m_textCtrlAddress->SetValue(strAddress);1722    m_choiceTransferType->SetSelection(0);1723    m_bitmapCheckMark->Show(false);1724    fEnabledPrev = true;1725    m_textCtrlAddress->SetFocus();1726    //// todo: should add a display of your balance for convenience1727#ifndef __WXMSW__1728    wxFont fontTmp = m_staticTextInstructions->GetFont();1729    if (fontTmp.GetPointSize() > 9);1730        fontTmp.SetPointSize(9);1731    m_staticTextInstructions->SetFont(fontTmp);1732    SetSize(725, wxDefaultCoord);1733#endif17341735    // Set Icon1736    wxIcon iconSend;1737    iconSend.CopyFromBitmap(wxBitmap(send16noshadow_xpm));1738    SetIcon(iconSend);17391740    wxCommandEvent event;1741    OnTextAddress(event);17421743    // Fixup the tab order1744    m_buttonPaste->MoveAfterInTabOrder(m_buttonCancel);1745    m_buttonAddress->MoveAfterInTabOrder(m_buttonPaste);1746    this->Layout();1747}17481749void CSendDialog::OnTextAddress(wxCommandEvent& event)1750{1751    // Check mark1752    bool fBitcoinAddress = IsValidBitcoinAddress(m_textCtrlAddress->GetValue());1753    m_bitmapCheckMark->Show(fBitcoinAddress);17541755    // Grey out message if bitcoin address1756    bool fEnable = !fBitcoinAddress;1757    m_staticTextFrom->Enable(fEnable);1758    m_textCtrlFrom->Enable(fEnable);1759    m_staticTextMessage->Enable(fEnable);1760    m_textCtrlMessage->Enable(fEnable);1761    m_textCtrlMessage->SetBackgroundColour(wxSystemSettings::GetColour(fEnable ? wxSYS_COLOUR_WINDOW : wxSYS_COLOUR_BTNFACE));1762    if (!fEnable && fEnabledPrev)1763    {1764        strFromSave    = m_textCtrlFrom->GetValue();1765        strMessageSave = m_textCtrlMessage->GetValue();1766        m_textCtrlFrom->SetValue("Will appear as \"From: Unknown\"");1767        m_textCtrlMessage->SetValue("Can't include a message when sending to a Bitcoin address");1768    }1769    else if (fEnable && !fEnabledPrev)1770    {1771        m_textCtrlFrom->SetValue(strFromSave);1772        m_textCtrlMessage->SetValue(strMessageSave);1773    }1774    fEnabledPrev = fEnable;1775}17761777void CSendDialog::OnKillFocusAmount(wxFocusEvent& event)1778{1779    // Reformat the amount1780    if (m_textCtrlAmount->GetValue().Trim().empty())1781        return;1782    int64 nTmp;1783    if (ParseMoney(m_textCtrlAmount->GetValue(), nTmp))1784        m_textCtrlAmount->SetValue(FormatMoney(nTmp));1785}17861787void CSendDialog::OnButtonAddressBook(wxCommandEvent& event)1788{1789    // Open address book1790    CAddressBookDialog dialog(this, m_textCtrlAddress->GetValue(), true);1791    if (dialog.ShowModal())1792        m_textCtrlAddress->SetValue(dialog.GetAddress());1793}17941795void CSendDialog::OnButtonPaste(wxCommandEvent& event)1796{1797    // Copy clipboard to address box1798    if (wxTheClipboard->Open())1799    {1800        if (wxTheClipboard->IsSupported(wxDF_TEXT))1801        {1802            wxTextDataObject data;1803            wxTheClipboard->GetData(data);1804            m_textCtrlAddress->SetValue(data.GetText());1805        }1806        wxTheClipboard->Close();1807    }1808}18091810void CSendDialog::OnButtonSend(wxCommandEvent& event)1811{1812    CWalletTx wtx;1813    string strAddress = (string)m_textCtrlAddress->GetValue();18141815    // Parse amount1816    int64 nValue = 0;1817    if (!ParseMoney(m_textCtrlAmount->GetValue(), nValue) || nValue <= 0)1818    {1819        wxMessageBox("Error in amount  ", "Send Coins");1820        return;1821    }1822    if (nValue > GetBalance())1823    {1824        wxMessageBox("Amount exceeds your balance  ", "Send Coins");1825        return;1826    }1827    if (nValue + nTransactionFee > GetBalance())1828    {1829        wxMessageBox(string("Total exceeds your balance when the ") + FormatMoney(nTransactionFee) + " transaction fee is included  ", "Send Coins");1830        return;1831    }18321833    // Parse bitcoin address1834    uint160 hash160;1835    bool fBitcoinAddress = AddressToHash160(strAddress, hash160);18361837    if (fBitcoinAddress)1838    {1839        // Send to bitcoin address1840        CScript scriptPubKey;1841        scriptPubKey << OP_DUP << OP_HASH160 << hash160 << OP_EQUALVERIFY << OP_CHECKSIG;18421843        if (!SendMoney(scriptPubKey, nValue, wtx))1844            return;18451846        wxMessageBox("Payment sent  ", "Sending...");1847    }1848    else1849    {1850        // Parse IP address1851        CAddress addr(strAddress);1852        if (!addr.IsValid())1853        {1854            wxMessageBox("Invalid address  ", "Send Coins");1855            return;1856        }18571858        // Message1859        wtx.mapValue["to"] = strAddress;1860        wtx.mapValue["from"] = m_textCtrlFrom->GetValue();1861        wtx.mapValue["message"] = m_textCtrlMessage->GetValue();18621863        // Send to IP address1864        CSendingDialog* pdialog = new CSendingDialog(this, addr, nValue, wtx);1865        if (!pdialog->ShowModal())1866            return;1867    }18681869    if (!mapAddressBook.count(strAddress))1870        SetAddressBookName(strAddress, "");18711872    EndModal(true);1873}18741875void CSendDialog::OnButtonCancel(wxCommandEvent& event)1876{1877    // Cancel1878    EndModal(false);1879}1880188118821883188418851886//////////////////////////////////////////////////////////////////////////////1887//1888// CSendingDialog1889//18901891CSendingDialog::CSendingDialog(wxWindow* parent, const CAddress& addrIn, int64 nPriceIn, const CWalletTx& wtxIn) : CSendingDialogBase(NULL) // we have to give null so parent can't destroy us1892{1893    addr = addrIn;1894    nPrice = nPriceIn;1895    wtx = wtxIn;1896    start = wxDateTime::UNow();1897    memset(pszStatus, 0, sizeof(pszStatus));1898    fCanCancel = true;1899    fAbort = false;1900    fSuccess = false;1901    fUIDone = false;1902    fWorkDone = false;1903#ifndef __WXMSW__1904    SetSize(1.2 * GetSize().GetWidth(), 1.05 * GetSize().GetHeight());1905#endif19061907    SetTitle(strprintf("Sending %s to %s", FormatMoney(nPrice).c_str(), wtx.mapValue["to"].c_str()));1908    m_textCtrlStatus->SetValue("");19091910    CreateThread(SendingDialogStartTransfer, this);1911}19121913CSendingDialog::~CSendingDialog()1914{1915    printf("~CSendingDialog()\n");1916}19171918void CSendingDialog::Close()1919{1920    // Last one out turn out the lights.1921    // fWorkDone signals that work side is done and UI thread should call destroy.1922    // fUIDone signals that UI window has closed and work thread should call destroy.1923    // This allows the window to disappear and end modality when cancelled1924    // without making the user wait for ConnectNode to return.  The dialog object1925    // hangs around in the background until the work thread exits.1926    if (IsModal())1927        EndModal(fSuccess);1928    else1929        Show(false);1930    if (fWorkDone)1931        Destroy();1932    else1933        fUIDone = true;1934}19351936void CSendingDialog::OnClose(wxCloseEvent& event)1937{1938    if (!event.CanVeto() || fWorkDone || fAbort || !fCanCancel)1939    {1940        Close();1941    }1942    else1943    {1944        event.Veto();1945        wxCommandEvent cmdevent;1946        OnButtonCancel(cmdevent);1947    }1948}19491950void CSendingDialog::OnButtonOK(wxCommandEvent& event)1951{1952    if (fWorkDone)1953        Close();1954}19551956void CSendingDialog::OnButtonCancel(wxCommandEvent& event)1957{1958    if (fCanCancel)1959        fAbort = true;1960}19611962void CSendingDialog::OnPaint(wxPaintEvent& event)1963{1964    if (strlen(pszStatus) > 130)1965        m_textCtrlStatus->SetValue(string("\n") + pszStatus);1966    else1967        m_textCtrlStatus->SetValue(string("\n\n") + pszStatus);1968    m_staticTextSending->SetFocus();1969    if (!fCanCancel)1970        m_buttonCancel->Enable(false);1971    if (fWorkDone)1972    {1973        m_buttonOK->Enable(true);1974        m_buttonOK->SetFocus();1975        m_buttonCancel->Enable(false);1976    }1977    if (fAbort && fCanCancel && IsShown())1978    {1979        strcpy(pszStatus, "CANCELLED");1980        m_buttonOK->Enable(true);1981        m_buttonOK->SetFocus();1982        m_buttonCancel->Enable(false);1983        m_buttonCancel->SetLabel("Cancelled");1984        Close();1985        wxMessageBox("Transfer cancelled  ", "Sending...", wxOK, this);1986    }1987    event.Skip();1988}198919901991//1992// Everything from here on is not in the UI thread and must only communicate1993// with the rest of the dialog through variables and calling repaint.1994//19951996void CSendingDialog::Repaint()1997{1998    Refresh();1999    wxPaintEvent event;2000    AddPendingEvent(event);2001}20022003bool CSendingDialog::Status()2004{2005    if (fUIDone)2006    {2007        Destroy();2008        return false;2009    }2010    if (fAbort && fCanCancel)2011    {2012        memset(pszStatus, 0, 10);2013        strcpy(pszStatus, "CANCELLED");2014        Repaint();2015        fWorkDone = true;2016        return false;2017    }2018    return true;2019}20202021bool CSendingDialog::Status(const string& str)2022{2023    if (!Status())2024        return false;20252026    // This can be read by the UI thread at any time,2027    // so copy in a way that can be read cleanly at all times.2028    memset(pszStatus, 0, min(str.size()+1, sizeof(pszStatus)));2029    strlcpy(pszStatus, str.c_str(), sizeof(pszStatus));20302031    Repaint();2032    return true;2033}20342035bool CSendingDialog::Error(const string& str)2036{2037    fCanCancel = false;2038    fWorkDone = true;2039    Status(string("Error: ") + str);2040    return false;2041}20422043void SendingDialogStartTransfer(void* parg)2044{2045    ((CSendingDialog*)parg)->StartTransfer();2046}20472048void CSendingDialog::StartTransfer()2049{2050    // Make sure we have enough money2051    if (nPrice + nTransactionFee > GetBalance())2052    {2053        Error("You don't have enough money");2054        return;2055    }20562057    // We may have connected already for product details2058    if (!Status("Connecting..."))2059        return;2060    CNode* pnode = ConnectNode(addr, 15 * 60);2061    if (!pnode)2062    {2063        Error("Unable to connect");2064        return;2065    }20662067    // Send order to seller, with response going to OnReply2 via event handler2068    if (!Status("Requesting public key..."))2069        return;2070    pnode->PushRequest("checkorder", wtx, SendingDialogOnReply2, this);2071}20722073void SendingDialogOnReply2(void* parg, CDataStream& vRecv)2074{2075    ((CSendingDialog*)parg)->OnReply2(vRecv);2076}20772078void CSendingDialog::OnReply2(CDataStream& vRecv)2079{2080    if (!Status("Received public key..."))2081        return;20822083    CScript scriptPubKey;2084    int nRet;2085    try2086    {2087        vRecv >> nRet;2088        if (nRet > 0)2089        {2090            string strMessage;2091            vRecv >> strMessage;2092            Error("Transfer was not accepted");2093            //// todo: enlarge the window and enable a hidden white box to put seller's message2094            return;2095        }2096        vRecv >> scriptPubKey;2097    }2098    catch (...)2099    {2100        //// what do we want to do about this?2101        Error("Invalid response received");2102        return;2103    }21042105    // Pause to give the user a chance to cancel2106    while (wxDateTime::UNow() < start + wxTimeSpan(0, 0, 0, 2 * 1000))2107    {2108        Sleep(200);2109        if (!Status())2110            return;2111    }21122113    CRITICAL_BLOCK(cs_main)2114    {2115        // Pay2116        if (!Status("Creating transaction..."))2117            return;2118        if (nPrice + nTransactionFee > GetBalance())2119        {2120            Error("You don't have enough money");2121            return;2122        }2123        CKey key;2124        int64 nFeeRequired;2125        if (!CreateTransaction(scriptPubKey, nPrice, wtx, key, nFeeRequired))2126        {2127            if (nPrice + nFeeRequired > GetBalance())2128                Error(strprintf("This is an oversized transaction that requires a transaction fee of %s", FormatMoney(nFeeRequired).c_str()));2129            else2130                Error("Transaction creation failed");2131            return;2132        }21332134        // Make sure we're still connected2135        CNode* pnode = ConnectNode(addr, 2 * 60 * 60);2136        if (!pnode)2137        {2138            Error("Lost connection, transaction cancelled");2139            return;2140        }21412142        // Last chance to cancel2143        Sleep(50);2144        if (!Status())2145            return;2146        fCanCancel = false;2147        if (fAbort)2148        {2149            fCanCancel = true;2150            if (!Status())2151                return;2152            fCanCancel = false;2153        }2154        if (!Status("Sending payment..."))2155            return;21562157        // Commit2158        if (!CommitTransactionSpent(wtx, key))2159        {2160            Error("Error finalizing payment");2161            return;2162        }21632164        // Send payment tx to seller, with response going to OnReply3 via event handler2165        pnode->PushRequest("submitorder", wtx, SendingDialogOnReply3, this);21662167        // Accept and broadcast transaction2168        if (!wtx.AcceptTransaction())2169            printf("ERROR: CSendingDialog : wtxNew.AcceptTransaction() %s failed\n", wtx.GetHash().ToString().c_str());2170        wtx.RelayWalletTransaction();21712172        Status("Waiting for confirmation...");2173        MainFrameRepaint();2174    }2175}21762177void SendingDialogOnReply3(void* parg, CDataStream& vRecv)2178{2179    ((CSendingDialog*)parg)->OnReply3(vRecv);2180}21812182void CSendingDialog::OnReply3(CDataStream& vRecv)2183{2184    int nRet;2185    try2186    {2187        vRecv >> nRet;2188        if (nRet > 0)2189        {2190            Error("The payment was sent, but the recipient was unable to verify it.\n"2191                  "The transaction is recorded and will credit to the recipient,\n"2192                  "but the comment information will be blank.");2193            return;2194        }2195    }2196    catch (...)2197    {2198        //// what do we want to do about this?2199        Error("Payment was sent, but an invalid response was received");2200        return;2201    }22022203    fSuccess = true;2204    fWorkDone = true;2205    Status("Payment completed");2206}2207220822092210221122122213//////////////////////////////////////////////////////////////////////////////2214//2215// CYourAddressDialog2216//22172218CYourAddressDialog::CYourAddressDialog(wxWindow* parent, const string& strInitSelected) : CYourAddressDialogBase(parent)2219{2220    // Init column headers2221    m_listCtrl->InsertColumn(0, "Label", wxLIST_FORMAT_LEFT, 200);2222    m_listCtrl->InsertColumn(1, "Bitcoin Address", wxLIST_FORMAT_LEFT, 350);2223    m_listCtrl->SetFocus();22242225    // Fill listctrl with address book data2226    CRITICAL_BLOCK(cs_mapKeys)2227    {2228        foreach(const PAIRTYPE(string, string)& item, mapAddressBook)2229        {2230            string strAddress = item.first;2231            string strName = item.second;2232            uint160 hash160;2233            bool fMine = (AddressToHash160(strAddress, hash160) && mapPubKeys.count(hash160));2234            if (fMine)2235            {2236                int nIndex = InsertLine(m_listCtrl, strName, strAddress);2237                if (strAddress == strInitSelected)2238                    m_listCtrl->SetItemState(nIndex, wxLIST_STATE_SELECTED|wxLIST_STATE_FOCUSED, wxLIST_STATE_SELECTED|wxLIST_STATE_FOCUSED);2239            }2240        }2241    }2242}22432244wxString CYourAddressDialog::GetAddress()2245{2246    int nIndex = GetSelection(m_listCtrl);2247    if (nIndex == -1)2248        return "";2249    return GetItemText(m_listCtrl, nIndex, 1);2250}22512252void CYourAddressDialog::OnListEndLabelEdit(wxListEvent& event)2253{2254    // Update address book with edited name2255    if (event.IsEditCancelled())2256        return;2257    string strAddress = (string)GetItemText(m_listCtrl, event.GetIndex(), 1);2258    SetAddressBookName(strAddress, string(event.GetText()));2259    pframeMain->RefreshListCtrl();2260}22612262void CYourAddressDialog::OnListItemSelected(wxListEvent& event)2263{2264}22652266void CYourAddressDialog::OnListItemActivated(wxListEvent& event)2267{2268    // Doubleclick edits item2269    wxCommandEvent event2;2270    OnButtonRename(event2);2271}22722273void CYourAddressDialog::OnButtonRename(wxCommandEvent& event)2274{2275    // Ask new name2276    int nIndex = GetSelection(m_listCtrl);2277    if (nIndex == -1)2278        return;2279    string strName = (string)m_listCtrl->GetItemText(nIndex);2280    string strAddress = (string)GetItemText(m_listCtrl, nIndex, 1);2281    CGetTextFromUserDialog dialog(this, "Edit Address Label", "New Label", strName);2282    if (!dialog.ShowModal())2283        return;2284    strName = dialog.GetValue();22852286    // Change name2287    SetAddressBookName(strAddress, strName);2288    m_listCtrl->SetItemText(nIndex, strName);2289    pframeMain->RefreshListCtrl();2290}22912292void CYourAddressDialog::OnButtonNew(wxCommandEvent& event)2293{2294    // Ask name2295    CGetTextFromUserDialog dialog(this, "New Bitcoin Address", "Label", "");2296    if (!dialog.ShowModal())2297        return;2298    string strName = dialog.GetValue();22992300    // Generate new key2301    string strAddress = PubKeyToAddress(GenerateNewKey());2302    SetAddressBookName(strAddress, strName);23032304    // Add to list and select it2305    int nIndex = InsertLine(m_listCtrl, strName, strAddress);2306    SetSelection(m_listCtrl, nIndex);2307    m_listCtrl->SetFocus();2308}23092310void CYourAddressDialog::OnButtonCopy(wxCommandEvent& event)2311{2312    // Copy address box to clipboard2313    if (wxTheClipboard->Open())2314    {2315        wxTheClipboard->SetData(new wxTextDataObject(GetAddress()));2316        wxTheClipboard->Close();2317    }2318}23192320void CYourAddressDialog::OnButtonOK(wxCommandEvent& event)2321{2322    // OK2323    EndModal(true);2324}23252326void CYourAddressDialog::OnButtonCancel(wxCommandEvent& event)2327{2328    // Cancel2329    EndModal(false);2330}23312332void CYourAddressDialog::OnClose(wxCloseEvent& event)2333{2334    // Close2335    EndModal(false);2336}2337233823392340234123422343//////////////////////////////////////////////////////////////////////////////2344//2345// CAddressBookDialog2346//23472348CAddressBookDialog::CAddressBookDialog(wxWindow* parent, const wxString& strInitSelected, bool fSendingIn) : CAddressBookDialogBase(parent)2349{2350    fSending = fSendingIn;2351    if (!fSending)2352        m_buttonCancel->Show(false);23532354    // Init column headers2355    m_listCtrl->InsertColumn(0, "Name", wxLIST_FORMAT_LEFT, 200);2356    m_listCtrl->InsertColumn(1, "Address", wxLIST_FORMAT_LEFT, 350);2357    m_listCtrl->SetFocus();23582359    // Set Icon2360    wxIcon iconAddressBook;2361    iconAddressBook.CopyFromBitmap(wxBitmap(addressbook16_xpm));2362    SetIcon(iconAddressBook);23632364    // Fill listctrl with address book data2365    CRITICAL_BLOCK(cs_mapKeys)2366    {2367        foreach(const PAIRTYPE(string, string)& item, mapAddressBook)2368        {2369            string strAddress = item.first;2370            string strName = item.second;2371            uint160 hash160;2372            bool fMine = (AddressToHash160(strAddress, hash160) && mapPubKeys.count(hash160));2373            if (!fMine)2374            {2375                int nIndex = InsertLine(m_listCtrl, strName, strAddress);2376                if (strAddress == strInitSelected)2377                    m_listCtrl->SetItemState(nIndex, wxLIST_STATE_SELECTED|wxLIST_STATE_FOCUSED, wxLIST_STATE_SELECTED|wxLIST_STATE_FOCUSED);2378            }2379        }2380    }2381}23822383wxString CAddressBookDialog::GetAddress()2384{2385    int nIndex = GetSelection(m_listCtrl);2386    if (nIndex == -1)2387        return "";2388    return GetItemText(m_listCtrl, nIndex, 1);2389}23902391void CAddressBookDialog::OnListEndLabelEdit(wxListEvent& event)2392{2393    // Update address book with edited name2394    if (event.IsEditCancelled())2395        return;2396    string strAddress = (string)GetItemText(m_listCtrl, event.GetIndex(), 1);2397    SetAddressBookName(strAddress, string(event.GetText()));2398    pframeMain->RefreshListCtrl();2399}24002401void CAddressBookDialog::OnListItemSelected(wxListEvent& event)2402{2403}24042405void CAddressBookDialog::OnListItemActivated(wxListEvent& event)2406{2407    if (fSending)2408    {2409        // Doubleclick returns selection2410        EndModal(GetAddress() != "" ? 2 : 0);2411    }2412    else2413    {2414        // Doubleclick edits item2415        wxCommandEvent event2;2416        OnButtonEdit(event2);2417    }2418}24192420bool CAddressBookDialog::CheckIfMine(const string& strAddress, const string& strTitle)2421{2422    uint160 hash160;2423    bool fMine = (AddressToHash160(strAddress, hash160) && mapPubKeys.count(hash160));2424    if (fMine)2425        wxMessageBox("This is one of your own addresses for receiving payments and cannot be entered in the address book.  ", strTitle);2426    return fMine;2427}24282429void CAddressBookDialog::OnButtonEdit(wxCommandEvent& event)2430{2431    // Ask new name2432    int nIndex = GetSelection(m_listCtrl);2433    if (nIndex == -1)2434        return;2435    string strName = (string)m_listCtrl->GetItemText(nIndex);2436    string strAddress = (string)GetItemText(m_listCtrl, nIndex, 1);2437    string strAddressOrg = strAddress;2438    do2439    {2440        CGetTextFromUserDialog dialog(this, "Edit Address", "Name", strName, "Address", strAddress);2441        if (!dialog.ShowModal())2442            return;2443        strName = dialog.GetValue1();2444        strAddress = dialog.GetValue2();2445    }2446    while (CheckIfMine(strAddress, "Edit Address"));24472448    // Change name2449    if (strAddress != strAddressOrg)2450        CWalletDB().EraseName(strAddressOrg);2451    SetAddressBookName(strAddress, strName);2452    m_listCtrl->SetItem(nIndex, 1, strAddress);2453    m_listCtrl->SetItemText(nIndex, strName);2454    pframeMain->RefreshListCtrl();2455}24562457void CAddressBookDialog::OnButtonNew(wxCommandEvent& event)2458{2459    // Ask name2460    string strName;2461    string strAddress;2462    do2463    {2464        CGetTextFromUserDialog dialog(this, "New Address", "Name", strName, "Address", strAddress);2465        if (!dialog.ShowModal())2466            return;2467        strName = dialog.GetValue1();2468        strAddress = dialog.GetValue2();2469    }2470    while (CheckIfMine(strAddress, "New Address"));24712472    // Add to list and select it2473    SetAddressBookName(strAddress, strName);2474    int nIndex = InsertLine(m_listCtrl, strName, strAddress);2475    SetSelection(m_listCtrl, nIndex);2476    m_listCtrl->SetFocus();2477    pframeMain->RefreshListCtrl();2478}24792480void CAddressBookDialog::OnButtonDelete(wxCommandEvent& event)2481{2482    for (int nIndex = m_listCtrl->GetItemCount()-1; nIndex >= 0; nIndex--)2483    {2484        if (m_listCtrl->GetItemState(nIndex, wxLIST_STATE_SELECTED))2485        {2486            string strAddress = (string)GetItemText(m_listCtrl, nIndex, 1);2487            CWalletDB().EraseName(strAddress);2488            m_listCtrl->DeleteItem(nIndex);2489        }2490    }2491    pframeMain->RefreshListCtrl();2492}24932494void CAddressBookDialog::OnButtonCopy(wxCommandEvent& event)2495{2496    // Copy address box to clipboard2497    if (wxTheClipboard->Open())2498    {2499        wxTheClipboard->SetData(new wxTextDataObject(GetAddress()));2500        wxTheClipboard->Close();2501    }2502}25032504void CAddressBookDialog::OnButtonOK(wxCommandEvent& event)2505{2506    // OK2507    EndModal(GetAddress() != "" ? 1 : 0);2508}25092510void CAddressBookDialog::OnButtonCancel(wxCommandEvent& event)2511{2512    // Cancel2513    EndModal(0);2514}25152516void CAddressBookDialog::OnClose(wxCloseEvent& event)2517{2518    // Close2519    EndModal(0);2520}2521252225232524252525262527//////////////////////////////////////////////////////////////////////////////2528//2529// CProductsDialog2530//25312532bool CompareIntStringPairBestFirst(const pair<int, string>& item1, const pair<int, string>& item2)2533{2534    return (item1.first > item2.first);2535}25362537CProductsDialog::CProductsDialog(wxWindow* parent) : CProductsDialogBase(parent)2538{2539    // Init column headers2540    m_listCtrl->InsertColumn(0, "Title",  wxLIST_FORMAT_LEFT, 200);2541    m_listCtrl->InsertColumn(1, "Price",  wxLIST_FORMAT_LEFT, 80);2542    m_listCtrl->InsertColumn(2, "Seller", wxLIST_FORMAT_LEFT, 80);2543    m_listCtrl->InsertColumn(3, "Stars",  wxLIST_FORMAT_LEFT, 50);2544    m_listCtrl->InsertColumn(4, "Power",  wxLIST_FORMAT_LEFT, 50);25452546    // Tally top categories2547    map<string, int> mapTopCategories;2548    CRITICAL_BLOCK(cs_mapProducts)2549        for (map<uint256, CProduct>::iterator mi = mapProducts.begin(); mi != mapProducts.end(); ++mi)2550            mapTopCategories[(*mi).second.mapValue["category"]]++;25512552    // Sort top categories2553    vector<pair<int, string> > vTopCategories;2554    for (map<string, int>::iterator mi = mapTopCategories.begin(); mi != mapTopCategories.end(); ++mi)2555        vTopCategories.push_back(make_pair((*mi).second, (*mi).first));2556    sort(vTopCategories.begin(), vTopCategories.end(), CompareIntStringPairBestFirst);25572558    // Fill categories combo box2559    int nLimit = 250;2560    for (vector<pair<int, string> >::iterator it = vTopCategories.begin(); it != vTopCategories.end() && nLimit-- > 0; ++it)2561        m_comboBoxCategory->Append((*it).second);25622563    // Fill window with initial search2564    //wxCommandEvent event;2565    //OnButtonSearch(event);2566}25672568void CProductsDialog::OnCombobox(wxCommandEvent& event)2569{2570    OnButtonSearch(event);2571}25722573bool CompareProductsBestFirst(const CProduct* p1, const CProduct* p2)2574{2575    return (p1->nAtoms > p2->nAtoms);2576}25772578void CProductsDialog::OnButtonSearch(wxCommandEvent& event)2579{2580    string strCategory = (string)m_comboBoxCategory->GetValue();2581    string strSearch = (string)m_textCtrlSearch->GetValue();25822583    // Search products2584    vector<CProduct*> vProductsFound;2585    CRITICAL_BLOCK(cs_mapProducts)2586    {2587        for (map<uint256, CProduct>::iterator mi = mapProducts.begin(); mi != mapProducts.end(); ++mi)2588        {2589            CProduct& product = (*mi).second;2590            if (product.mapValue["category"].find(strCategory) != -1)2591            {2592                if (product.mapValue["title"].find(strSearch) != -1 ||2593                    product.mapValue["description"].find(strSearch) != -1 ||2594                    product.mapValue["seller"].find(strSearch) != -1)2595                {2596                    vProductsFound.push_back(&product);2597                }2598            }2599        }2600    }26012602    // Sort2603    sort(vProductsFound.begin(), vProductsFound.end(), CompareProductsBestFirst);26042605    // Display2606    foreach(CProduct* pproduct, vProductsFound)2607    {2608        InsertLine(m_listCtrl,2609                   pproduct->mapValue["title"],2610                   pproduct->mapValue["price"],2611                   pproduct->mapValue["seller"],2612                   pproduct->mapValue["stars"],2613                   itostr(pproduct->nAtoms));2614    }2615}26162617void CProductsDialog::OnListItemActivated(wxListEvent& event)2618{2619    // Doubleclick opens product2620    CViewProductDialog* pdialog = new CViewProductDialog(this, m_vProduct[event.GetIndex()]);2621    pdialog->Show();2622}26232624262526262627262826292630//////////////////////////////////////////////////////////////////////////////2631//2632// CEditProductDialog2633//26342635CEditProductDialog::CEditProductDialog(wxWindow* parent) : CEditProductDialogBase(parent)2636{2637    m_textCtrlLabel[0 ] = m_textCtrlLabel0;2638    m_textCtrlLabel[1 ] = m_textCtrlLabel1;2639    m_textCtrlLabel[2 ] = m_textCtrlLabel2;2640    m_textCtrlLabel[3 ] = m_textCtrlLabel3;2641    m_textCtrlLabel[4 ] = m_textCtrlLabel4;2642    m_textCtrlLabel[5 ] = m_textCtrlLabel5;2643    m_textCtrlLabel[6 ] = m_textCtrlLabel6;2644    m_textCtrlLabel[7 ] = m_textCtrlLabel7;2645    m_textCtrlLabel[8 ] = m_textCtrlLabel8;2646    m_textCtrlLabel[9 ] = m_textCtrlLabel9;2647    m_textCtrlLabel[10] = m_textCtrlLabel10;2648    m_textCtrlLabel[11] = m_textCtrlLabel11;2649    m_textCtrlLabel[12] = m_textCtrlLabel12;2650    m_textCtrlLabel[13] = m_textCtrlLabel13;2651    m_textCtrlLabel[14] = m_textCtrlLabel14;2652    m_textCtrlLabel[15] = m_textCtrlLabel15;2653    m_textCtrlLabel[16] = m_textCtrlLabel16;2654    m_textCtrlLabel[17] = m_textCtrlLabel17;2655    m_textCtrlLabel[18] = m_textCtrlLabel18;2656    m_textCtrlLabel[19] = m_textCtrlLabel19;26572658    m_textCtrlField[0 ] = m_textCtrlField0;2659    m_textCtrlField[1 ] = m_textCtrlField1;2660    m_textCtrlField[2 ] = m_textCtrlField2;2661    m_textCtrlField[3 ] = m_textCtrlField3;2662    m_textCtrlField[4 ] = m_textCtrlField4;2663    m_textCtrlField[5 ] = m_textCtrlField5;2664    m_textCtrlField[6 ] = m_textCtrlField6;2665    m_textCtrlField[7 ] = m_textCtrlField7;2666    m_textCtrlField[8 ] = m_textCtrlField8;2667    m_textCtrlField[9 ] = m_textCtrlField9;2668    m_textCtrlField[10] = m_textCtrlField10;2669    m_textCtrlField[11] = m_textCtrlField11;2670    m_textCtrlField[12] = m_textCtrlField12;2671    m_textCtrlField[13] = m_textCtrlField13;2672    m_textCtrlField[14] = m_textCtrlField14;2673    m_textCtrlField[15] = m_textCtrlField15;2674    m_textCtrlField[16] = m_textCtrlField16;2675    m_textCtrlField[17] = m_textCtrlField17;2676    m_textCtrlField[18] = m_textCtrlField18;2677    m_textCtrlField[19] = m_textCtrlField19;26782679    m_buttonDel[0 ] = m_buttonDel0;2680    m_buttonDel[1 ] = m_buttonDel1;2681    m_buttonDel[2 ] = m_buttonDel2;2682    m_buttonDel[3 ] = m_buttonDel3;2683    m_buttonDel[4 ] = m_buttonDel4;2684    m_buttonDel[5 ] = m_buttonDel5;2685    m_buttonDel[6 ] = m_buttonDel6;2686    m_buttonDel[7 ] = m_buttonDel7;2687    m_buttonDel[8 ] = m_buttonDel8;2688    m_buttonDel[9 ] = m_buttonDel9;2689    m_buttonDel[10] = m_buttonDel10;2690    m_buttonDel[11] = m_buttonDel11;2691    m_buttonDel[12] = m_buttonDel12;2692    m_buttonDel[13] = m_buttonDel13;2693    m_buttonDel[14] = m_buttonDel14;2694    m_buttonDel[15] = m_buttonDel15;2695    m_buttonDel[16] = m_buttonDel16;2696    m_buttonDel[17] = m_buttonDel17;2697    m_buttonDel[18] = m_buttonDel18;2698    m_buttonDel[19] = m_buttonDel19;26992700    for (int i = 1; i < FIELDS_MAX; i++)2701        ShowLine(i, false);27022703    LayoutAll();2704}27052706void CEditProductDialog::LayoutAll()2707{2708    m_scrolledWindow->Layout();2709    m_scrolledWindow->GetSizer()->Fit(m_scrolledWindow);2710    this->Layout();2711}27122713void CEditProductDialog::ShowLine(int i, bool fShow)2714{2715    m_textCtrlLabel[i]->Show(fShow);2716    m_textCtrlField[i]->Show(fShow);2717    m_buttonDel[i]->Show(fShow);2718}27192720void CEditProductDialog::OnButtonDel0(wxCommandEvent& event)  { OnButtonDel(event, 0); }2721void CEditProductDialog::OnButtonDel1(wxCommandEvent& event)  { OnButtonDel(event, 1); }2722void CEditProductDialog::OnButtonDel2(wxCommandEvent& event)  { OnButtonDel(event, 2); }2723void CEditProductDialog::OnButtonDel3(wxCommandEvent& event)  { OnButtonDel(event, 3); }2724void CEditProductDialog::OnButtonDel4(wxCommandEvent& event)  { OnButtonDel(event, 4); }2725void CEditProductDialog::OnButtonDel5(wxCommandEvent& event)  { OnButtonDel(event, 5); }2726void CEditProductDialog::OnButtonDel6(wxCommandEvent& event)  { OnButtonDel(event, 6); }2727void CEditProductDialog::OnButtonDel7(wxCommandEvent& event)  { OnButtonDel(event, 7); }2728void CEditProductDialog::OnButtonDel8(wxCommandEvent& event)  { OnButtonDel(event, 8); }2729void CEditProductDialog::OnButtonDel9(wxCommandEvent& event)  { OnButtonDel(event, 9); }2730void CEditProductDialog::OnButtonDel10(wxCommandEvent& event) { OnButtonDel(event, 10); }2731void CEditProductDialog::OnButtonDel11(wxCommandEvent& event) { OnButtonDel(event, 11); }2732void CEditProductDialog::OnButtonDel12(wxCommandEvent& event) { OnButtonDel(event, 12); }2733void CEditProductDialog::OnButtonDel13(wxCommandEvent& event) { OnButtonDel(event, 13); }2734void CEditProductDialog::OnButtonDel14(wxCommandEvent& event) { OnButtonDel(event, 14); }2735void CEditProductDialog::OnButtonDel15(wxCommandEvent& event) { OnButtonDel(event, 15); }2736void CEditProductDialog::OnButtonDel16(wxCommandEvent& event) { OnButtonDel(event, 16); }2737void CEditProductDialog::OnButtonDel17(wxCommandEvent& event) { OnButtonDel(event, 17); }2738void CEditProductDialog::OnButtonDel18(wxCommandEvent& event) { OnButtonDel(event, 18); }2739void CEditProductDialog::OnButtonDel19(wxCommandEvent& event) { OnButtonDel(event, 19); }27402741void CEditProductDialog::OnButtonDel(wxCommandEvent& event, int n)2742{2743    Freeze();2744    int x, y;2745    m_scrolledWindow->GetViewStart(&x, &y);2746    int i;2747    for (i = n; i < FIELDS_MAX-1; i++)2748    {2749        m_textCtrlLabel[i]->SetValue(m_textCtrlLabel[i+1]->GetValue());2750        m_textCtrlField[i]->SetValue(m_textCtrlField[i+1]->GetValue());2751        if (!m_buttonDel[i+1]->IsShown())2752            break;2753    }2754    m_textCtrlLabel[i]->SetValue("");2755    m_textCtrlField[i]->SetValue("");2756    ShowLine(i, false);2757    m_buttonAddField->Enable(true);2758    LayoutAll();2759    m_scrolledWindow->Scroll(0, y);2760    Thaw();2761}27622763void CEditProductDialog::OnButtonAddField(wxCommandEvent& event)2764{2765    for (int i = 0; i < FIELDS_MAX; i++)2766    {2767        if (!m_buttonDel[i]->IsShown())2768        {2769            Freeze();2770            ShowLine(i, true);2771            if (i == FIELDS_MAX-1)2772                m_buttonAddField->Enable(false);2773            LayoutAll();2774            m_scrolledWindow->Scroll(0, 99999);2775            Thaw();2776            break;2777        }2778    }2779}27802781void CEditProductDialog::OnButtonSend(wxCommandEvent& event)2782{2783    CProduct product;2784    GetProduct(product);27852786    // Sign the detailed product2787    product.vchPubKeyFrom = keyUser.GetPubKey();2788    if (!keyUser.Sign(product.GetSigHash(), product.vchSig))2789    {2790        wxMessageBox("Error digitally signing the product  ");2791        return;2792    }27932794    // Save detailed product2795    AddToMyProducts(product);27962797    // Strip down to summary product2798    product.mapDetails.clear();2799    product.vOrderForm.clear();28002801    // Sign the summary product2802    if (!keyUser.Sign(product.GetSigHash(), product.vchSig))2803    {2804        wxMessageBox("Error digitally signing the product  ");2805        return;2806    }28072808    // Verify2809    if (!product.CheckProduct())2810    {2811        wxMessageBox("Errors found in product  ");2812        return;2813    }28142815    // Broadcast2816    AdvertStartPublish(pnodeLocalHost, MSG_PRODUCT, 0, product);28172818    Destroy();2819}28202821void CEditProductDialog::OnButtonPreview(wxCommandEvent& event)2822{2823    CProduct product;2824    GetProduct(product);2825    CViewProductDialog* pdialog = new CViewProductDialog(this, product);2826    pdialog->Show();2827}28282829void CEditProductDialog::OnButtonCancel(wxCommandEvent& event)2830{2831    Destroy();2832}28332834void CEditProductDialog::SetProduct(const CProduct& productIn)2835{2836    CProduct product = productIn;28372838    m_comboBoxCategory->SetValue(product.mapValue["category"]);2839    m_textCtrlTitle->SetValue(product.mapValue["title"]);2840    m_textCtrlPrice->SetValue(product.mapValue["price"]);2841    m_textCtrlDescription->SetValue(product.mapValue["description"]);2842    m_textCtrlInstructions->SetValue(product.mapValue["instructions"]);28432844    for (int i = 0; i < FIELDS_MAX; i++)2845    {2846        bool fUsed = i < product.vOrderForm.size();2847        m_buttonDel[i]->Show(fUsed);2848        m_textCtrlLabel[i]->Show(fUsed);2849        m_textCtrlField[i]->Show(fUsed);2850        if (!fUsed)2851            continue;28522853        m_textCtrlLabel[i]->SetValue(product.vOrderForm[i].first);2854        string strControl = product.vOrderForm[i].second;2855        if (strControl.substr(0, 5) == "text=")2856            m_textCtrlField[i]->SetValue("");2857        else if (strControl.substr(0, 7) == "choice=")2858            m_textCtrlField[i]->SetValue(strControl.substr(7));2859        else2860            m_textCtrlField[i]->SetValue(strControl);2861    }2862}28632864void CEditProductDialog::GetProduct(CProduct& product)2865{2866    // map<string, string> mapValue;2867    // vector<pair<string, string> > vOrderForm;28682869    product.mapValue["category"]     = m_comboBoxCategory->GetValue().Trim();2870    product.mapValue["title"]        = m_textCtrlTitle->GetValue().Trim();2871    product.mapValue["price"]        = m_textCtrlPrice->GetValue().Trim();2872    product.mapValue["description"]  = m_textCtrlDescription->GetValue().Trim();2873    product.mapValue["instructions"] = m_textCtrlInstructions->GetValue().Trim();28742875    for (int i = 0; i < FIELDS_MAX; i++)2876    {2877        if (m_buttonDel[i]->IsShown())2878        {2879            string strLabel = (string)m_textCtrlLabel[i]->GetValue().Trim();2880            string strControl = (string)m_textCtrlField[i]->GetValue();2881            if (strControl.empty())2882                strControl = "text=";2883            else2884                strControl = "choice=" + strControl;2885            product.vOrderForm.push_back(make_pair(strLabel, strControl));2886        }2887    }2888}28892890289128922893289428952896//////////////////////////////////////////////////////////////////////////////2897//2898// CViewProductDialog2899//29002901CViewProductDialog::CViewProductDialog(wxWindow* parent, const CProduct& productIn) : CViewProductDialogBase(parent)2902{2903    Connect(wxEVT_REPLY1, wxCommandEventHandler(CViewProductDialog::OnReply1), NULL, this);2904    AddCallbackAvailable(GetEventHandler());29052906    // Fill display with product summary while waiting for details2907    product = productIn;2908    UpdateProductDisplay(false);29092910    m_buttonBack->Enable(false);2911    m_buttonNext->Enable(!product.vOrderForm.empty());2912    m_htmlWinReviews->Show(true);2913    m_scrolledWindow->Show(false);2914    this->Layout();29152916    // Request details from seller2917    CreateThread(ThreadRequestProductDetails, new pair<CProduct, wxEvtHandler*>(product, GetEventHandler()));2918}29192920CViewProductDialog::~CViewProductDialog()2921{2922    RemoveCallbackAvailable(GetEventHandler());2923}29242925void ThreadRequestProductDetails(void* parg)2926{2927    // Extract parameters2928    pair<CProduct, wxEvtHandler*>* pitem = (pair<CProduct, wxEvtHandler*>*)parg;2929    CProduct product = pitem->first;2930    wxEvtHandler* pevthandler = pitem->second;2931    delete pitem;29322933    // Connect to seller2934    CNode* pnode = ConnectNode(product.addr, 5 * 60);2935    if (!pnode)2936    {2937        CDataStream ssEmpty;2938        AddPendingReplyEvent1(pevthandler, ssEmpty);2939        return;2940    }29412942    // Request detailed product, with response going to OnReply1 via dialog's event handler2943    pnode->PushRequest("getdetails", product.GetHash(), AddPendingReplyEvent1, (void*)pevthandler);2944}29452946void CViewProductDialog::OnReply1(wxCommandEvent& event)2947{2948    CDataStream ss = GetStreamFromEvent(event);2949    if (ss.empty())2950    {2951        product.mapValue["description"] = "-- CAN'T CONNECT TO SELLER --\n";2952        UpdateProductDisplay(true);2953        return;2954    }29552956    int nRet;2957    CProduct product2;2958    try2959    {2960        ss >> nRet;2961        if (nRet > 0)2962            throw false;2963        ss >> product2;2964        if (product2.GetHash() != product.GetHash())2965            throw false;2966        if (!product2.CheckSignature())2967            throw false;2968    }2969    catch (...)2970    {2971        product.mapValue["description"] = "-- INVALID RESPONSE --\n";2972        UpdateProductDisplay(true);2973        return;2974    }29752976    product = product2;2977    UpdateProductDisplay(true);2978}29792980bool CompareReviewsBestFirst(const CReview* p1, const CReview* p2)2981{2982    return (p1->nAtoms > p2->nAtoms);2983}29842985void CViewProductDialog::UpdateProductDisplay(bool fDetails)2986{2987    // Product and reviews2988    string strHTML;2989    strHTML.reserve(4000);2990    strHTML += "<html>\n"2991               "<head>\n"2992               "<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">\n"2993               "</head>\n"2994               "<body>\n";2995    strHTML += "<b>Category:</b> " + HtmlEscape(product.mapValue["category"]) + "<br>\n";2996    strHTML += "<b>Title:</b> "    + HtmlEscape(product.mapValue["title"])    + "<br>\n";2997    strHTML += "<b>Price:</b> "    + HtmlEscape(product.mapValue["price"])    + "<br>\n";29982999    if (!fDetails)3000        strHTML += "<b>Loading details...</b><br>\n<br>\n";3001    else3002        strHTML += HtmlEscape(product.mapValue["description"], true) + "<br>\n<br>\n";30033004    strHTML += "<b>Reviews:</b><br>\n<br>\n";30053006    if (!product.vchPubKeyFrom.empty())3007    {3008        CReviewDB reviewdb("r");30093010        // Get reviews3011        vector<CReview> vReviews;3012        reviewdb.ReadReviews(product.GetUserHash(), vReviews);30133014        // Get reviewer's number of atoms3015        vector<CReview*> vSortedReviews;3016        vSortedReviews.reserve(vReviews.size());3017        for (vector<CReview>::reverse_iterator it = vReviews.rbegin(); it != vReviews.rend(); ++it)3018        {3019            CReview& review = *it;3020            CUser user;3021            reviewdb.ReadUser(review.GetUserHash(), user);3022            review.nAtoms = user.GetAtomCount();3023            vSortedReviews.push_back(&review);3024        }30253026        reviewdb.Close();30273028        // Sort3029        stable_sort(vSortedReviews.begin(), vSortedReviews.end(), CompareReviewsBestFirst);30303031        // Format reviews3032        foreach(CReview* preview, vSortedReviews)3033        {3034            CReview& review = *preview;3035            int nStars = atoi(review.mapValue["stars"].c_str());3036            if (nStars < 1 || nStars > 5)3037                continue;30383039            strHTML += "<b>" + itostr(nStars) + (nStars == 1 ? " star" : " stars") + "</b>";3040            strHTML += " &nbsp;&nbsp;&nbsp; ";3041            strHTML += DateStr(atoi64(review.mapValue["date"])) + "<br>\n";3042            strHTML += HtmlEscape(review.mapValue["review"], true);3043            strHTML += "<br>\n<br>\n";3044        }3045    }30463047    strHTML += "</body>\n</html>\n";30483049    // Shrink capacity to fit3050    string(strHTML.begin(), strHTML.end()).swap(strHTML);30513052    m_htmlWinReviews->SetPage(strHTML);30533054    ///// need to find some other indicator to use so can allow empty order form3055    if (product.vOrderForm.empty())3056        return;30573058    // Order form3059    m_staticTextInstructions->SetLabel(product.mapValue["instructions"]);3060    for (int i = 0; i < FIELDS_MAX; i++)3061    {3062        m_staticTextLabel[i] = NULL;3063        m_textCtrlField[i] = NULL;3064        m_choiceField[i] = NULL;3065    }30663067    // Construct flexgridsizer3068    wxBoxSizer* bSizer21 = (wxBoxSizer*)m_scrolledWindow->GetSizer();3069    wxFlexGridSizer* fgSizer;3070    fgSizer = new wxFlexGridSizer(0, 2, 0, 0);3071    fgSizer->AddGrowableCol(1);3072    fgSizer->SetFlexibleDirection(wxBOTH);3073    fgSizer->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED);30743075    // Construct order form fields3076    wxWindow* windowLast = NULL;3077    for (int i = 0; i < product.vOrderForm.size(); i++)3078    {3079        string strLabel = product.vOrderForm[i].first;3080        string strControl = product.vOrderForm[i].second;30813082        if (strLabel.size() < 20)3083            strLabel.insert(strLabel.begin(), 20 - strLabel.size(), ' ');30843085        m_staticTextLabel[i] = new wxStaticText(m_scrolledWindow, wxID_ANY, strLabel, wxDefaultPosition, wxDefaultSize, wxALIGN_RIGHT);3086        m_staticTextLabel[i]->Wrap(-1);3087        fgSizer->Add(m_staticTextLabel[i], 0, wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxALL, 5);30883089        if (strControl.substr(0, 5) == "text=")3090        {3091            m_textCtrlField[i] = new wxTextCtrl(m_scrolledWindow, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0);3092            fgSizer->Add(m_textCtrlField[i], 1, wxALL|wxALIGN_CENTER_VERTICAL|wxEXPAND, 5);3093            windowLast = m_textCtrlField[i];3094        }3095        else if (strControl.substr(0, 7) == "choice=")3096        {3097            vector<string> vChoices;3098            ParseString(strControl.substr(7), ',', vChoices);30993100            wxArrayString arraystring;3101            foreach(const string& str, vChoices)3102                arraystring.Add(str);31033104            m_choiceField[i] = new wxChoice(m_scrolledWindow, wxID_ANY, wxDefaultPosition, wxDefaultSize, arraystring, 0);3105            fgSizer->Add(m_choiceField[i], 0, wxALL|wxALIGN_CENTER_VERTICAL, 5);3106            windowLast = m_choiceField[i];3107        }3108        else3109        {3110            m_textCtrlField[i] = new wxTextCtrl(m_scrolledWindow, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0);3111            fgSizer->Add(m_textCtrlField[i], 1, wxALL|wxALIGN_CENTER_VERTICAL|wxEXPAND, 5);3112            m_staticTextLabel[i]->Show(false);3113            m_textCtrlField[i]->Show(false);3114        }3115    }31163117    // Insert after instructions and before submit/cancel buttons3118    bSizer21->Insert(2, fgSizer, 0, wxEXPAND|wxRIGHT|wxLEFT, 5);3119    m_scrolledWindow->Layout();3120    bSizer21->Fit(m_scrolledWindow);3121    this->Layout();31223123    // Fixup the tab order3124    m_buttonSubmitForm->MoveAfterInTabOrder(windowLast);3125    m_buttonCancelForm->MoveAfterInTabOrder(m_buttonSubmitForm);3126    //m_buttonBack->MoveAfterInTabOrder(m_buttonCancelForm);3127    //m_buttonNext->MoveAfterInTabOrder(m_buttonBack);3128    //m_buttonCancel->MoveAfterInTabOrder(m_buttonNext);3129    this->Layout();3130}31313132void CViewProductDialog::GetOrder(CWalletTx& wtx)3133{3134    wtx.SetNull();3135    for (int i = 0; i < product.vOrderForm.size(); i++)3136    {3137        string strValue;3138        if (m_textCtrlField[i])3139            strValue = m_textCtrlField[i]->GetValue().Trim();3140        else3141            strValue = m_choiceField[i]->GetStringSelection();3142        wtx.vOrderForm.push_back(make_pair(m_staticTextLabel[i]->GetLabel(), strValue));3143    }3144}31453146void CViewProductDialog::OnButtonSubmitForm(wxCommandEvent& event)3147{3148    m_buttonSubmitForm->Enable(false);3149    m_buttonCancelForm->Enable(false);31503151    CWalletTx wtx;3152    GetOrder(wtx);31533154    CSendingDialog* pdialog = new CSendingDialog(this, product.addr, atoi64(product.mapValue["price"]), wtx);3155    if (!pdialog->ShowModal())3156    {3157        m_buttonSubmitForm->Enable(true);3158        m_buttonCancelForm->Enable(true);3159        return;3160    }3161}31623163void CViewProductDialog::OnButtonCancelForm(wxCommandEvent& event)3164{3165    Destroy();3166}31673168void CViewProductDialog::OnButtonBack(wxCommandEvent& event)3169{3170    Freeze();3171    m_htmlWinReviews->Show(true);3172    m_scrolledWindow->Show(false);3173    m_buttonBack->Enable(false);3174    m_buttonNext->Enable(!product.vOrderForm.empty());3175    this->Layout();3176    Thaw();3177}31783179void CViewProductDialog::OnButtonNext(wxCommandEvent& event)3180{3181    if (!product.vOrderForm.empty())3182    {3183        Freeze();3184        m_htmlWinReviews->Show(false);3185        m_scrolledWindow->Show(true);3186        m_buttonBack->Enable(true);3187        m_buttonNext->Enable(false);3188        this->Layout();3189        Thaw();3190    }3191}31923193void CViewProductDialog::OnButtonCancel(wxCommandEvent& event)3194{3195    Destroy();3196}31973198319932003201320232033204//////////////////////////////////////////////////////////////////////////////3205//3206// CViewOrderDialog3207//32083209CViewOrderDialog::CViewOrderDialog(wxWindow* parent, CWalletTx order, bool fReceived) : CViewOrderDialogBase(parent)3210{3211    int64 nPrice = (fReceived ? order.GetCredit() : order.GetDebit());32123213    string strHTML;3214    strHTML.reserve(4000);3215    strHTML += "<html>\n"3216               "<head>\n"3217               "<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">\n"3218               "</head>\n"3219               "<body>\n";3220    strHTML += "<b>Time:</b> "   + HtmlEscape(DateTimeStr(order.nTimeReceived)) + "<br>\n";3221    strHTML += "<b>Price:</b> "  + HtmlEscape(FormatMoney(nPrice)) + "<br>\n";3222    strHTML += "<b>Status:</b> " + HtmlEscape(FormatTxStatus(order)) + "<br>\n";32233224    strHTML += "<table>\n";3225    for (int i = 0; i < order.vOrderForm.size(); i++)3226    {3227        strHTML += " <tr><td><b>" + HtmlEscape(order.vOrderForm[i].first) + ":</b></td>";3228        strHTML += "<td>" + HtmlEscape(order.vOrderForm[i].second) + "</td></tr>\n";3229    }3230    strHTML += "</table>\n";32313232    strHTML += "</body>\n</html>\n";32333234    // Shrink capacity to fit3235    // (strings are ref counted, so it may live on in SetPage)3236    string(strHTML.begin(), strHTML.end()).swap(strHTML);32373238    m_htmlWin->SetPage(strHTML);3239}32403241void CViewOrderDialog::OnButtonOK(wxCommandEvent& event)3242{3243    Destroy();3244}32453246324732483249325032513252//////////////////////////////////////////////////////////////////////////////3253//3254// CEditReviewDialog3255//32563257CEditReviewDialog::CEditReviewDialog(wxWindow* parent) : CEditReviewDialogBase(parent)3258{3259}32603261void CEditReviewDialog::OnButtonSubmit(wxCommandEvent& event)3262{3263    if (m_choiceStars->GetSelection() == -1)3264    {3265        wxMessageBox("Please select a rating  ");3266        return;3267    }32683269    CReview review;3270    GetReview(review);32713272    // Sign the review3273    review.vchPubKeyFrom = keyUser.GetPubKey();3274    if (!keyUser.Sign(review.GetSigHash(), review.vchSig))3275    {3276        wxMessageBox("Unable to digitally sign the review  ");3277        return;3278    }32793280    // Broadcast3281    if (!review.AcceptReview())3282    {3283        wxMessageBox("Save failed  ");3284        return;3285    }3286    RelayMessage(CInv(MSG_REVIEW, review.GetHash()), review);32873288    Destroy();3289}32903291void CEditReviewDialog::OnButtonCancel(wxCommandEvent& event)3292{3293    Destroy();3294}32953296void CEditReviewDialog::GetReview(CReview& review)3297{3298    review.mapValue["time"]   = i64tostr(GetAdjustedTime());3299    review.mapValue["stars"]  = itostr(m_choiceStars->GetSelection()+1);3300    review.mapValue["review"] = m_textCtrlReview->GetValue();3301}33023303330433053306330733083309//////////////////////////////////////////////////////////////////////////////3310//3311// CMyTaskBarIcon3312//33133314enum3315{3316    ID_TASKBAR_RESTORE = 10001,3317    ID_TASKBAR_OPTIONS,3318    ID_TASKBAR_GENERATE,3319    ID_TASKBAR_EXIT,3320};33213322BEGIN_EVENT_TABLE(CMyTaskBarIcon, wxTaskBarIcon)3323    EVT_TASKBAR_LEFT_DCLICK(CMyTaskBarIcon::OnLeftButtonDClick)3324    EVT_MENU(ID_TASKBAR_RESTORE, CMyTaskBarIcon::OnMenuRestore)3325    EVT_MENU(ID_TASKBAR_OPTIONS, CMyTaskBarIcon::OnMenuOptions)3326    EVT_MENU(ID_TASKBAR_GENERATE, CMyTaskBarIcon::OnMenuGenerate)3327    EVT_UPDATE_UI(ID_TASKBAR_GENERATE, CMyTaskBarIcon::OnUpdateUIGenerate)3328    EVT_MENU(ID_TASKBAR_EXIT, CMyTaskBarIcon::OnMenuExit)3329END_EVENT_TABLE()33303331void CMyTaskBarIcon::Show(bool fShow)3332{3333    static char pszPrevTip[200];3334    if (fShow)3335    {3336        string strTooltip = "Bitcoin";3337        if (fGenerateBitcoins)3338            strTooltip = "Bitcoin - Generating";3339        if (fGenerateBitcoins && vNodes.empty())3340            strTooltip = "Bitcoin - (not connected)";33413342        // Optimization, only update when changed, using char array to be reentrant3343        if (strncmp(pszPrevTip, strTooltip.c_str(), sizeof(pszPrevTip)-1) != 0)3344        {3345            strlcpy(pszPrevTip, strTooltip.c_str(), sizeof(pszPrevTip));3346#ifdef __WXMSW__3347            SetIcon(wxICON(bitcoin), strTooltip);3348#else3349            SetIcon(bitcoin20_xpm, strTooltip);3350#endif3351        }3352    }3353    else3354    {3355        strlcpy(pszPrevTip, "", sizeof(pszPrevTip));3356        RemoveIcon();3357    }3358}33593360void CMyTaskBarIcon::Hide()3361{3362    Show(false);3363}33643365void CMyTaskBarIcon::OnLeftButtonDClick(wxTaskBarIconEvent& event)3366{3367    Restore();3368}33693370void CMyTaskBarIcon::OnMenuRestore(wxCommandEvent& event)3371{3372    Restore();3373}33743375void CMyTaskBarIcon::OnMenuOptions(wxCommandEvent& event)3376{3377    // Since it's modal, get the main window to do it3378    wxCommandEvent event2(wxEVT_COMMAND_MENU_SELECTED, wxID_MENUOPTIONSOPTIONS);3379    pframeMain->AddPendingEvent(event2);3380}33813382void CMyTaskBarIcon::Restore()3383{3384    pframeMain->Show();3385    wxIconizeEvent event(0, false);3386    pframeMain->AddPendingEvent(event);3387    pframeMain->Iconize(false);3388    pframeMain->Raise();3389}33903391void CMyTaskBarIcon::OnMenuGenerate(wxCommandEvent& event)3392{3393    GenerateBitcoins(event.IsChecked());3394}33953396void CMyTaskBarIcon::OnUpdateUIGenerate(wxUpdateUIEvent& event)3397{3398    event.Check(fGenerateBitcoins);3399}34003401void CMyTaskBarIcon::OnMenuExit(wxCommandEvent& event)3402{3403    pframeMain->Close(true);3404}34053406void CMyTaskBarIcon::UpdateTooltip()3407{3408    if (IsIconInstalled())3409        Show(true);3410}34113412wxMenu* CMyTaskBarIcon::CreatePopupMenu()3413{3414    wxMenu* pmenu = new wxMenu;3415    pmenu->Append(ID_TASKBAR_RESTORE, "&Open Bitcoin");3416    pmenu->Append(ID_TASKBAR_OPTIONS, "O&ptions...");3417    pmenu->AppendCheckItem(ID_TASKBAR_GENERATE, "&Generate Coins")->Check(fGenerateBitcoins);3418#ifndef __WXMAC_OSX__ // Mac has built-in quit menu3419    pmenu->AppendSeparator();3420    pmenu->Append(ID_TASKBAR_EXIT, "E&xit");3421#endif3422    return pmenu;3423}34243425342634273428342934303431343234333434//////////////////////////////////////////////////////////////////////////////3435//3436// CMyApp3437//34383439// Define a new application3440class CMyApp: public wxApp3441{3442  public:3443    CMyApp(){};3444    ~CMyApp(){};3445    bool OnInit();3446    bool OnInit2();3447    int OnExit();34483449    // 2nd-level exception handling: we get all the exceptions occurring in any3450    // event handler here3451    virtual bool OnExceptionInMainLoop();34523453    // 3rd, and final, level exception handling: whenever an unhandled3454    // exception is caught, this function is called3455    virtual void OnUnhandledException();34563457    // and now for something different: this function is called in case of a3458    // crash (e.g. dereferencing null pointer, division by 0, ...)3459    virtual void OnFatalException();3460};34613462IMPLEMENT_APP(CMyApp)34633464bool CMyApp::OnInit()3465{3466    bool fRet = false;3467    try3468    {3469        fRet = OnInit2();3470    }3471    catch (std::exception& e) {3472        PrintException(&e, "OnInit()");3473    } catch (...) {3474        PrintException(NULL, "OnInit()");3475    }3476    if (!fRet)3477        Shutdown(NULL);3478    return fRet;3479}34803481bool CMyApp::OnInit2()3482{3483#ifdef _MSC_VER3484    // Turn off microsoft heap dump noise for now3485    _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);3486    _CrtSetReportFile(_CRT_WARN, CreateFile("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));3487#endif3488#if defined(__WXMSW__) && defined(__WXDEBUG__)3489    // Disable malfunctioning wxWidgets debug assertion3490    g_isPainting = 10000;3491#endif3492    wxImage::AddHandler(new wxPNGHandler);3493#ifdef __WXMSW__3494    SetAppName("Bitcoin");3495#else3496    SetAppName("bitcoin");3497    umask(077);3498#endif34993500    //3501    // Parameters3502    //3503    ParseParameters(argc, argv);3504    if (mapArgs.count("-?") || mapArgs.count("--help"))3505    {3506#ifdef __WXMSW__3507        string strUsage =3508            "Usage: bitcoin [options]\t\t\t\t\t\t\n"3509            "Options:\n"3510            "  -gen\t\t  Generate coins\n"3511            "  -gen=0\t\t  Don't generate coins\n"3512            "  -min\t\t  Start minimized\n"3513            "  -datadir=<dir>\t  Specify data directory\n"3514            "  -proxy=<ip:port>\t  Connect through socks4 proxy\n"3515            "  -addnode=<ip>\t  Add a node to connect to\n"3516            "  -connect=<ip>\t  Connect only to the specified node\n"3517            "  -?\t\t  This help message\n";3518        wxMessageBox(strUsage, "Bitcoin", wxOK);3519#else3520        string strUsage =3521            "Usage: bitcoin [options]\n"3522            "Options:\n"3523            "  -gen              Generate coins\n"3524            "  -gen=0            Don't generate coins\n"3525            "  -min              Start minimized\n"3526            "  -datadir=<dir>    Specify data directory\n"3527            "  -proxy=<ip:port>  Connect through socks4 proxy\n"3528            "  -addnode=<ip>     Add a node to connect to\n"3529            "  -connect=<ip>     Connect only to the specified node\n"3530            "  -?                This help message\n";3531        fprintf(stderr, "%s", strUsage.c_str());3532#endif3533        return false;3534    }35353536    if (mapArgs.count("-datadir"))3537        strlcpy(pszSetDataDir, mapArgs["-datadir"].c_str(), sizeof(pszSetDataDir));35383539    if (mapArgs.count("-debug"))3540        fDebug = true;35413542    if (mapArgs.count("-printtodebugger"))3543        fPrintToDebugger = true;35443545    if (!fDebug && !pszSetDataDir[0])3546        ShrinkDebugFile();3547    printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");3548    printf("Bitcoin version %d%s, OS version %s\n", VERSION, pszSubVer, wxGetOsDescription().mb_str());35493550    if (mapArgs.count("-loadblockindextest"))3551    {3552        CTxDB txdb("r");3553        txdb.LoadBlockIndex();3554        PrintBlockTree();3555        return false;3556    }35573558    //3559    // Limit to single instance per user3560    // Required to protect the database files if we're going to keep deleting log.*3561    //3562#ifdef __WXMSW__3563    // todo: wxSingleInstanceChecker wasn't working on Linux, never deleted its lock file3564    //  maybe should go by whether successfully bind port 8333 instead3565    wxString strMutexName = wxString("bitcoin_running.") + getenv("HOMEPATH");3566    for (int i = 0; i < strMutexName.size(); i++)3567        if (!isalnum(strMutexName[i]))3568            strMutexName[i] = '.';3569    wxSingleInstanceChecker* psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);3570    if (psingleinstancechecker->IsAnotherRunning())3571    {3572        printf("Existing instance found\n");3573        unsigned int nStart = GetTime();3574        loop3575        {3576            // TODO: find out how to do this in Linux, or replace with wxWidgets commands3577            // Show the previous instance and exit3578            HWND hwndPrev = FindWindow("wxWindowClassNR", "Bitcoin");3579            if (hwndPrev)3580            {3581                if (IsIconic(hwndPrev))3582                    ShowWindow(hwndPrev, SW_RESTORE);3583                SetForegroundWindow(hwndPrev);3584                return false;3585            }35863587            if (GetTime() > nStart + 60)3588                return false;35893590            // Resume this instance if the other exits3591            delete psingleinstancechecker;3592            Sleep(1000);3593            psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);3594            if (!psingleinstancechecker->IsAnotherRunning())3595                break;3596        }3597    }3598#endif35993600    // Bind to the port early so we can tell if another instance is already running.3601    // This is a backup to wxSingleInstanceChecker, which doesn't work on Linux.3602    string strErrors;3603    if (!BindListenPort(strErrors))3604    {3605        wxMessageBox(strErrors, "Bitcoin");3606        return false;3607    }36083609    //3610    // Load data files3611    //3612    bool fFirstRun;3613    strErrors = "";3614    int64 nStart;36153616    printf("Loading addresses...\n");3617    nStart = GetTimeMillis();3618    if (!LoadAddresses())3619        strErrors += "Error loading addr.dat      \n";3620    printf(" addresses   %15"PRI64d"ms\n", GetTimeMillis() - nStart);36213622    printf("Loading block index...\n");3623    nStart = GetTimeMillis();3624    if (!LoadBlockIndex())3625        strErrors += "Error loading blkindex.dat      \n";3626    printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);36273628    printf("Loading wallet...\n");3629    nStart = GetTimeMillis();3630    if (!LoadWallet(fFirstRun))3631        strErrors += "Error loading wallet.dat      \n";3632    printf(" wallet      %15"PRI64d"ms\n", GetTimeMillis() - nStart);36333634    printf("Done loading\n");36353636        //// debug print3637        printf("mapBlockIndex.size() = %d\n",   mapBlockIndex.size());3638        printf("nBestHeight = %d\n",            nBestHeight);3639        printf("mapKeys.size() = %d\n",         mapKeys.size());3640        printf("mapPubKeys.size() = %d\n",      mapPubKeys.size());3641        printf("mapWallet.size() = %d\n",       mapWallet.size());3642        printf("mapAddressBook.size() = %d\n",  mapAddressBook.size());36433644    if (!strErrors.empty())3645    {3646        wxMessageBox(strErrors, "Bitcoin");3647        return false;3648    }36493650    // Add wallet transactions that aren't already in a block to mapTransactions3651    ReacceptWalletTransactions();36523653    //3654    // Parameters3655    //3656    if (mapArgs.count("-printblockindex") || mapArgs.count("-printblocktree"))3657    {3658        PrintBlockTree();3659        return false;3660    }36613662    if (mapArgs.count("-printblock"))3663    {3664        string strMatch = mapArgs["-printblock"];3665        int nFound = 0;3666        for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)3667        {3668            uint256 hash = (*mi).first;3669            if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)3670            {3671                CBlockIndex* pindex = (*mi).second;3672                CBlock block;3673                block.ReadFromDisk(pindex);3674                block.BuildMerkleTree();3675                block.print();3676                printf("\n");3677                nFound++;3678            }3679        }3680        if (nFound == 0)3681            printf("No blocks matching %s were found\n", strMatch.c_str());3682        return false;3683    }36843685    if (mapArgs.count("-gen"))3686    {3687        if (mapArgs["-gen"].empty())3688            fGenerateBitcoins = true;3689        else3690            fGenerateBitcoins = (atoi(mapArgs["-gen"].c_str()) != 0);3691    }36923693    if (mapArgs.count("-proxy"))3694    {3695        fUseProxy = true;3696        addrProxy = CAddress(mapArgs["-proxy"]);3697        if (!addrProxy.IsValid())3698        {3699            wxMessageBox("Invalid -proxy address", "Bitcoin");3700            return false;3701        }3702    }37033704    if (mapArgs.count("-addnode"))3705    {3706        CAddrDB addrdb;3707        foreach(string strAddr, mapMultiArgs["-addnode"])3708        {3709            CAddress addr(strAddr, NODE_NETWORK);3710            addr.nTime = 0; // so it won't relay unless successfully connected3711            if (addr.IsValid())3712                AddAddress(addrdb, addr);3713        }3714    }37153716    //3717    // Create the main frame window3718    //3719    pframeMain = new CMainFrame(NULL);3720    if (mapArgs.count("-min"))3721        pframeMain->Iconize(true);3722    pframeMain->Show(true);  // have to show first to get taskbar button to hide3723    if (fMinimizeToTray && pframeMain->IsIconized())3724        fClosedToTray = true;3725    pframeMain->Show(!fClosedToTray);3726    ptaskbaricon->Show(fMinimizeToTray || fClosedToTray);37273728    CreateThread(ThreadDelayedRepaint, NULL);37293730    if (!CheckDiskSpace())3731        return false;37323733    RandAddSeedPerfmon();37343735    if (!CreateThread(StartNode, NULL))3736        wxMessageBox("Error: CreateThread(StartNode) failed", "Bitcoin");37373738    if (fFirstRun)3739        SetStartOnSystemStartup(true);374037413742    //3743    // Tests3744    //3745#ifdef __WXMSW__3746    if (argc >= 2 && stricmp(argv[1], "-send") == 0)3747#else3748    if (argc >= 2 && strcmp(argv[1], "-send") == 0)3749#endif3750    {3751        int64 nValue = 1;3752        if (argc >= 3)3753            ParseMoney(argv[2], nValue);37543755        string strAddress;3756        if (argc >= 4)3757            strAddress = argv[3];3758        CAddress addr(strAddress);37593760        CWalletTx wtx;3761        wtx.mapValue["to"] = strAddress;3762        wtx.mapValue["from"] = addrLocalHost.ToString();3763        wtx.mapValue["message"] = "command line send";37643765        // Send to IP address3766        CSendingDialog* pdialog = new CSendingDialog(pframeMain, addr, nValue, wtx);3767        if (!pdialog->ShowModal())3768            return false;3769    }37703771    return true;3772}37733774int CMyApp::OnExit()3775{3776    Shutdown(NULL);3777    return wxApp::OnExit();3778}37793780bool CMyApp::OnExceptionInMainLoop()3781{3782    try3783    {3784        throw;3785    }3786    catch (std::exception& e)3787    {3788        PrintException(&e, "CMyApp::OnExceptionInMainLoop()");3789        wxLogWarning("Exception %s %s", typeid(e).name(), e.what());3790        Sleep(1000);3791        throw;3792    }3793    catch (...)3794    {3795        PrintException(NULL, "CMyApp::OnExceptionInMainLoop()");3796        wxLogWarning("Unknown exception");3797        Sleep(1000);3798        throw;3799    }38003801    return true;3802}38033804void CMyApp::OnUnhandledException()3805{3806    // this shows how we may let some exception propagate uncaught3807    try3808    {3809        throw;3810    }3811    catch (std::exception& e)3812    {3813        PrintException(&e, "CMyApp::OnUnhandledException()");3814        wxLogWarning("Exception %s %s", typeid(e).name(), e.what());3815        Sleep(1000);3816        throw;3817    }3818    catch (...)3819    {3820        PrintException(NULL, "CMyApp::OnUnhandledException()");3821        wxLogWarning("Unknown exception");3822        Sleep(1000);3823        throw;3824    }3825}38263827void CMyApp::OnFatalException()3828{3829    wxMessageBox("Program has crashed and will terminate.  ", "Bitcoin", wxOK | wxICON_ERROR);3830}383138323833383438353836#ifdef __WXMSW__3837typedef WINSHELLAPI BOOL (WINAPI *PSHGETSPECIALFOLDERPATHA)(HWND hwndOwner, LPSTR lpszPath, int nFolder, BOOL fCreate);38383839string MyGetSpecialFolderPath(int nFolder, bool fCreate)3840{3841    char pszPath[MAX_PATH+100] = "";38423843    // SHGetSpecialFolderPath is not usually available on NT 4.03844    HMODULE hShell32 = LoadLibrary("shell32.dll");3845    if (hShell32)3846    {3847        PSHGETSPECIALFOLDERPATHA pSHGetSpecialFolderPath =3848            (PSHGETSPECIALFOLDERPATHA)GetProcAddress(hShell32, "SHGetSpecialFolderPathA");3849        if (pSHGetSpecialFolderPath)3850            (*pSHGetSpecialFolderPath)(NULL, pszPath, nFolder, fCreate);3851        FreeModule(hShell32);3852    }38533854    // Backup option3855    if (pszPath[0] == '\0')3856    {3857        if (nFolder == CSIDL_STARTUP)3858        {3859            strcpy(pszPath, getenv("USERPROFILE"));3860            strcat(pszPath, "\\Start Menu\\Programs\\Startup");3861        }3862        else if (nFolder == CSIDL_APPDATA)3863        {3864            strcpy(pszPath, getenv("APPDATA"));3865        }3866    }38673868    return pszPath;3869}38703871string StartupShortcutPath()3872{3873    return MyGetSpecialFolderPath(CSIDL_STARTUP, true) + "\\Bitcoin.lnk";3874}38753876bool GetStartOnSystemStartup()3877{3878    return wxFileExists(StartupShortcutPath());3879}38803881void SetStartOnSystemStartup(bool fAutoStart)3882{3883    // If the shortcut exists already, remove it for updating3884    remove(StartupShortcutPath().c_str());38853886    if (fAutoStart)3887    {3888        CoInitialize(NULL);38893890        // Get a pointer to the IShellLink interface.3891        IShellLink* psl = NULL;3892        HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL,3893                                CLSCTX_INPROC_SERVER, IID_IShellLink,3894                                reinterpret_cast<void**>(&psl));38953896        if (SUCCEEDED(hres))3897        {3898            // Get the current executable path3899            char pszExePath[MAX_PATH];3900            GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));39013902            // Set the path to the shortcut target3903            psl->SetPath(pszExePath);3904            PathRemoveFileSpec(pszExePath);3905            psl->SetWorkingDirectory(pszExePath);3906            psl->SetShowCmd(SW_SHOWMINNOACTIVE);39073908            // Query IShellLink for the IPersistFile interface for3909            // saving the shortcut in persistent storage.3910            IPersistFile* ppf = NULL;3911            hres = psl->QueryInterface(IID_IPersistFile,3912                                       reinterpret_cast<void**>(&ppf));3913            if (SUCCEEDED(hres))3914            {3915                WCHAR pwsz[MAX_PATH];3916                // Ensure that the string is ANSI.3917                MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().c_str(), -1, pwsz, MAX_PATH);3918                // Save the link by calling IPersistFile::Save.3919                hres = ppf->Save(pwsz, TRUE);3920                ppf->Release();3921            }3922            psl->Release();3923        }3924        CoUninitialize();3925    }3926}3927#else3928bool GetStartOnSystemStartup() { return false; }3929void SetStartOnSystemStartup(bool fAutoStart) { }3930#endif3931393239333934393539363937393839393940

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