bitcoin-qt cannot be used as command line rpc client
[novacoin.git] / src / init.cpp
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2011 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
5 #include "headers.h"
6 #include "db.h"
7 #include "bitcoinrpc.h"
8 #include "net.h"
9 #include "init.h"
10 #include "strlcpy.h"
11 #include <boost/filesystem.hpp>
12 #include <boost/filesystem/fstream.hpp>
13 #include <boost/interprocess/sync/file_lock.hpp>
14
15 using namespace std;
16 using namespace boost;
17
18 CWallet* pwalletMain;
19
20 //////////////////////////////////////////////////////////////////////////////
21 //
22 // Shutdown
23 //
24
25 void ExitTimeout(void* parg)
26 {
27 #ifdef __WXMSW__
28     Sleep(5000);
29     ExitProcess(0);
30 #endif
31 }
32
33 void Shutdown(void* parg)
34 {
35     static CCriticalSection cs_Shutdown;
36     static bool fTaken;
37     bool fFirstThread;
38     CRITICAL_BLOCK(cs_Shutdown)
39     {
40         fFirstThread = !fTaken;
41         fTaken = true;
42     }
43     static bool fExit;
44     if (fFirstThread)
45     {
46         fShutdown = true;
47         nTransactionsUpdated++;
48         DBFlush(false);
49         StopNode();
50         DBFlush(true);
51         boost::filesystem::remove(GetPidFile());
52         UnregisterWallet(pwalletMain);
53         delete pwalletMain;
54         CreateThread(ExitTimeout, NULL);
55         Sleep(50);
56         printf("Bitcoin exiting\n\n");
57         fExit = true;
58         exit(0);
59     }
60     else
61     {
62         while (!fExit)
63             Sleep(500);
64         Sleep(100);
65         ExitThread(0);
66     }
67 }
68
69 void HandleSIGTERM(int)
70 {
71     fRequestShutdown = true;
72 }
73
74
75
76
77
78
79 //////////////////////////////////////////////////////////////////////////////
80 //
81 // Start
82 //
83 #if !defined(QT_GUI) && !defined(GUI)
84 int main(int argc, char* argv[])
85 {
86     bool fRet = false;
87     fRet = AppInit(argc, argv);
88
89     if (fRet && fDaemon)
90         return 0;
91
92     return 1;
93 }
94 #endif
95
96 bool AppInit(int argc, char* argv[])
97 {
98     bool fRet = false;
99     try
100     {
101         fRet = AppInit2(argc, argv);
102     }
103     catch (std::exception& e) {
104         PrintException(&e, "AppInit()");
105     } catch (...) {
106         PrintException(NULL, "AppInit()");
107     }
108     if (!fRet)
109         Shutdown(NULL);
110     return fRet;
111 }
112
113 bool AppInit2(int argc, char* argv[])
114 {
115 #ifdef _MSC_VER
116     // Turn off microsoft heap dump noise
117     _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
118     _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
119 #endif
120 #if _MSC_VER >= 1400
121     // Disable confusing "helpful" text message on abort, ctrl-c
122     _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
123 #endif
124 #ifndef __WXMSW__
125     umask(077);
126 #endif
127 #ifndef __WXMSW__
128     // Clean shutdown on SIGTERM
129     struct sigaction sa;
130     sa.sa_handler = HandleSIGTERM;
131     sigemptyset(&sa.sa_mask);
132     sa.sa_flags = 0;
133     sigaction(SIGTERM, &sa, NULL);
134     sigaction(SIGINT, &sa, NULL);
135     sigaction(SIGHUP, &sa, NULL);
136 #endif
137
138     //
139     // Parameters
140     //
141     ParseParameters(argc, argv);
142
143     if (mapArgs.count("-datadir"))
144     {
145         if (filesystem::is_directory(filesystem::system_complete(mapArgs["-datadir"])))
146         {
147             filesystem::path pathDataDir = filesystem::system_complete(mapArgs["-datadir"]);
148             strlcpy(pszSetDataDir, pathDataDir.string().c_str(), sizeof(pszSetDataDir));
149         }
150         else
151         {
152             fprintf(stderr, "Error: Specified directory does not exist\n");
153             Shutdown(NULL);
154         }
155     }
156
157
158     ReadConfigFile(mapArgs, mapMultiArgs); // Must be done after processing datadir
159
160     if (mapArgs.count("-?") || mapArgs.count("--help"))
161     {
162         string strUsage = string() +
163           _("Bitcoin version") + " " + FormatFullVersion() + "\n\n" +
164           _("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" +
165             "  bitcoin [options]                   \t  " + "\n" +
166             "  bitcoin [options] <command> [params]\t  " + _("Send command to -server or bitcoind\n") +
167             "  bitcoin [options] help              \t\t  " + _("List commands\n") +
168             "  bitcoin [options] help <command>    \t\t  " + _("Get help for a command\n") +
169           _("Options:\n") +
170             "  -conf=<file>     \t\t  " + _("Specify configuration file (default: bitcoin.conf)\n") +
171             "  -pid=<file>      \t\t  " + _("Specify pid file (default: bitcoind.pid)\n") +
172             "  -gen             \t\t  " + _("Generate coins\n") +
173             "  -gen=0           \t\t  " + _("Don't generate coins\n") +
174             "  -min             \t\t  " + _("Start minimized\n") +
175             "  -datadir=<dir>   \t\t  " + _("Specify data directory\n") +
176             "  -timeout=<n>     \t  "   + _("Specify connection timeout (in milliseconds)\n") +
177             "  -proxy=<ip:port> \t  "   + _("Connect through socks4 proxy\n") +
178             "  -dns             \t  "   + _("Allow DNS lookups for addnode and connect\n") +
179             "  -addnode=<ip>    \t  "   + _("Add a node to connect to\n") +
180             "  -connect=<ip>    \t\t  " + _("Connect only to the specified node\n") +
181             "  -nolisten        \t  "   + _("Don't accept connections from outside\n") +
182 #ifdef USE_UPNP
183 #if USE_UPNP
184             "  -noupnp          \t  "   + _("Don't attempt to use UPnP to map the listening port\n") +
185 #else
186             "  -upnp            \t  "   + _("Attempt to use UPnP to map the listening port\n") +
187 #endif
188 #endif
189             "  -paytxfee=<amt>  \t  "   + _("Fee per KB to add to transactions you send\n") +
190 #ifdef GUI
191             "  -server          \t\t  " + _("Accept command line and JSON-RPC commands\n") +
192 #endif
193 #ifndef __WXMSW__
194             "  -daemon          \t\t  " + _("Run in the background as a daemon and accept commands\n") +
195 #endif
196             "  -testnet         \t\t  " + _("Use the test network\n") +
197             "  -rpcuser=<user>  \t  "   + _("Username for JSON-RPC connections\n") +
198             "  -rpcpassword=<pw>\t  "   + _("Password for JSON-RPC connections\n") +
199             "  -rpcport=<port>  \t\t  " + _("Listen for JSON-RPC connections on <port> (default: 8332)\n") +
200             "  -rpcallowip=<ip> \t\t  " + _("Allow JSON-RPC connections from specified IP address\n") +
201             "  -rpcconnect=<ip> \t  "   + _("Send commands to node running on <ip> (default: 127.0.0.1)\n") +
202             "  -keypool=<n>     \t  "   + _("Set key pool size to <n> (default: 100)\n") +
203             "  -rescan          \t  "   + _("Rescan the block chain for missing wallet transactions\n");
204
205 #ifdef USE_SSL
206         strUsage += string() +
207             _("\nSSL options: (see the Bitcoin Wiki for SSL setup instructions)\n") +
208             "  -rpcssl                                \t  " + _("Use OpenSSL (https) for JSON-RPC connections\n") +
209             "  -rpcsslcertificatechainfile=<file.cert>\t  " + _("Server certificate file (default: server.cert)\n") +
210             "  -rpcsslprivatekeyfile=<file.pem>       \t  " + _("Server private key (default: server.pem)\n") +
211             "  -rpcsslciphers=<ciphers>               \t  " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)\n");
212 #endif
213
214         strUsage += string() +
215             "  -?               \t\t  " + _("This help message\n");
216
217 #if defined(__WXMSW__) && defined(GUI)
218         // Tabs make the columns line up in the message box
219         wxMessageBox(strUsage, "Bitcoin", wxOK);
220 #else
221         // Remove tabs
222         strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
223         fprintf(stderr, "%s", strUsage.c_str());
224 #endif
225         return false;
226     }
227
228     fDebug = GetBoolArg("-debug");
229     fAllowDNS = GetBoolArg("-dns");
230
231 #ifndef __WXMSW__
232     fDaemon = GetBoolArg("-daemon");
233 #else
234     fDaemon = false;
235 #endif
236
237     if (fDaemon)
238         fServer = true;
239     else
240         fServer = GetBoolArg("-server");
241
242     /* force fServer when running without GUI */
243 #if !defined(QT_GUI) && !defined(GUI)
244     fServer = true;
245 #endif
246     fPrintToConsole = GetBoolArg("-printtoconsole");
247     fPrintToDebugger = GetBoolArg("-printtodebugger");
248
249     fTestNet = GetBoolArg("-testnet");
250     bool fTOR = (fUseProxy && addrProxy.port == htons(9050));
251     fNoListen = GetBoolArg("-nolisten") || fTOR;
252     fLogTimestamps = GetBoolArg("-logtimestamps");
253
254 #ifndef QT_GUI
255     for (int i = 1; i < argc; i++)
256         if (!IsSwitchChar(argv[i][0]))
257             fCommandLine = true;
258
259     if (fCommandLine)
260     {
261         int ret = CommandLineRPC(argc, argv);
262         exit(ret);
263     }
264 #endif
265
266 #ifndef __WXMSW__
267     if (fDaemon)
268     {
269         // Daemonize
270         pid_t pid = fork();
271         if (pid < 0)
272         {
273             fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
274             return false;
275         }
276         if (pid > 0)
277         {
278             CreatePidFile(GetPidFile(), pid);
279             return true;
280         }
281
282         pid_t sid = setsid();
283         if (sid < 0)
284             fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
285     }
286 #endif
287
288     if (!fDebug && !pszSetDataDir[0])
289         ShrinkDebugFile();
290     printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
291     printf("Bitcoin version %s\n", FormatFullVersion().c_str());
292 #ifdef GUI
293     printf("OS version %s\n", ((string)wxGetOsDescription()).c_str());
294     printf("System default language is %d %s\n", g_locale.GetSystemLanguage(), ((string)g_locale.GetSysName()).c_str());
295     printf("Language file %s (%s)\n", (string("locale/") + (string)g_locale.GetCanonicalName() + "/LC_MESSAGES/bitcoin.mo").c_str(), ((string)g_locale.GetLocale()).c_str());
296 #endif
297     printf("Default data directory %s\n", GetDefaultDataDir().c_str());
298
299     if (GetBoolArg("-loadblockindextest"))
300     {
301         CTxDB txdb("r");
302         txdb.LoadBlockIndex();
303         PrintBlockTree();
304         return false;
305     }
306
307     //
308     // Limit to single instance per user
309     // Required to protect the database files if we're going to keep deleting log.*
310     //
311 #if defined(__WXMSW__) && defined(GUI)
312     // wxSingleInstanceChecker doesn't work on Linux
313     wxString strMutexName = wxString("bitcoin_running.") + getenv("HOMEPATH");
314     for (int i = 0; i < strMutexName.size(); i++)
315         if (!isalnum(strMutexName[i]))
316             strMutexName[i] = '.';
317     wxSingleInstanceChecker* psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
318     if (psingleinstancechecker->IsAnotherRunning())
319     {
320         printf("Existing instance found\n");
321         unsigned int nStart = GetTime();
322         loop
323         {
324             // Show the previous instance and exit
325             HWND hwndPrev = FindWindowA("wxWindowClassNR", "Bitcoin");
326             if (hwndPrev)
327             {
328                 if (IsIconic(hwndPrev))
329                     ShowWindow(hwndPrev, SW_RESTORE);
330                 SetForegroundWindow(hwndPrev);
331                 return false;
332             }
333
334             if (GetTime() > nStart + 60)
335                 return false;
336
337             // Resume this instance if the other exits
338             delete psingleinstancechecker;
339             Sleep(1000);
340             psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
341             if (!psingleinstancechecker->IsAnotherRunning())
342                 break;
343         }
344     }
345 #endif
346
347     // Make sure only a single bitcoin process is using the data directory.
348     string strLockFile = GetDataDir() + "/.lock";
349     FILE* file = fopen(strLockFile.c_str(), "a"); // empty lock file; created if it doesn't exist.
350     if (file) fclose(file);
351     static boost::interprocess::file_lock lock(strLockFile.c_str());
352     if (!lock.try_lock())
353     {
354         wxMessageBox(strprintf(_("Cannot obtain a lock on data directory %s.  Bitcoin is probably already running."), GetDataDir().c_str()), "Bitcoin");
355         return false;
356     }
357
358     // Bind to the port early so we can tell if another instance is already running.
359     string strErrors;
360     if (!fNoListen)
361     {
362         if (!BindListenPort(strErrors))
363         {
364             wxMessageBox(strErrors, "Bitcoin");
365             return false;
366         }
367     }
368
369     //
370     // Load data files
371     //
372     if (fDaemon)
373         fprintf(stdout, "bitcoin server starting\n");
374     strErrors = "";
375     int64 nStart;
376
377     InitMessage(_("Loading addresses..."));
378     printf("Loading addresses...\n");
379     nStart = GetTimeMillis();
380     if (!LoadAddresses())
381         strErrors += _("Error loading addr.dat      \n");
382     printf(" addresses   %15"PRI64d"ms\n", GetTimeMillis() - nStart);
383
384     InitMessage(_("Loading block index..."));
385     printf("Loading block index...\n");
386     nStart = GetTimeMillis();
387     if (!LoadBlockIndex())
388         strErrors += _("Error loading blkindex.dat      \n");
389     printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
390
391     InitMessage(_("Loading wallet..."));
392     printf("Loading wallet...\n");
393     nStart = GetTimeMillis();
394     bool fFirstRun;
395     pwalletMain = new CWallet("wallet.dat");
396     int nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
397     if (nLoadWalletRet != DB_LOAD_OK)
398     {
399         if (nLoadWalletRet == DB_CORRUPT)
400             strErrors += _("Error loading wallet.dat: Wallet corrupted      \n");
401         else if (nLoadWalletRet == DB_TOO_NEW)
402             strErrors += _("Error loading wallet.dat: Wallet requires newer version of Bitcoin      \n");
403         else
404             strErrors += _("Error loading wallet.dat      \n");
405     }
406     printf(" wallet      %15"PRI64d"ms\n", GetTimeMillis() - nStart);
407
408     RegisterWallet(pwalletMain);
409
410     CBlockIndex *pindexRescan = pindexBest;
411     if (GetBoolArg("-rescan"))
412         pindexRescan = pindexGenesisBlock;
413     else
414     {
415         CWalletDB walletdb("wallet.dat");
416         CBlockLocator locator;
417         if (walletdb.ReadBestBlock(locator))
418             pindexRescan = locator.GetBlockIndex();
419     }
420     if (pindexBest != pindexRescan)
421     {
422         InitMessage(_("Rescanning..."));
423         printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
424         nStart = GetTimeMillis();
425         pwalletMain->ScanForWalletTransactions(pindexRescan, true);
426         printf(" rescan      %15"PRI64d"ms\n", GetTimeMillis() - nStart);
427     }
428
429     InitMessage(_("Done loading"));
430     printf("Done loading\n");
431
432         //// debug print
433         printf("mapBlockIndex.size() = %d\n",   mapBlockIndex.size());
434         printf("nBestHeight = %d\n",            nBestHeight);
435         printf("setKeyPool.size() = %d\n",      pwalletMain->setKeyPool.size());
436         printf("mapWallet.size() = %d\n",       pwalletMain->mapWallet.size());
437         printf("mapAddressBook.size() = %d\n",  pwalletMain->mapAddressBook.size());
438
439     if (!strErrors.empty())
440     {
441         wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);
442         return false;
443     }
444
445     // Add wallet transactions that aren't already in a block to mapTransactions
446     pwalletMain->ReacceptWalletTransactions();
447
448     //
449     // Parameters
450     //
451     if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
452     {
453         PrintBlockTree();
454         return false;
455     }
456
457     if (mapArgs.count("-timeout"))
458     {
459         int nNewTimeout = GetArg("-timeout", 5000);
460         if (nNewTimeout > 0 && nNewTimeout < 600000)
461             nConnectTimeout = nNewTimeout;
462     }
463
464     if (mapArgs.count("-printblock"))
465     {
466         string strMatch = mapArgs["-printblock"];
467         int nFound = 0;
468         for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
469         {
470             uint256 hash = (*mi).first;
471             if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
472             {
473                 CBlockIndex* pindex = (*mi).second;
474                 CBlock block;
475                 block.ReadFromDisk(pindex);
476                 block.BuildMerkleTree();
477                 block.print();
478                 printf("\n");
479                 nFound++;
480             }
481         }
482         if (nFound == 0)
483             printf("No blocks matching %s were found\n", strMatch.c_str());
484         return false;
485     }
486
487     fGenerateBitcoins = GetBoolArg("-gen");
488
489     if (mapArgs.count("-proxy"))
490     {
491         fUseProxy = true;
492         addrProxy = CAddress(mapArgs["-proxy"]);
493         if (!addrProxy.IsValid())
494         {
495             wxMessageBox(_("Invalid -proxy address"), "Bitcoin");
496             return false;
497         }
498     }
499
500     if (mapArgs.count("-addnode"))
501     {
502         BOOST_FOREACH(string strAddr, mapMultiArgs["-addnode"])
503         {
504             CAddress addr(strAddr, fAllowDNS);
505             addr.nTime = 0; // so it won't relay unless successfully connected
506             if (addr.IsValid())
507                 AddAddress(addr);
508         }
509     }
510
511     if (GetBoolArg("-nodnsseed"))
512         printf("DNS seeding disabled\n");
513     else
514         DNSAddressSeed();
515
516     if (mapArgs.count("-paytxfee"))
517     {
518         if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
519         {
520             wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");
521             return false;
522         }
523         if (nTransactionFee > 0.25 * COIN)
524             wxMessageBox(_("Warning: -paytxfee is set very high.  This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);
525     }
526
527     if (fHaveUPnP)
528     {
529 #if USE_UPNP
530     if (GetBoolArg("-noupnp"))
531         fUseUPnP = false;
532 #else
533     if (GetBoolArg("-upnp"))
534         fUseUPnP = true;
535 #endif
536     }
537
538     //
539     // Create the main window and start the node
540     //
541 #ifdef GUI
542     if (!fDaemon)
543         CreateMainWindow();
544 #endif
545
546     if (!CheckDiskSpace())
547         return false;
548
549     RandAddSeedPerfmon();
550
551     if (!CreateThread(StartNode, NULL))
552         wxMessageBox(_("Error: CreateThread(StartNode) failed"), "Bitcoin");
553
554     if (fServer)
555         CreateThread(ThreadRPCServer, NULL);
556
557 #if defined(__WXMSW__) && defined(GUI)
558     if (fFirstRun)
559         SetStartOnSystemStartup(true);
560 #endif
561
562 #if !defined(QT_GUI) && !defined(GUI)
563     while (1)
564         Sleep(5000);
565 #endif
566
567     return true;
568 }