Merge pull request #593 (Full URL Support in bitcoin-qt)
authorWladimir J. van der Laan <laanwj@gmail.com>
Thu, 26 Jan 2012 18:00:02 +0000 (19:00 +0100)
committerWladimir J. van der Laan <laanwj@gmail.com>
Thu, 26 Jan 2012 18:00:02 +0000 (19:00 +0100)
57 files changed:
bitcoin-qt.pro
contrib/debian/changelog
contrib/debian/control
contrib/debian/manpages/bitcoind.1
doc/release-process.txt
src/base58.h
src/bitcoinrpc.cpp
src/checkpoints.cpp
src/compat.h [new file with mode: 0644]
src/db.cpp
src/headers.h
src/init.cpp
src/irc.cpp
src/key.h
src/keystore.cpp
src/keystore.h
src/main.cpp
src/main.h
src/makefile.linux-mingw
src/makefile.mingw
src/makefile.osx
src/makefile.unix
src/makefile.vc [deleted file]
src/net.cpp
src/net.h
src/netbase.cpp [new file with mode: 0644]
src/netbase.h [new file with mode: 0644]
src/obj-test/.gitignore [new file with mode: 0644]
src/protocol.cpp
src/protocol.h
src/qt/bitcoingui.cpp
src/qt/forms/aboutdialog.ui
src/qt/forms/sendcoinsdialog.ui
src/qt/forms/transactiondescdialog.ui
src/qt/optionsmodel.cpp
src/qt/transactiondesc.cpp
src/qt/transactionfilterproxy.h
src/rpcdump.cpp
src/script.cpp
src/script.h
src/serialize.h
src/test/DoS_tests.cpp
src/test/key_tests.cpp [new file with mode: 0644]
src/test/multisig_tests.cpp
src/test/rpc_tests.cpp [new file with mode: 0644]
src/test/script_P2SH_tests.cpp [new file with mode: 0644]
src/test/script_op_eval_tests.cpp [deleted file]
src/test/script_tests.cpp
src/test/sigopcount_tests.cpp [new file with mode: 0644]
src/test/test_bitcoin.cpp
src/test/transaction_tests.cpp
src/test/util_tests.cpp
src/uint256.h
src/util.cpp
src/util.h
src/wallet.cpp
src/wallet.h

index ab5414c..cd68720 100644 (file)
@@ -97,6 +97,7 @@ HEADERS += src/qt/bitcoingui.h \
     src/base58.h \
     src/bignum.h \
     src/checkpoints.h \
+    src/compat.h \
     src/util.h \
     src/uint256.h \
     src/serialize.h \
@@ -157,6 +158,7 @@ SOURCES += src/qt/bitcoin.cpp src/qt/bitcoingui.cpp \
     src/qt/editaddressdialog.cpp \
     src/qt/bitcoinaddressvalidator.cpp \
     src/util.cpp \
+    src/netbase.cpp \
     src/key.cpp \
     src/script.cpp \
     src/main.cpp \
index 44aa683..db5e268 100644 (file)
@@ -1,5 +1,9 @@
 bitcoin (0.5.1-natty1) natty; urgency=low
 
+  * Remove mentions on anonymity in package descriptions and manpage.
+    These should never have been there, bitcoin isnt anonymous without
+    a ton of work that virtually no users will ever be willing and
+    capable of doing
   * Add GNOME/KDE support for bitcoin-qt's bitcoin: URI support.
     Thanks to luke-jr for the KDE .protocol file.
 
index 13fde59..c41664c 100644 (file)
@@ -24,7 +24,7 @@ Vcs-Browser: http://github.com/bitcoin/bitcoin
 Package: bitcoind
 Architecture: any
 Depends: ${shlibs:Depends}, ${misc:Depends}
-Description: peer-to-peer network based anonymous digital currency - daemon
+Description: peer-to-peer network based digital currency - daemon
  Bitcoin is a free open source peer-to-peer electronic cash system that
  is completely decentralized, without the need for a central server or
  trusted parties.  Users hold the crypto keys to their own money and
@@ -42,7 +42,7 @@ Description: peer-to-peer network based anonymous digital currency - daemon
 Package: bitcoin-qt
 Architecture: any
 Depends: ${shlibs:Depends}, ${misc:Depends}
-Description: peer-to-peer network based anonymous digital currency - QT GUI
+Description: peer-to-peer network based digital currency - QT GUI
  Bitcoin is a free open source peer-to-peer electronic cash system that
  is completely decentralized, without the need for a central server or
  trusted parties.  Users hold the crypto keys to their own money and
index 0179406..bf46a66 100644 (file)
@@ -1,6 +1,6 @@
 .TH BITCOIND "1" "January 2011" "bitcoind 3.19" 
 .SH NAME
-bitcoind \- peer-to-peer network based anonymous digital currency
+bitcoind \- peer-to-peer network based digital currency
 .SH SYNOPSIS
 bitcoin [options] <command> [params]  
 .TP
index ee1a5d4..3f1a6a5 100644 (file)
@@ -1,3 +1,5 @@
+* update translations (ping tcatm on IRC for now)
+
 * update (commit) version in sources
   bitcoin-qt.pro
   src/main.h      (CLIENT_VERSION : PROTOCOL_VERSION in serialize.h is updated only on protocol changes)
@@ -77,9 +79,9 @@
  Build output expected:
   Bitcoin-Qt.dmg
 
-* upload source and builds to SourceForge
+* upload builds to SourceForge
 
-* create SHA1SUMS for builds, and PGP-sign it
+* create SHA256SUMS for builds, and PGP-sign it
 
 * update bitcoin.org version
 
index ef6493d..d3a153b 100644 (file)
@@ -255,7 +255,7 @@ public:
 // base58-encoded bitcoin addresses
 // Public-key-hash-addresses have version 0 (or 192 testnet)
 // The data vector contains RIPEMD160(SHA256(pubkey)), where pubkey is the serialized public key
-// Script-hash-addresses (OP_EVAL) have version 5 (or 196 testnet)
+// Script-hash-addresses have version 5 (or 196 testnet)
 // The data vector contains RIPEMD160(SHA256(cscript)), where cscript is the serialized redemption script
 class CBitcoinAddress : public CBase58Data
 {
@@ -296,7 +296,7 @@ public:
                 fExpectTestNet = false;
                 break;
             case SCRIPT_ADDRESS:
-                nExpectedSize = 20; // OP_EVAL, hash of CScript
+                nExpectedSize = 20; // Hash of CScript
                 fExpectTestNet = false;
                 break;
 
@@ -359,22 +359,25 @@ public:
 class CBitcoinSecret : public CBase58Data
 {
 public:
-    void SetSecret(const CSecret& vchSecret)
-    {
+    void SetSecret(const CSecret& vchSecret, bool fCompressed)
+    { 
+        assert(vchSecret.size() == 32);
         SetData(fTestNet ? 239 : 128, &vchSecret[0], vchSecret.size());
+        if (fCompressed)
+            vchData.push_back(1);
     }
 
-    CSecret GetSecret()
+    CSecret GetSecret(bool &fCompressedOut)
     {
         CSecret vchSecret;
-        vchSecret.resize(vchData.size());
-        memcpy(&vchSecret[0], &vchData[0], vchData.size());
+        vchSecret.resize(32);
+        memcpy(&vchSecret[0], &vchData[0], 32);
+        fCompressedOut = vchData.size() == 33;
         return vchSecret;
     }
 
     bool IsValid() const
     {
-        int nExpectedSize = 32;
         bool fExpectTestNet = false;
         switch(nVersion)
         {
@@ -388,12 +391,12 @@ public:
             default:
                 return false;
         }
-        return fExpectTestNet == fTestNet && vchData.size() == nExpectedSize;
+        return fExpectTestNet == fTestNet && (vchData.size() == 32 || (vchData.size() == 33 && vchData[32] == 1));
     }
 
-    CBitcoinSecret(const CSecret& vchSecret)
+    CBitcoinSecret(const CSecret& vchSecret, bool fCompressed)
     {
-        SetSecret(vchSecret);
+        SetSecret(vchSecret, fCompressed);
     }
 
     CBitcoinSecret()
index 09be73a..3063abd 100644 (file)
@@ -347,10 +347,7 @@ Value getinfo(const Array& params, bool fHelp)
     obj.push_back(Pair("blocks",        (int)nBestHeight));
     obj.push_back(Pair("connections",   (int)vNodes.size()));
     obj.push_back(Pair("proxy",         (fUseProxy ? addrProxy.ToStringIPPort() : string())));
-    obj.push_back(Pair("generate",      (bool)fGenerateBitcoins));
-    obj.push_back(Pair("genproclimit",  (int)(fLimitProcessors ? nLimitProcessors : -1)));
     obj.push_back(Pair("difficulty",    (double)GetDifficulty()));
-    obj.push_back(Pair("hashespersec",  gethashespersec(params, false)));
     obj.push_back(Pair("testnet",       fTestNet));
     obj.push_back(Pair("keypoololdest", (boost::int64_t)pwalletMain->GetOldestKeyPoolTime()));
     obj.push_back(Pair("keypoolsize",   pwalletMain->GetKeyPoolSize()));
@@ -362,6 +359,28 @@ Value getinfo(const Array& params, bool fHelp)
 }
 
 
+Value getmininginfo(const Array& params, bool fHelp)
+{
+    if (fHelp || params.size() != 0)
+        throw runtime_error(
+            "getmininginfo\n"
+            "Returns an object containing mining-related information.");
+
+    Object obj;
+    obj.push_back(Pair("blocks",        (int)nBestHeight));
+    obj.push_back(Pair("currentblocksize",(uint64_t)nLastBlockSize));
+    obj.push_back(Pair("currentblocktx",(uint64_t)nLastBlockTx));
+    obj.push_back(Pair("difficulty",    (double)GetDifficulty()));
+    obj.push_back(Pair("errors",        GetWarnings("statusbar")));
+    obj.push_back(Pair("generate",      (bool)fGenerateBitcoins));
+    obj.push_back(Pair("genproclimit",  (int)(fLimitProcessors ? nLimitProcessors : -1)));
+    obj.push_back(Pair("hashespersec",  gethashespersec(params, false)));
+    obj.push_back(Pair("pooledtx",      (uint64_t)nPooledTx));
+    obj.push_back(Pair("testnet",       fTestNet));
+    return obj;
+}
+
+
 Value getnewaddress(const Array& params, bool fHelp)
 {
     if (fHelp || params.size() > 1)
@@ -975,7 +994,7 @@ Value addmultisigaddress(const Array& params, bool fHelp)
     {
         string msg = "addmultisigaddress <nrequired> <'[\"key\",\"key\"]'> [account]\n"
             "Add a nrequired-to-sign multisignature address to the wallet\"\n"
-            "each key is a bitcoin address, hex or base58 public key\n"
+            "each key is a bitcoin address or hex-encoded public key\n"
             "If [account] is specified, assign address to [account].";
         throw runtime_error(msg);
     }
@@ -989,41 +1008,52 @@ Value addmultisigaddress(const Array& params, bool fHelp)
         strAccount = AccountFromValue(params[2]);
 
     // Gather public keys
-    if (keys.size() < nRequired)
+    if (nRequired < 1 || keys.size() < nRequired)
         throw runtime_error(
-            strprintf("addmultisigaddress: wrong number of keys (got %d, need at least %d)", keys.size(), nRequired));
+            strprintf("wrong number of keys"
+                      "(got %d, need at least %d)", keys.size(), nRequired));
     std::vector<CKey> pubkeys;
     pubkeys.resize(keys.size());
     for (int i = 0; i < keys.size(); i++)
     {
         const std::string& ks = keys[i].get_str();
-        if (ks.size() == 130) // hex public key
-            pubkeys[i].SetPubKey(ParseHex(ks));
-        else if (ks.size() > 34) // base58-encoded
+
+        // Case 1: bitcoin address and we have full public key:
+        CBitcoinAddress address(ks);
+        if (address.IsValid())
         {
+            if (address.IsScript())
+                throw runtime_error(
+                    strprintf("%s is a pay-to-script address",ks.c_str()));
             std::vector<unsigned char> vchPubKey;
-            if (DecodeBase58(ks, vchPubKey))
-                pubkeys[i].SetPubKey(vchPubKey);
-            else
-                throw runtime_error("Error base58 decoding key: "+ks);
+            if (!pwalletMain->GetPubKey(address, vchPubKey))
+                throw runtime_error(
+                    strprintf("no full public key for address %s",ks.c_str()));
+            if (vchPubKey.empty() || !pubkeys[i].SetPubKey(vchPubKey))
+                throw runtime_error(" Invalid public key: "+ks);
         }
-        else // bitcoin address for key in this wallet
+
+        // Case 2: hex public key
+        else if (IsHex(ks))
         {
-            CBitcoinAddress address(ks);
-            if (!pwalletMain->GetKey(address, pubkeys[i]))
-                throw runtime_error(
-                    strprintf("addmultisigaddress: unknown address: %s",ks.c_str()));
+            vector<unsigned char> vchPubKey = ParseHex(ks);
+            if (vchPubKey.empty() || !pubkeys[i].SetPubKey(vchPubKey))
+                throw runtime_error(" Invalid public key: "+ks);
+        }
+        else
+        {
+            throw runtime_error(" Invalid public key: "+ks);
         }
     }
 
-    // Construct using OP_EVAL
+    // Construct using pay-to-script-hash:
     CScript inner;
     inner.SetMultisig(nRequired, pubkeys);
 
     uint160 scriptHash = Hash160(inner);
     CScript scriptPubKey;
-    scriptPubKey.SetEval(inner);
-    pwalletMain->AddCScript(scriptHash, inner);
+    scriptPubKey.SetPayToScriptHash(inner);
+    pwalletMain->AddCScript(inner);
     CBitcoinAddress address;
     address.SetScriptHash160(scriptHash);
 
@@ -1418,7 +1448,7 @@ Value listsinceblock(const Array& params, bool fHelp)
         CBlockIndex *block;
         for (block = pindexBest;
              block && block->nHeight > target_height;
-             block = block->pprev);
+             block = block->pprev)  { }
 
         lastblock = block ? block->GetBlockHash() : 0;
     }
@@ -1699,8 +1729,9 @@ Value validateaddress(const Array& params, bool fHelp)
             std::vector<unsigned char> vchPubKey;
             pwalletMain->GetPubKey(address, vchPubKey);
             ret.push_back(Pair("pubkey", HexStr(vchPubKey)));
-            std::string strPubKey(vchPubKey.begin(), vchPubKey.end());
-            ret.push_back(Pair("pubkey58", EncodeBase58(vchPubKey)));
+            CKey key;
+            key.SetPubKey(vchPubKey);
+            ret.push_back(Pair("iscompressed", key.IsCompressed()));
         }
         else if (pwalletMain->HaveCScript(address.GetHash160()))
         {
@@ -1843,7 +1874,10 @@ Value getmemorypool(const Array& params, bool fHelp)
             "  \"previousblockhash\" : hash of current highest block\n"
             "  \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
             "  \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
+            "  \"coinbaseflags\" : data that should be included in coinbase so support for new features can be judged\n"
             "  \"time\" : timestamp appropriate for next block\n"
+            "  \"mintime\" : minimum timestamp appropriate for next block\n"
+            "  \"curtime\" : current timestamp\n"
             "  \"bits\" : compressed target of next block\n"
             "If [data] is specified, tries to solve the block and returns true if it was successful.");
 
@@ -1897,7 +1931,10 @@ Value getmemorypool(const Array& params, bool fHelp)
         result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
         result.push_back(Pair("transactions", transactions));
         result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
+        result.push_back(Pair("coinbaseflags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
         result.push_back(Pair("time", (int64_t)pblock->nTime));
+        result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
+        result.push_back(Pair("curtime", (int64_t)GetAdjustedTime()));
 
         union {
             int32_t nBits;
@@ -1983,6 +2020,7 @@ pair<string, rpcfn_type> pCallTable[] =
     make_pair("setgenerate",            &setgenerate),
     make_pair("gethashespersec",        &gethashespersec),
     make_pair("getinfo",                &getinfo),
+    make_pair("getmininginfo",          &getmininginfo),
     make_pair("getnewaddress",          &getnewaddress),
     make_pair("getaccountaddress",      &getaccountaddress),
     make_pair("setaccount",             &setaccount),
@@ -2033,6 +2071,7 @@ string pAllowInSafeMode[] =
     "setgenerate",
     "gethashespersec",
     "getinfo",
+    "getmininginfo",
     "getnewaddress",
     "getaccountaddress",
     "getaccount",
@@ -2657,7 +2696,7 @@ int CommandLineRPC(int argc, char *argv[])
             string s = params[1].get_str();
             Value v;
             if (!read_string(s, v) || v.type() != array_type)
-                throw runtime_error("addmultisigaddress: type mismatch "+s);
+                throw runtime_error("type mismatch "+s);
             params[1] = v.get_array();
         }
 
index c7e054d..508f72b 100644 (file)
@@ -52,7 +52,6 @@ namespace Checkpoints
     {
         if (fTestNet) return NULL;
 
-        int64 nResult;
         BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints)
         {
             const uint256& hash = i.second;
diff --git a/src/compat.h b/src/compat.h
new file mode 100644 (file)
index 0000000..5c1fcc3
--- /dev/null
@@ -0,0 +1,42 @@
+// Copyright (c) 2009-2010 Satoshi Nakamoto
+// Copyright (c) 2011 The Bitcoin developers
+// Distributed under the MIT/X11 software license, see the accompanying
+// file license.txt or http://www.opensource.org/licenses/mit-license.php.
+#ifndef _BITCOIN_COMPAT_H
+#define _BITCOIN_COMPAT_H 1
+
+typedef u_int SOCKET;
+#ifdef WIN32
+#define MSG_NOSIGNAL        0
+#define MSG_DONTWAIT        0
+typedef int socklen_t;
+#else
+#include "errno.h"
+#define WSAGetLastError()   errno
+#define WSAEINVAL           EINVAL
+#define WSAEALREADY         EALREADY
+#define WSAEWOULDBLOCK      EWOULDBLOCK
+#define WSAEMSGSIZE         EMSGSIZE
+#define WSAEINTR            EINTR
+#define WSAEINPROGRESS      EINPROGRESS
+#define WSAEADDRINUSE       EADDRINUSE
+#define WSAENOTSOCK         EBADF
+#define INVALID_SOCKET      (SOCKET)(~0)
+#define SOCKET_ERROR        -1
+#endif
+
+inline int myclosesocket(SOCKET& hSocket)
+{
+    if (hSocket == INVALID_SOCKET)
+        return WSAENOTSOCK;
+#ifdef WIN32
+    int ret = closesocket(hSocket);
+#else
+    int ret = close(hSocket);
+#endif
+    hSocket = INVALID_SOCKET;
+    return ret;
+}
+#define closesocket(s)      myclosesocket(s)
+
+#endif
index f43b2a5..9ad05ba 100644 (file)
@@ -860,12 +860,16 @@ int CWalletDB::LoadWallet(CWallet* pwallet)
                 {
                     CPrivKey pkey;
                     ssValue >> pkey;
+                    key.SetPubKey(vchPubKey);
                     key.SetPrivKey(pkey);
+                    if (key.GetPubKey() != vchPubKey)
+                        return DB_CORRUPT;
                 }
                 else
                 {
                     CWalletKey wkey;
                     ssValue >> wkey;
+                    key.SetPubKey(vchPubKey);
                     key.SetPrivKey(wkey.vchPrivKey);
                 }
                 if (!pwallet->LoadKey(key))
@@ -940,7 +944,7 @@ int CWalletDB::LoadWallet(CWallet* pwallet)
                 ssKey >> hash;
                 CScript script;
                 ssValue >> script;
-                if (!pwallet->LoadCScript(hash, script))
+                if (!pwallet->LoadCScript(script))
                     return DB_CORRUPT;
             }
         }
index b6903fe..127cf41 100644 (file)
@@ -12,7 +12,7 @@
 #ifdef _WIN32_WINNT
 #undef _WIN32_WINNT
 #endif
-#define _WIN32_WINNT 0x0500
+#define _WIN32_WINNT 0x0501
 #ifdef _WIN32_IE
 #undef _WIN32_IE
 #endif
@@ -79,8 +79,6 @@
 #endif
 
 
-#pragma hdrstop
-
 #include "serialize.h"
 #include "uint256.h"
 #include "util.h"
index 05ba795..d237e24 100644 (file)
@@ -192,7 +192,7 @@ bool AppInit2(int argc, char* argv[])
             "  -dns             \t  "   + _("Allow DNS lookups for addnode and connect") + "\n" +
             "  -port=<port>     \t\t  " + _("Listen for connections on <port> (default: 8333 or testnet: 18333)") + "\n" +
             "  -maxconnections=<n>\t  " + _("Maintain at most <n> connections to peers (default: 125)") + "\n" +
-            "  -addnode=<ip>    \t  "   + _("Add a node to connect to") + "\n" +
+            "  -addnode=<ip>    \t  "   + _("Add a node to connect to and attempt to keep the connection open") + "\n" +
             "  -connect=<ip>    \t\t  " + _("Connect only to the specified node") + "\n" +
             "  -noirc           \t  "   + _("Don't find peers using internet relay chat") + "\n" +
             "  -nolisten        \t  "   + _("Don't accept connections from outside") + "\n" +
@@ -227,6 +227,7 @@ bool AppInit2(int argc, char* argv[])
             "  -rpcport=<port>  \t\t  " + _("Listen for JSON-RPC connections on <port> (default: 8332)") + "\n" +
             "  -rpcallowip=<ip> \t\t  " + _("Allow JSON-RPC connections from specified IP address") + "\n" +
             "  -rpcconnect=<ip> \t  "   + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n" +
+            "  -blocknotify=<cmd> "     + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n" +
             "  -keypool=<n>     \t  "   + _("Set key pool size to <n> (default: 100)") + "\n" +
             "  -rescan          \t  "   + _("Rescan the block chain for missing wallet transactions") + "\n";
 
@@ -462,7 +463,7 @@ bool AppInit2(int argc, char* argv[])
     if (mapArgs.count("-proxy"))
     {
         fUseProxy = true;
-        addrProxy = CAddress(mapArgs["-proxy"]);
+        addrProxy = CService(mapArgs["-proxy"], 9050);
         if (!addrProxy.IsValid())
         {
             wxMessageBox(_("Invalid -proxy address"), "Bitcoin");
@@ -470,7 +471,7 @@ bool AppInit2(int argc, char* argv[])
         }
     }
 
-    bool fTor = (fUseProxy && addrProxy.port == htons(9050));
+    bool fTor = (fUseProxy && addrProxy.GetPort() == 9050);
     if (fTor)
     {
         // Use SoftSetArg here so user can override any of these if they wish.
@@ -511,7 +512,7 @@ bool AppInit2(int argc, char* argv[])
     {
         BOOST_FOREACH(string strAddr, mapMultiArgs["-addnode"])
         {
-            CAddress addr(strAddr, fAllowDNS);
+            CAddress addr(CService(strAddr, GetDefaultPort(), fAllowDNS));
             addr.nTime = 0; // so it won't relay unless successfully connected
             if (addr.IsValid())
                 AddAddress(addr);
index fe96a90..8805c7f 100644 (file)
@@ -22,22 +22,25 @@ void ThreadIRCSeed2(void* parg);
 #pragma pack(push, 1)
 struct ircaddr
 {
-    int ip;
+    struct in_addr ip;
     short port;
 };
 #pragma pack(pop)
 
-string EncodeAddress(const CAddress& addr)
+string EncodeAddress(const CService& addr)
 {
     struct ircaddr tmp;
-    tmp.ip    = addr.ip;
-    tmp.port  = addr.port;
+    if (addr.GetInAddr(&tmp.ip))
+    {
+        tmp.port = htons(addr.GetPort());
 
-    vector<unsigned char> vch(UBEGIN(tmp), UEND(tmp));
-    return string("u") + EncodeBase58Check(vch);
+        vector<unsigned char> vch(UBEGIN(tmp), UEND(tmp));
+        return string("u") + EncodeBase58Check(vch);
+    }
+    return "";
 }
 
-bool DecodeAddress(string str, CAddress& addr)
+bool DecodeAddress(string str, CService& addr)
 {
     vector<unsigned char> vch;
     if (!DecodeBase58Check(str.substr(1), vch))
@@ -48,7 +51,7 @@ bool DecodeAddress(string str, CAddress& addr)
         return false;
     memcpy(&tmp, &vch[0], sizeof(tmp));
 
-    addr = CAddress(tmp.ip, ntohs(tmp.port), NODE_NETWORK);
+    addr = CService(tmp.ip, ntohs(tmp.port));
     return true;
 }
 
@@ -204,7 +207,7 @@ bool RecvCodeLine(SOCKET hSocket, const char* psz1, string& strRet)
     }
 }
 
-bool GetIPFromIRC(SOCKET hSocket, string strMyName, unsigned int& ipRet)
+bool GetIPFromIRC(SOCKET hSocket, string strMyName, CNetAddr& ipRet)
 {
     Send(hSocket, strprintf("USERHOST %s\r", strMyName.c_str()).c_str());
 
@@ -227,10 +230,10 @@ bool GetIPFromIRC(SOCKET hSocket, string strMyName, unsigned int& ipRet)
     printf("GetIPFromIRC() got userhost %s\n", strHost.c_str());
     if (fUseProxy)
         return false;
-    CAddress addr(strHost, 0, true);
+    CNetAddr addr(strHost, true);
     if (!addr.IsValid())
         return false;
-    ipRet = addr.ip;
+    ipRet = addr;
 
     return true;
 }
@@ -267,9 +270,9 @@ void ThreadIRCSeed2(void* parg)
 
     while (!fShutdown)
     {
-        CAddress addrConnect("92.243.23.21", 6667); // irc.lfnet.org
+        CService addrConnect("92.243.23.21", 6667); // irc.lfnet.org
 
-        CAddress addrIRC("irc.lfnet.org", 6667, true);
+        CService addrIRC("irc.lfnet.org", 6667, true);
         if (addrIRC.IsValid())
             addrConnect = addrIRC;
 
@@ -325,15 +328,15 @@ void ThreadIRCSeed2(void* parg)
         Sleep(500);
 
         // Get our external IP from the IRC server and re-nick before joining the channel
-        CAddress addrFromIRC;
-        if (GetIPFromIRC(hSocket, strMyName, addrFromIRC.ip))
+        CNetAddr addrFromIRC;
+        if (GetIPFromIRC(hSocket, strMyName, addrFromIRC))
         {
-            printf("GetIPFromIRC() returned %s\n", addrFromIRC.ToStringIP().c_str());
+            printf("GetIPFromIRC() returned %s\n", addrFromIRC.ToString().c_str());
             if (!fUseProxy && addrFromIRC.IsRoutable())
             {
                 // IRC lets you to re-nick
                 fGotExternalIP = true;
-                addrLocalHost.ip = addrFromIRC.ip;
+                addrLocalHost.SetIP(addrFromIRC);
                 strMyName = EncodeAddress(addrLocalHost);
                 Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str());
             }
index 94ec552..c28222a 100644 (file)
--- a/src/key.h
+++ b/src/key.h
@@ -59,16 +59,30 @@ class CKey
 protected:
     EC_KEY* pkey;
     bool fSet;
+    bool fCompressedPubKey;
+
+    void SetCompressedPubKey()
+    {
+        EC_KEY_set_conv_form(pkey, POINT_CONVERSION_COMPRESSED);
+        fCompressedPubKey = true;
+    }
 
 public:
-    CKey()
+
+    void Reset()
     {
+        fCompressedPubKey = false;
         pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
         if (pkey == NULL)
             throw key_error("CKey::CKey() : EC_KEY_new_by_curve_name failed");
         fSet = false;
     }
 
+    CKey()
+    {
+        Reset();
+    }
+
     CKey(const CKey& b)
     {
         pkey = EC_KEY_dup(b.pkey);
@@ -95,10 +109,17 @@ public:
         return !fSet;
     }
 
-    void MakeNewKey()
+    bool IsCompressed() const
+    {
+        return fCompressedPubKey;
+    }
+
+    void MakeNewKey(bool fCompressed = true)
     {
         if (!EC_KEY_generate_key(pkey))
             throw key_error("CKey::MakeNewKey() : EC_KEY_generate_key failed");
+        if (fCompressed)
+            SetCompressedPubKey();
         fSet = true;
     }
 
@@ -111,7 +132,7 @@ public:
         return true;
     }
 
-    bool SetSecret(const CSecret& vchSecret)
+    bool SetSecret(const CSecret& vchSecret, bool fCompressed = false)
     {
         EC_KEY_free(pkey);
         pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
@@ -126,10 +147,12 @@ public:
             throw key_error("CKey::SetSecret() : EC_KEY_regenerate_key failed");
         BN_clear_free(bn);
         fSet = true;
+        if (fCompressed || fCompressedPubKey)
+            SetCompressedPubKey();
         return true;
     }
 
-    CSecret GetSecret() const
+    CSecret GetSecret(bool &fCompressed) const
     {
         CSecret vchRet;
         vchRet.resize(32);
@@ -140,6 +163,7 @@ public:
         int n=BN_bn2bin(bn,&vchRet[32 - nBytes]);
         if (n != nBytes) 
             throw key_error("CKey::GetSecret(): BN_bn2bin failed");
+        fCompressed = fCompressedPubKey;
         return vchRet;
     }
 
@@ -161,6 +185,8 @@ public:
         if (!o2i_ECPublicKey(&pkey, &pbegin, vchPubKey.size()))
             return false;
         fSet = true;
+        if (vchPubKey.size() == 33)
+            SetCompressedPubKey();
         return true;
     }
 
@@ -210,6 +236,8 @@ public:
             {
                 CKey keyRec;
                 keyRec.fSet = true;
+                if (fCompressedPubKey)
+                    keyRec.SetCompressedPubKey();
                 if (ECDSA_SIG_recover_key_GFp(keyRec.pkey, sig, (unsigned char*)&hash, sizeof(hash), i, 1) == 1)
                     if (keyRec.GetPubKey() == this->GetPubKey())
                     {
@@ -221,7 +249,7 @@ public:
             if (nRecId == -1)
                 throw key_error("CKey::SignCompact() : unable to construct recoverable key");
 
-            vchSig[0] = nRecId+27;
+            vchSig[0] = nRecId+27+(fCompressedPubKey ? 4 : 0);
             BN_bn2bin(sig->r,&vchSig[33-(nBitsR+7)/8]);
             BN_bn2bin(sig->s,&vchSig[65-(nBitsS+7)/8]);
             fOk = true;
@@ -238,7 +266,8 @@ public:
     {
         if (vchSig.size() != 65)
             return false;
-        if (vchSig[0]<27 || vchSig[0]>=31)
+        int nV = vchSig[0];
+        if (nV<27 || nV>=35)
             return false;
         ECDSA_SIG *sig = ECDSA_SIG_new();
         BN_bin2bn(&vchSig[1],32,sig->r);
@@ -246,7 +275,12 @@ public:
 
         EC_KEY_free(pkey);
         pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
-        if (ECDSA_SIG_recover_key_GFp(pkey, sig, (unsigned char*)&hash, sizeof(hash), vchSig[0] - 27, 0) == 1)
+        if (nV >= 31)
+        {
+            SetCompressedPubKey();
+            nV -= 4;
+        }
+        if (ECDSA_SIG_recover_key_GFp(pkey, sig, (unsigned char*)&hash, sizeof(hash), nV - 27, 0) == 1)
         {
             fSet = true;
             ECDSA_SIG_free(sig);
index 21fb0f9..61d84ec 100644 (file)
@@ -29,15 +29,17 @@ bool CKeyStore::GetPubKey(const CBitcoinAddress &address, std::vector<unsigned c
 
 bool CBasicKeyStore::AddKey(const CKey& key)
 {
+    bool fCompressed = false;
+    CSecret secret = key.GetSecret(fCompressed);
     CRITICAL_BLOCK(cs_KeyStore)
-        mapKeys[CBitcoinAddress(key.GetPubKey())] = key.GetSecret();
+        mapKeys[CBitcoinAddress(key.GetPubKey())] = make_pair(secret, fCompressed);
     return true;
 }
 
-bool CBasicKeyStore::AddCScript(const uint160 &hash, const CScript& redeemScript)
+bool CBasicKeyStore::AddCScript(const CScript& redeemScript)
 {
     CRITICAL_BLOCK(cs_KeyStore)
-        mapScripts[hash] = redeemScript;
+        mapScripts[Hash160(redeemScript)] = redeemScript;
     return true;
 }
 
@@ -77,16 +79,6 @@ bool CCryptoKeyStore::SetCrypted()
     return true;
 }
 
-std::vector<unsigned char> CCryptoKeyStore::GenerateNewKey()
-{
-    RandAddSeedPerfmon();
-    CKey key;
-    key.MakeNewKey();
-    if (!AddKey(key))
-        throw std::runtime_error("CCryptoKeyStore::GenerateNewKey() : AddKey failed");
-    return key.GetPubKey();
-}
-
 bool CCryptoKeyStore::Unlock(const CKeyingMaterial& vMasterKeyIn)
 {
     CRITICAL_BLOCK(cs_KeyStore)
@@ -103,6 +95,7 @@ bool CCryptoKeyStore::Unlock(const CKeyingMaterial& vMasterKeyIn)
             if(!DecryptSecret(vMasterKeyIn, vchCryptedSecret, Hash(vchPubKey.begin(), vchPubKey.end()), vchSecret))
                 return false;
             CKey key;
+            key.SetPubKey(vchPubKey);
             key.SetSecret(vchSecret);
             if (key.GetPubKey() == vchPubKey)
                 break;
@@ -125,7 +118,8 @@ bool CCryptoKeyStore::AddKey(const CKey& key)
 
         std::vector<unsigned char> vchCryptedSecret;
         std::vector<unsigned char> vchPubKey = key.GetPubKey();
-        if (!EncryptSecret(vMasterKey, key.GetSecret(), Hash(vchPubKey.begin(), vchPubKey.end()), vchCryptedSecret))
+        bool fCompressed;
+        if (!EncryptSecret(vMasterKey, key.GetSecret(fCompressed), Hash(vchPubKey.begin(), vchPubKey.end()), vchCryptedSecret))
             return false;
 
         if (!AddCryptedKey(key.GetPubKey(), vchCryptedSecret))
@@ -147,19 +141,24 @@ bool CCryptoKeyStore::AddCryptedKey(const std::vector<unsigned char> &vchPubKey,
     return true;
 }
 
-bool CCryptoKeyStore::GetSecret(const CBitcoinAddress &address, CSecret& vchSecretOut) const
+bool CCryptoKeyStore::GetKey(const CBitcoinAddress &address, CKey& keyOut) const
 {
     CRITICAL_BLOCK(cs_KeyStore)
     {
         if (!IsCrypted())
-            return CBasicKeyStore::GetSecret(address, vchSecretOut);
+            return CBasicKeyStore::GetKey(address, keyOut);
 
         CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
         if (mi != mapCryptedKeys.end())
         {
             const std::vector<unsigned char> &vchPubKey = (*mi).second.first;
             const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
-            return DecryptSecret(vMasterKey, vchCryptedSecret, Hash(vchPubKey.begin(), vchPubKey.end()), vchSecretOut);
+            CSecret vchSecret;
+            if (!DecryptSecret(vMasterKey, vchCryptedSecret, Hash(vchPubKey.begin(), vchPubKey.end()), vchSecret))
+                return false;
+            keyOut.SetPubKey(vchPubKey);
+            keyOut.SetSecret(vchSecret);
+            return true;
         }
     }
     return false;
@@ -190,14 +189,15 @@ bool CCryptoKeyStore::EncryptKeys(CKeyingMaterial& vMasterKeyIn)
             return false;
 
         fUseCrypto = true;
-        CKey key;
         BOOST_FOREACH(KeyMap::value_type& mKey, mapKeys)
         {
-            if (!key.SetSecret(mKey.second))
+            CKey key;
+            if (!key.SetSecret(mKey.second.first, false))
                 return false;
             const std::vector<unsigned char> vchPubKey = key.GetPubKey();
             std::vector<unsigned char> vchCryptedSecret;
-            if (!EncryptSecret(vMasterKeyIn, key.GetSecret(), Hash(vchPubKey.begin(), vchPubKey.end()), vchCryptedSecret))
+            bool fCompressed;
+            if (!EncryptSecret(vMasterKeyIn, key.GetSecret(fCompressed), Hash(vchPubKey.begin(), vchPubKey.end()), vchCryptedSecret))
                 return false;
             if (!AddCryptedKey(vchPubKey, vchCryptedSecret))
                 return false;
index 669bf90..1d068b4 100644 (file)
@@ -20,36 +20,28 @@ public:
 
     // Check whether a key corresponding to a given address is present in the store.
     virtual bool HaveKey(const CBitcoinAddress &address) const =0;
-    virtual bool GetKey(const CBitcoinAddress &address, CKey& keyOut) const 
-    {
-        CSecret vchSecret;
-        if (!GetSecret(address, vchSecret))
-            return false;
-        if (!keyOut.SetSecret(vchSecret))
-            return false;
-        return true;
-    }
+    virtual bool GetKey(const CBitcoinAddress &address, CKey& keyOut) const =0;
     virtual void GetKeys(std::set<CBitcoinAddress> &setAddress) const =0;
     virtual bool GetPubKey(const CBitcoinAddress &address, std::vector<unsigned char>& vchPubKeyOut) const;
 
     // Support for BIP 0013 : see https://en.bitcoin.it/wiki/BIP_0013
-    virtual bool AddCScript(const uint160 &hash, const CScript& redeemScript) =0;
+    virtual bool AddCScript(const CScript& redeemScript) =0;
     virtual bool HaveCScript(const uint160 &hash) const =0;
     virtual bool GetCScript(const uint160 &hash, CScript& redeemScriptOut) const =0;
 
     // Generate a new key, and add it to the store
     virtual std::vector<unsigned char> GenerateNewKey();
-    virtual bool GetSecret(const CBitcoinAddress &address, CSecret& vchSecret) const
+    virtual bool GetSecret(const CBitcoinAddress &address, CSecret& vchSecret, bool &fCompressed) const
     {
         CKey key;
         if (!GetKey(address, key))
             return false;
-        vchSecret = key.GetSecret();
+        vchSecret = key.GetSecret(fCompressed);
         return true;
     }
 };
 
-typedef std::map<CBitcoinAddress, CSecret> KeyMap;
+typedef std::map<CBitcoinAddress, std::pair<CSecret, bool> > KeyMap;
 typedef std::map<uint160, CScript > ScriptMap;
 
 // Basic key store, that keeps keys in an address->secret map
@@ -81,20 +73,21 @@ public:
             }
         }
     }
-    bool GetSecret(const CBitcoinAddress &address, CSecret &vchSecret) const
+    bool GetKey(const CBitcoinAddress &address, CKey &keyOut) const
     {
         CRITICAL_BLOCK(cs_KeyStore)
         {
             KeyMap::const_iterator mi = mapKeys.find(address);
             if (mi != mapKeys.end())
             {
-                vchSecret = (*mi).second;
+                keyOut.Reset();
+                keyOut.SetSecret((*mi).second.first, (*mi).second.second);
                 return true;
             }
         }
         return false;
     }
-    virtual bool AddCScript(const uint160 &hash, const CScript& redeemScript);
+    virtual bool AddCScript(const CScript& redeemScript);
     virtual bool HaveCScript(const uint160 &hash) const;
     virtual bool GetCScript(const uint160 &hash, CScript& redeemScriptOut) const;
 };
@@ -154,7 +147,6 @@ public:
     }
 
     virtual bool AddCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
-    std::vector<unsigned char> GenerateNewKey();
     bool AddKey(const CKey& key);
     bool HaveKey(const CBitcoinAddress &address) const
     {
@@ -166,7 +158,7 @@ public:
         }
         return false;
     }
-    bool GetSecret(const CBitcoinAddress &address, CSecret& vchSecret) const;
+    bool GetKey(const CBitcoinAddress &address, CKey& keyOut) const;
     bool GetPubKey(const CBitcoinAddress &address, std::vector<unsigned char>& vchPubKeyOut) const;
     void GetKeys(std::set<CBitcoinAddress> &setAddress) const
     {
index 15f047b..1dbd50f 100644 (file)
@@ -7,6 +7,7 @@
 #include "db.h"
 #include "net.h"
 #include "init.h"
+#include <boost/algorithm/string/replace.hpp>
 #include <boost/filesystem.hpp>
 #include <boost/filesystem/fstream.hpp>
 
@@ -250,63 +251,76 @@ bool CTransaction::IsStandard() const
     BOOST_FOREACH(const CTxIn& txin, vin)
     {
         // Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG
-        // in an OP_EVAL, which is 3 ~80-byte signatures, 3
+        // pay-to-script-hash, which is 3 ~80-byte signatures, 3
         // ~65-byte public keys, plus a few script ops.
         if (txin.scriptSig.size() > 500)
-            return error("nonstandard txin, size %d is too large\n", txin.scriptSig.size());
+            return false;
         if (!txin.scriptSig.IsPushOnly())
-            return error("nonstandard txin (opcodes other than PUSH): %s", txin.scriptSig.ToString().c_str());
+            return false;
     }
     BOOST_FOREACH(const CTxOut& txout, vout)
         if (!::IsStandard(txout.scriptPubKey))
-            return error("nonstandard txout: %s", txout.scriptPubKey.ToString().c_str());
+            return false;
     return true;
 }
 
 //
 // Check transaction inputs, and make sure any
-// OP_EVAL transactions are evaluating IsStandard scripts
+// pay-to-script-hash transactions are evaluating IsStandard scripts
 //
 // Why bother? To avoid denial-of-service attacks; an attacker
-// can submit a standard DUP HASH... OP_EVAL transaction,
-// which will get accepted into blocks. The script being
-// EVAL'ed can be anything; an attacker could use a very
+// can submit a standard HASH... OP_EQUAL transaction,
+// which will get accepted into blocks. The redemption
+// script can be anything; an attacker could use a very
 // expensive-to-check-upon-redemption script like:
 //   DUP CHECKSIG DROP ... repeated 100 times... OP_1
 //
-bool CTransaction::AreInputsStandard(std::map<uint256, std::pair<CTxIndex, CTransaction> > mapInputs) const
+bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const
 {
-    if (fTestNet)
-        return true; // Allow non-standard on testnet
+    if (IsCoinBase())
+        return true; // Coinbases don't use vin normally
 
     for (int i = 0; i < vin.size(); i++)
     {
-        COutPoint prevout = vin[i].prevout;
-        assert(mapInputs.count(prevout.hash) > 0);
-        CTransaction& txPrev = mapInputs[prevout.hash].second;
-        assert(prevout.n < txPrev.vout.size());
+        const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
 
         vector<vector<unsigned char> > vSolutions;
         txnouttype whichType;
         // get the scriptPubKey corresponding to this input:
-        CScript& prevScript = txPrev.vout[prevout.n].scriptPubKey;
+        const CScript& prevScript = prev.scriptPubKey;
         if (!Solver(prevScript, whichType, vSolutions))
-            return error("nonstandard txin (spending nonstandard txout %s)", prevScript.ToString().c_str());
+            return false;
         if (whichType == TX_SCRIPTHASH)
         {
             vector<vector<unsigned char> > stack;
-            int nUnused;
-            if (!EvalScript(stack, vin[i].scriptSig, *this, i, 0, true, nUnused))
+
+            if (!EvalScript(stack, vin[i].scriptSig, *this, i, 0))
+                return false;
+            if (stack.empty())
                 return false;
             CScript subscript(stack.back().begin(), stack.back().end());
             if (!::IsStandard(subscript))
-                return error("nonstandard txin (nonstandard OP_EVAL subscript %s)", subscript.ToString().c_str());
+                return false;
         }
     }
 
     return true;
 }
 
+int
+CTransaction::GetLegacySigOpCount() const
+{
+    int nSigOps = 0;
+    BOOST_FOREACH(const CTxIn& txin, vin)
+    {
+        nSigOps += txin.scriptSig.GetSigOpCount(false);
+    }
+    BOOST_FOREACH(const CTxOut& txout, vout)
+    {
+        nSigOps += txout.scriptPubKey.GetSigOpCount(false);
+    }
+    return nSigOps;
+}
 
 
 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
@@ -473,34 +487,28 @@ bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMi
 
     if (fCheckInputs)
     {
-        map<uint256, pair<CTxIndex, CTransaction> > mapInputs;
+        MapPrevTx mapInputs;
         map<uint256, CTxIndex> mapUnused;
-        if (!FetchInputs(txdb, mapUnused, false, false, mapInputs))
+        bool fInvalid = false;
+        if (!FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
         {
+            if (fInvalid)
+                return error("AcceptToMemoryPool() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str());
             if (pfMissingInputs)
                 *pfMissingInputs = true;
             return error("AcceptToMemoryPool() : FetchInputs failed %s", hash.ToString().substr(0,10).c_str());
         }
 
-        // Check for non-standard OP_EVALs in inputs
-        if (!AreInputsStandard(mapInputs))
+        // Check for non-standard pay-to-script-hash in inputs
+        if (!AreInputsStandard(mapInputs) && !fTestNet)
             return error("AcceptToMemoryPool() : nonstandard transaction input");
 
-        // Check against previous transactions
-        int64 nFees = 0;
-        int nSigOps = 0;
-        if (!ConnectInputs(mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, nFees, false, false, nSigOps))
-        {
-            if (pfMissingInputs)
-                *pfMissingInputs = true;
-            return error("AcceptToMemoryPool() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
-        }
-        // Checking ECDSA signatures is a CPU bottleneck, so to avoid denial-of-service
-        // attacks disallow transactions with more than one SigOp per 65 bytes.
-        // 65 bytes because that is the minimum size of an ECDSA signature
+        // Note: if you modify this code to accept non-standard transactions, then
+        // you should add code here to check that the transaction does a
+        // reasonable number of ECDSA signature verifications.
+
+        int64 nFees = GetValueIn(mapInputs)-GetValueOut();
         unsigned int nSize = ::GetSerializeSize(*this, SER_NETWORK);
-        if (nSigOps > nSize / 65 || nSize < 100)
-            return error("AcceptToMemoryPool() : transaction with out-of-bounds SigOpCount");
 
         // Don't accept it if it can't get into a block
         if (nFees < GetMinFee(1000, true, GMF_RELAY))
@@ -530,6 +538,13 @@ bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMi
                 dFreeCount += nSize;
             }
         }
+
+        // Check against previous transactions
+        // This is done last to help prevent CPU exhaustion denial-of-service attacks.
+        if (!ConnectInputs(mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false))
+        {
+            return error("AcceptToMemoryPool() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
+        }
     }
 
     // Store transaction in memory
@@ -558,8 +573,11 @@ bool CTransaction::AcceptToMemoryPool(bool fCheckInputs, bool* pfMissingInputs)
     return AcceptToMemoryPool(txdb, fCheckInputs, pfMissingInputs);
 }
 
+uint64 nPooledTx = 0;
+
 bool CTransaction::AddToMemoryPoolUnchecked()
 {
+    printf("AcceptToMemoryPoolUnchecked(): size %lu\n",  mapTransactions.size());
     // Add to memory pool without checking anything.  Don't call this directly,
     // call AcceptToMemoryPool to properly check the transaction first.
     CRITICAL_BLOCK(cs_mapTransactions)
@@ -569,6 +587,7 @@ bool CTransaction::AddToMemoryPoolUnchecked()
         for (int i = 0; i < vin.size(); i++)
             mapNextTx[vin[i].prevout] = CInPoint(&mapTransactions[hash], i);
         nTransactionsUpdated++;
+        ++nPooledTx;
     }
     return true;
 }
@@ -583,6 +602,7 @@ bool CTransaction::RemoveFromMemoryPool()
             mapNextTx.erase(txin.prevout);
         mapTransactions.erase(GetHash());
         nTransactionsUpdated++;
+        --nPooledTx;
     }
     return true;
 }
@@ -898,8 +918,14 @@ bool CTransaction::DisconnectInputs(CTxDB& txdb)
 
 
 bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
-                               bool fBlock, bool fMiner, map<uint256, pair<CTxIndex, CTransaction> >& inputsRet)
+                               bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid)
 {
+    // FetchInputs can return false either because we just haven't seen some inputs
+    // (in which case the transaction should be stored as an orphan)
+    // or because the transaction is malformed (in which case the transaction should
+    // be dropped).  If tx is definitely invalid, fInvalid will be set to true.
+    fInvalid = false;
+
     if (IsCoinBase())
         return true; // Coinbase transactions have no inputs to fetch.
 
@@ -951,18 +977,66 @@ bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTes
     for (int i = 0; i < vin.size(); i++)
     {
         const COutPoint prevout = vin[i].prevout;
+        assert(inputsRet.count(prevout.hash) != 0);
         const CTxIndex& txindex = inputsRet[prevout.hash].first;
         const CTransaction& txPrev = inputsRet[prevout.hash].second;
         if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
+        {
+            // Revisit this if/when transaction replacement is implemented and allows
+            // adding inputs:
+            fInvalid = true;
             return DoS(100, error("FetchInputs() : %s prevout.n out of range %d %d %d prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str()));
+        }
     }
 
     return true;
 }
 
-bool CTransaction::ConnectInputs(map<uint256, pair<CTxIndex, CTransaction> > inputs,
-                                 map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
-                                 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int& nSigOpsRet, int64 nMinFee)
+const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const
+{
+    MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash);
+    if (mi == inputs.end())
+        throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found");
+
+    const CTransaction& txPrev = (mi->second).second;
+    if (input.prevout.n >= txPrev.vout.size())
+        throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range");
+
+    return txPrev.vout[input.prevout.n];
+}
+
+int64 CTransaction::GetValueIn(const MapPrevTx& inputs) const
+{
+    if (IsCoinBase())
+        return 0;
+
+    int64 nResult = 0;
+    for (int i = 0; i < vin.size(); i++)
+    {
+        nResult += GetOutputFor(vin[i], inputs).nValue;
+    }
+    return nResult;
+
+}
+
+int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const
+{
+    if (IsCoinBase())
+        return 0;
+
+    int nSigOps = 0;
+    for (int i = 0; i < vin.size(); i++)
+    {
+        const CTxOut& prevout = GetOutputFor(vin[i], inputs);
+        if (prevout.scriptPubKey.IsPayToScriptHash())
+            nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
+    }
+    return nSigOps;
+}
+
+bool CTransaction::ConnectInputs(MapPrevTx inputs,
+                                 map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
+                                 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash)
 {
     // Take over previous transactions' spent pointers
     // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
@@ -971,6 +1045,7 @@ bool CTransaction::ConnectInputs(map<uint256, pair<CTxIndex, CTransaction> > inp
     if (!IsCoinBase())
     {
         int64 nValueIn = 0;
+        int64 nFees = 0;
         for (int i = 0; i < vin.size(); i++)
         {
             COutPoint prevout = vin[i].prevout;
@@ -983,36 +1058,10 @@ bool CTransaction::ConnectInputs(map<uint256, pair<CTxIndex, CTransaction> > inp
 
             // If prev is coinbase, check that it's matured
             if (txPrev.IsCoinBase())
-                for (CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)
+                for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)
                     if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
                         return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight);
 
-            // Skip ECDSA signature verification when connecting blocks (fBlock=true)
-            // before the last blockchain checkpoint. This is safe because block merkle hashes are
-            // still computed and checked, and any change will be caught at the next checkpoint.
-            if (!(fBlock && (nBestHeight < Checkpoints::GetTotalBlocksEstimate())))
-            {
-                bool fStrictOpEval = true;
-                // This code should be removed when OP_EVAL has
-                // a majority of hashing power on the network.
-                if (fBlock)
-                {
-                    // To avoid being on the short end of a block-chain split,
-                    // interpret OP_EVAL as a NO_OP until blocks with timestamps
-                    // after opevaltime:
-                    int64 nEvalSwitchTime = GetArg("opevaltime", 1328054400); // Feb 1, 2012
-                    fStrictOpEval = (pindexBlock->nTime >= nEvalSwitchTime);
-                }
-                // if !fBlock, then always be strict-- don't accept
-                // invalid-under-new-rules OP_EVAL transactions into
-                // our memory pool (don't relay them, don't include them
-                // in blocks we mine).
-
-                // Verify signature
-                if (!VerifySignature(txPrev, *this, i, nSigOpsRet, fStrictOpEval))
-                    return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
-            }
-
             // Check for conflicts (double-spend)
             // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
             // for an attacker to attempt to split the network.
@@ -1024,6 +1073,16 @@ bool CTransaction::ConnectInputs(map<uint256, pair<CTxIndex, CTransaction> > inp
             if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
                 return DoS(100, error("ConnectInputs() : txin values out of range"));
 
+            // Skip ECDSA signature verification when connecting blocks (fBlock=true)
+            // before the last blockchain checkpoint. This is safe because block merkle hashes are
+            // still computed and checked, and any change will be caught at the next checkpoint.
+            if (!(fBlock && (nBestHeight < Checkpoints::GetTotalBlocksEstimate())))
+            {
+                // Verify signature
+                if (!VerifySignature(txPrev, *this, i, fStrictPayToScriptHash, 0))
+                    return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
+            }
+
             // Mark outpoints as spent
             txindex.vSpent[prevout.n] = posThisTx;
 
@@ -1041,24 +1100,11 @@ bool CTransaction::ConnectInputs(map<uint256, pair<CTxIndex, CTransaction> > inp
         int64 nTxFee = nValueIn - GetValueOut();
         if (nTxFee < 0)
             return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
-        if (nTxFee < nMinFee)
-            return false;
         nFees += nTxFee;
         if (!MoneyRange(nFees))
             return DoS(100, error("ConnectInputs() : nFees out of range"));
     }
 
-    if (fBlock)
-    {
-        // Add transaction to changes
-        mapTestPool[GetHash()] = CTxIndex(posThisTx, vout.size());
-    }
-    else if (fMiner)
-    {
-        // Add transaction to test pool
-        mapTestPool[GetHash()] = CTxIndex(CDiskTxPos(1,1,1), vout.size());
-    }
-
     return true;
 }
 
@@ -1084,8 +1130,7 @@ bool CTransaction::ClientConnectInputs()
                 return false;
 
             // Verify signature
-            int nUnused = 0;
-            if (!VerifySignature(txPrev, *this, i, nUnused, false))
+            if (!VerifySignature(txPrev, *this, i, true, 0))
                 return error("ConnectInputs() : VerifySignature failed");
 
             ///// this is redundant with the mapNextTx stuff, not sure which I want to get rid of
@@ -1138,6 +1183,12 @@ bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
     if (!CheckBlock())
         return false;
 
+    // To avoid being on the short end of a block-chain split,
+    // don't do secondary validation of pay-to-script-hash transactions
+    // until blocks with timestamps after paytoscripthashtime:
+    int64 nEvalSwitchTime = GetArg("-paytoscripthashtime", 1329264000); // Feb 15, 2012
+    bool fStrictPayToScriptHash = (pindex->nTime >= nEvalSwitchTime);
+
     //// issue here: it doesn't know the version
     unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - 1 + GetSizeOfCompactSize(vtx.size());
 
@@ -1146,16 +1197,37 @@ bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
     int nSigOps = 0;
     BOOST_FOREACH(CTransaction& tx, vtx)
     {
+        nSigOps += tx.GetLegacySigOpCount();
+        if (nSigOps > MAX_BLOCK_SIGOPS)
+            return DoS(100, error("ConnectBlock() : too many sigops"));
+
         CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
         nTxPos += ::GetSerializeSize(tx, SER_DISK);
 
-        map<uint256, pair<CTxIndex, CTransaction> > mapInputs;
-        if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs))
-            return false;
-        if (!tx.ConnectInputs(mapInputs, mapQueuedChanges, posThisTx, pindex, nFees, true, false, nSigOps))
-            return false;
-        if (nSigOps > MAX_BLOCK_SIGOPS)
-            return DoS(100, error("ConnectBlock() : too many sigops"));
+        MapPrevTx mapInputs;
+        if (!tx.IsCoinBase())
+        {
+            bool fInvalid;
+            if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid))
+                return false;
+
+            if (fStrictPayToScriptHash)
+            {
+                // Add in sigops done by pay-to-script-hash inputs;
+                // this is to prevent a "rogue miner" from creating
+                // an incredibly-expensive-to-validate block.
+                nSigOps += tx.GetP2SHSigOpCount(mapInputs);
+                if (nSigOps > MAX_BLOCK_SIGOPS)
+                    return DoS(100, error("ConnectBlock() : too many sigops"));
+            }
+
+            nFees += tx.GetValueIn(mapInputs)-tx.GetValueOut();
+
+            if (!tx.ConnectInputs(mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, fStrictPayToScriptHash))
+                return false;
+        }
+
+        mapQueuedChanges[tx.GetHash()] = CTxIndex(posThisTx, tx.vout.size());
     }
 
     // Write queued txindex changes
@@ -1278,6 +1350,14 @@ bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
 }
 
 
+static void
+runCommand(std::string strCommand)
+{
+    int nErr = ::system(strCommand.c_str());
+    if (nErr)
+        printf("runCommand error: system(%s) returned %d\n", strCommand.c_str(), nErr);
+}
+
 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
 {
     uint256 hash = GetHash();
@@ -1321,7 +1401,8 @@ bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
     }
 
     // Update best block in wallet (so we can detect restored wallets)
-    if (!IsInitialBlockDownload())
+    bool fIsInitialDownload = IsInitialBlockDownload();
+    if (!fIsInitialDownload)
     {
         const CBlockLocator locator(pindexNew);
         ::SetBestChain(locator);
@@ -1336,6 +1417,14 @@ bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
     nTransactionsUpdated++;
     printf("SetBestChain: new best=%s  height=%d  work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
 
+    std::string strCmd = GetArg("-blocknotify", "");
+
+    if (!fIsInitialDownload && !strCmd.empty())
+    {
+        boost::replace_all(strCmd, "%s", hashBestChain.GetHex());
+        boost::thread t(runCommand, strCmd); // thread runs free
+    }
+
     return true;
 }
 
@@ -1418,19 +1507,10 @@ bool CBlock::CheckBlock() const
         if (!tx.CheckTransaction())
             return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
 
-    // This code should be removed when a compatibility-breaking block chain split has passed.
-    // Compatibility check for old clients that counted sigops differently:
     int nSigOps = 0;
     BOOST_FOREACH(const CTransaction& tx, vtx)
     {
-        BOOST_FOREACH(const CTxIn& txin, tx.vin)
-        {
-            nSigOps += txin.scriptSig.GetSigOpCount();
-        }
-        BOOST_FOREACH(const CTxOut& txout, tx.vout)
-        {
-            nSigOps += txout.scriptPubKey.GetSigOpCount();
-        }
+        nSigOps += tx.GetLegacySigOpCount();
     }
     if (nSigOps > MAX_BLOCK_SIGOPS)
         return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
@@ -1931,7 +2011,7 @@ unsigned char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };
 
 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
 {
-    static map<unsigned int, vector<unsigned char> > mapReuseKey;
+    static map<CService, vector<unsigned char> > mapReuseKey;
     RandAddSeedPerfmon();
     if (fDebug) {
         printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
@@ -1987,7 +2067,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
 
         pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
 
-        AddTimeData(pfrom->addr.ip, nTime);
+        AddTimeData(pfrom->addr, nTime);
 
         // Change version
         if (pfrom->nVersion >= 209)
@@ -2093,7 +2173,8 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
                     static uint256 hashSalt;
                     if (hashSalt == 0)
                         RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
-                    uint256 hashRand = hashSalt ^ (((int64)addr.ip)<<32) ^ ((GetTime()+addr.ip)/(24*60*60));
+                    int64 hashAddr = addr.GetHash();
+                    uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
                     hashRand = Hash(BEGIN(hashRand), END(hashRand));
                     multimap<uint256, CNode*> mapMix;
                     BOOST_FOREACH(CNode* pnode, vNodes)
@@ -2392,12 +2473,12 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
         /// we have a chance to check the order here
 
         // Keep giving the same key to the same ip until they use it
-        if (!mapReuseKey.count(pfrom->addr.ip))
-            pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr.ip], true);
+        if (!mapReuseKey.count(pfrom->addr))
+            pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
 
         // Send back approval of order and pubkey to use
         CScript scriptPubKey;
-        scriptPubKey << mapReuseKey[pfrom->addr.ip] << OP_CHECKSIG;
+        scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
         pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
     }
 
@@ -2868,6 +2949,9 @@ public:
 };
 
 
+uint64 nLastBlockTx = 0;
+uint64 nLastBlockSize = 0;
+
 CBlock* CreateNewBlock(CReserveKey& reservekey)
 {
     CBlockIndex* pindexPrev = pindexBest;
@@ -2955,6 +3039,7 @@ CBlock* CreateNewBlock(CReserveKey& reservekey)
         // Collect transactions into block
         map<uint256, CTxIndex> mapTestPool;
         uint64 nBlockSize = 1000;
+        uint64 nBlockTx = 0;
         int nBlockSigOps = 100;
         while (!mapPriority.empty())
         {
@@ -2968,6 +3053,11 @@ CBlock* CreateNewBlock(CReserveKey& reservekey)
             if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
                 continue;
 
+            // Legacy limits on sigOps:
+            int nTxSigOps = tx.GetLegacySigOpCount();
+            if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
+                continue;
+
             // Transaction fee required depends on block size
             bool fAllowFree = (nBlockSize + nTxSize < 4000 || CTransaction::AllowFree(dPriority));
             int64 nMinFee = tx.GetMinFee(nBlockSize, fAllowFree, GMF_BLOCK);
@@ -2975,19 +3065,28 @@ CBlock* CreateNewBlock(CReserveKey& reservekey)
             // Connecting shouldn't fail due to dependency on other memory pool transactions
             // because we're already processing them in order of dependency
             map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
-            map<uint256, pair<CTxIndex, CTransaction> > mapInputs;
-            if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs))
+            MapPrevTx mapInputs;
+            bool fInvalid;
+            if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs, fInvalid))
                 continue;
-            int nTxSigOps = 0;
-            if (!tx.ConnectInputs(mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, nFees, false, true, nTxSigOps, nMinFee))
+
+            int64 nFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
+            if (nFees < nMinFee)
                 continue;
+
+            nTxSigOps += tx.GetP2SHSigOpCount(mapInputs);
             if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
                 continue;
+
+            if (!tx.ConnectInputs(mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, false, true))
+                continue;
+            mapTestPoolTmp[tx.GetHash()] = CTxIndex(CDiskTxPos(1,1,1), tx.vout.size());
             swap(mapTestPool, mapTestPoolTmp);
 
             // Added
             pblock->vtx.push_back(tx);
             nBlockSize += nTxSize;
+            ++nBlockTx;
             nBlockSigOps += nTxSigOps;
 
             // Add transactions that depend on this one to the priority queue
@@ -3005,6 +3104,11 @@ CBlock* CreateNewBlock(CReserveKey& reservekey)
                 }
             }
         }
+
+        nLastBlockTx = nBlockTx;
+        nLastBlockSize = nBlockSize;
+        printf("CreateNewBlock(): total size %lu\n", nBlockSize);
+
     }
     pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
 
@@ -3029,12 +3133,7 @@ void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int&
         hashPrevBlock = pblock->hashPrevBlock;
     }
     ++nExtraNonce;
-    pblock->vtx[0].vin[0].scriptSig = CScript() << pblock->nTime << CBigNum(nExtraNonce);
-
-    // Put "OP_EVAL" in the coinbase so everybody can tell when
-    // a majority of miners support it
-    const char* pOpEvalName = GetOpName(OP_EVAL);
-    pblock->vtx[0].vin[0].scriptSig += CScript() << std::vector<unsigned char>(pOpEvalName, pOpEvalName+strlen(pOpEvalName));
+    pblock->vtx[0].vin[0].scriptSig = (CScript() << pblock->nTime << CBigNum(nExtraNonce)) + COINBASE_FLAGS;
     assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);
 
     pblock->hashMerkleRoot = pblock->BuildMerkleTree();
index a7c1682..124b228 100644 (file)
@@ -49,6 +49,12 @@ static const int fHaveUPnP = false;
 #endif
 
 
+// Put "/P2SH/" in the coinbase so everybody can tell when
+// a majority of miners support it
+static const char* pszP2SH = "/P2SH/";
+static const CScript COINBASE_FLAGS = CScript() << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH));
+
+
 
 
 
@@ -62,7 +68,10 @@ extern CBigNum bnBestChainWork;
 extern CBigNum bnBestInvalidWork;
 extern uint256 hashBestChain;
 extern CBlockIndex* pindexBest;
+extern uint64 nPooledTx;
 extern unsigned int nTransactionsUpdated;
+extern uint64 nLastBlockTx;
+extern uint64 nLastBlockSize;
 extern double dHashesPerSec;
 extern int64 nHPSTimerStart;
 extern int64 nTimeBestReceived;
@@ -399,6 +408,8 @@ enum GetMinFee_mode
     GMF_SEND,
 };
 
+typedef std::map<uint256, std::pair<CTxIndex, CTransaction> > MapPrevTx;
+
 //
 // The basic transaction that is broadcasted on the network and contained in
 // blocks.  A transaction can contain multiple inputs and outputs.
@@ -499,9 +510,35 @@ public:
         return (vin.size() == 1 && vin[0].prevout.IsNull());
     }
 
+    /** Check for standard transaction types
+        @return True if all outputs (scriptPubKeys) use only standard transaction forms
+    */
     bool IsStandard() const;
-    bool AreInputsStandard(std::map<uint256, std::pair<CTxIndex, CTransaction> > mapInputs) const;
 
+    /** Check for standard transaction types
+        @param[in] mapInputs   Map of previous transactions that have outputs we're spending
+        @return True if all inputs (scriptSigs) use only standard transaction forms
+        @see CTransaction::FetchInputs
+    */
+    bool AreInputsStandard(const MapPrevTx& mapInputs) const;
+
+    /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
+        @return number of sigops this transaction's outputs will produce when spent
+        @see CTransaction::FetchInputs
+    */
+    int GetLegacySigOpCount() const;
+
+    /** Count ECDSA signature operations in pay-to-script-hash inputs.
+
+        @param[in] mapInputs   Map of previous transactions that have outputs we're spending
+        @return maximum number of sigops required to validate this transaction's inputs
+        @see CTransaction::FetchInputs
+     */
+    int GetP2SHSigOpCount(const MapPrevTx& mapInputs) const;
+
+    /** Amount of bitcoins spent by this transaction.
+        @return sum of all outputs (note: does not include fees)
+     */
     int64 GetValueOut() const
     {
         int64 nValueOut = 0;
@@ -514,6 +551,16 @@ public:
         return nValueOut;
     }
 
+    /** Amount of bitcoins coming in to this transaction
+        Note that lightweight clients may not know anything besides the hash of previous transactions,
+        so may not be able to calculate this.
+
+        @param[in] mapInputs   Map of previous transactions that have outputs we're spending
+        @return        Sum of value of all inputs (scriptSigs)
+        @see CTransaction::FetchInputs
+     */
+    int64 GetValueIn(const MapPrevTx& mapInputs) const;
+
     static bool AllowFree(double dPriority)
     {
         // Large (in bytes) low-priority (new, small-coin) transactions
@@ -629,17 +676,41 @@ public:
     bool ReadFromDisk(COutPoint prevout);
     bool DisconnectInputs(CTxDB& txdb);
 
-    // Fetch from memory and/or disk. inputsRet keys are transaction hashes.
+    /** Fetch from memory and/or disk. inputsRet keys are transaction hashes.
+
+     @param[in] txdb   Transaction database
+     @param[in] mapTestPool    List of pending changes to the transaction index database
+     @param[in] fBlock True if being called to add a new best-block to the chain
+     @param[in] fMiner True if being called by CreateNewBlock
+     @param[out] inputsRet     Pointers to this transaction's inputs
+     @param[out] fInvalid      returns true if transaction is invalid
+     @return   Returns true if all inputs are in txdb or mapTestPool
+     */
     bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
-                     bool fBlock, bool fMiner, std::map<uint256, std::pair<CTxIndex, CTransaction> >& inputsRet);
-    bool ConnectInputs(std::map<uint256, std::pair<CTxIndex, CTransaction> > inputs,
-                       std::map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
-                       CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int& nSigOpsRet, int64 nMinFee=0);
+                     bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid);
+
+    /** Sanity check previous transactions, then, if all checks succeed,
+        mark them as spent by this transaction.
+
+        @param[in] inputs      Previous transactions (from FetchInputs)
+        @param[out] mapTestPool        Keeps track of inputs that need to be updated on disk
+        @param[in] posThisTx   Position of this transaction on disk
+        @param[in] pindexBlock
+        @param[in] fBlock      true if called from ConnectBlock
+        @param[in] fMiner      true if called from CreateNewBlock
+        @param[in] fStrictPayToScriptHash      true if fully validating p2sh transactions
+        @return Returns true if all checks succeed
+     */
+    bool ConnectInputs(MapPrevTx inputs,
+                       std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
+                       const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash=true);
     bool ClientConnectInputs();
     bool CheckTransaction() const;
     bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
     bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL);
+
 protected:
+    const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const;
     bool AddToMemoryPoolUnchecked();
 public:
     bool RemoveFromMemoryPool();
index c96a121..9212698 100644 (file)
@@ -29,28 +29,6 @@ LIBS= \
 DEFS=-D_MT -DWIN32 -D_WINDOWS -DNOPCH -DUSE_SSL -DBOOST_THREAD_USE_LIB
 DEBUGFLAGS=-g
 CFLAGS=-O2 -w -Wno-invalid-offsetof -Wformat $(DEBUGFLAGS) $(DEFS) $(INCLUDEPATHS)
-HEADERS = \
-    base58.h \
-    bignum.h \
-    checkpoints.h \
-    crypter.h \
-    db.h \
-    headers.h \
-    init.h \
-    irc.h \
-    key.h \
-    keystore.h \
-    main.h \
-    net.h \
-    noui.h \
-    protocol.h \
-    bitcoinrpc.h \
-    script.h \
-    serialize.h \
-    strlcpy.h \
-    uint256.h \
-    util.h \
-    wallet.h
 
 
 ifdef USE_UPNP
@@ -61,8 +39,12 @@ endif
 
 LIBS += -l mingwthrd -l kernel32 -l user32 -l gdi32 -l comdlg32 -l winspool -l winmm -l shell32 -l comctl32 -l ole32 -l oleaut32 -l uuid -l rpcrt4 -l advapi32 -l ws2_32 -l shlwapi
 
+# TODO: make the mingw builds smarter about dependencies, like the linux/osx builds are
+HEADERS = $(wildcard *.h)
+
 OBJS= \
     obj/checkpoints.o \
+    obj/netbase.o \
     obj/crypter.o \
     obj/key.o \
     obj/db.o \
@@ -80,23 +62,22 @@ OBJS= \
 
 all: bitcoind.exe
 
-obj/nogui/%.o: %.cpp $(HEADERS)
+obj/%.o: %.cpp $(HEADERS)
        i586-mingw32msvc-g++ -c $(CFLAGS) -o $@ $<
 
-bitcoind.exe: $(OBJS:obj/%=obj/nogui/%)
+bitcoind.exe: $(OBJS:obj/%=obj/%)
        i586-mingw32msvc-g++ $(CFLAGS) -o $@ $(LIBPATHS) $^ $(LIBS)
 
 
 obj/test/%.o: obj/test/%.cpp $(HEADERS)
        i586-mingw32msvc-g++ -c $(CFLAGS) -o $@ $<
 
-test_bitcoin.exe: obj/test/test_bitcoin.o $(filter-out obj/nogui/init.o,$(OBJS:obj/%=obj/nogui/%))
+test_bitcoin.exe: obj/test/test_bitcoin.o $(filter-out obj/init.o,$(OBJS:obj/%=obj/%))
        i586-mingw32msvc-g++ $(CFLAGS) -o $@ $(LIBPATHS) $^ $(LIBS) -lboost_unit_test_framework-mt-s
 
 
 clean:
        -rm -f obj/*.o
-       -rm -f obj/nogui/*.o
        -rm -f obj/test/*.o
        -rm -f test/*.o
        -rm -f headers.h.gch
index ed718b8..c55e17a 100644 (file)
@@ -26,28 +26,7 @@ LIBS= \
 DEFS=-DWIN32 -D_WINDOWS -DNOPCH -DUSE_SSL -DBOOST_THREAD_USE_LIB
 DEBUGFLAGS=-g
 CFLAGS=-mthreads -O2 -w -Wno-invalid-offsetof -Wformat $(DEBUGFLAGS) $(DEFS) $(INCLUDEPATHS)
-HEADERS = \
-    base58.h \
-    bignum.h \
-    checkpoints.h \
-    crypter.h \
-    db.h \
-    headers.h \
-    init.h \
-    irc.h \
-    key.h \
-    keystore.h \
-    main.h \
-    net.h \
-    noui.h \
-    protocol.h \
-    bitcoinrpc.h \
-    script.h \
-    serialize.h \
-    strlcpy.h \
-    uint256.h \
-    util.h \
-    wallet.h
+
 
 ifdef USE_UPNP
  INCLUDEPATHS += -I"C:\miniupnpc-1.6-mgw"
@@ -58,8 +37,12 @@ endif
 
 LIBS += -l kernel32 -l user32 -l gdi32 -l comdlg32 -l winspool -l winmm -l shell32 -l comctl32 -l ole32 -l oleaut32 -l uuid -l rpcrt4 -l advapi32 -l ws2_32 -l shlwapi
 
+# TODO: make the mingw builds smarter about dependencies, like the linux/osx builds are
+HEADERS = $(wildcard *.h)
+
 OBJS= \
     obj/checkpoints.o \
+    obj/netbase.o \
     obj/crypter.o \
     obj/key.o \
     obj/db.o \
@@ -78,16 +61,16 @@ OBJS= \
 
 all: bitcoind.exe
 
-obj/nogui/%.o: %.cpp $(HEADERS)
+obj/%.o: %.cpp $(HEADERS)
        g++ -c $(CFLAGS) -o $@ $<
 
-bitcoind.exe: $(OBJS:obj/%=obj/nogui/%)
+bitcoind.exe: $(OBJS:obj/%=obj/%)
        g++ $(CFLAGS) -o $@ $(LIBPATHS) $^ $(LIBS)
 
 obj/test/test_bitcoin.o: $(wildcard test/*.cpp) $(HEADERS)
        g++ -c $(CFLAGS) -o $@ test/test_bitcoin.cpp
 
-test_bitcoin.exe: obj/test/test_bitcoin.o $(filter-out obj/nogui/init.o,$(OBJS:obj/%=obj/nogui/%))
+test_bitcoin.exe: obj/test/test_bitcoin.o $(filter-out obj/init.o,$(OBJS:obj/%=obj/%))
        g++ $(CFLAGS) -o $@ $(LIBPATHS) $^ $(LIBS)
 
 clean:
index 966829e..9943271 100644 (file)
@@ -23,6 +23,8 @@ USE_UPNP:=1
 LIBS= -dead_strip
 ifdef STATIC
 # Build STATIC if you are redistributing the bitcoind binary
+TESTLIBS += \
+ $(DEPSDIR)/lib/libboost_unit_test_framework-mt.a
 LIBS += \
  $(DEPSDIR)/lib/db48/libdb_cxx-4.8.a \
  $(DEPSDIR)/lib/libboost_system-mt.a \
@@ -30,8 +32,11 @@ LIBS += \
  $(DEPSDIR)/lib/libboost_program_options-mt.a \
  $(DEPSDIR)/lib/libboost_thread-mt.a \
  $(DEPSDIR)/lib/libssl.a \
- $(DEPSDIR)/lib/libcrypto.a
+ $(DEPSDIR)/lib/libcrypto.a \
+ -lz
 else
+TESTLIBS += \
+ -lboost_unit_test_framework-mt
 LIBS += \
  -ldb_cxx-4.8 \
  -lboost_system-mt \
@@ -39,39 +44,22 @@ LIBS += \
  -lboost_program_options-mt \
  -lboost_thread-mt \
  -lssl \
- -lcrypto
+ -lcrypto \
+ -lz
+TESTDEFS += -DBOOST_TEST_DYN_LINK
 endif
 
 DEFS=-DMAC_OSX -DMSG_NOSIGNAL=0 -DUSE_SSL
 
 DEBUGFLAGS=-g
 # ppc doesn't work because we don't support big-endian
-CFLAGS=-mmacosx-version-min=10.5 -arch i386 -O3 -Wno-invalid-offsetof -Wformat $(DEBUGFLAGS) $(DEFS) $(INCLUDEPATHS)
-HEADERS = \
-    base58.h \
-    bignum.h \
-    checkpoints.h \
-    crypter.h \
-    db.h \
-    headers.h \
-    init.h \
-    irc.h \
-    key.h \
-    keystore.h \
-    main.h \
-    net.h \
-    noui.h \
-    protocol.h \
-    bitcoinrpc.h \
-    script.h \
-    serialize.h \
-    strlcpy.h \
-    uint256.h \
-    util.h \
-    wallet.h
+CFLAGS=-mmacosx-version-min=10.5 -arch i386 -O3 \
+    -Wextra -Wno-sign-compare -Wno-char-subscripts -Wno-invalid-offsetof -Wformat-security \
+    $(DEBUGFLAGS) $(DEFS) $(INCLUDEPATHS)
 
 OBJS= \
     obj/checkpoints.o \
+    obj/netbase.o \
     obj/crypter.o \
     obj/key.o \
     obj/db.o \
@@ -99,36 +87,34 @@ endif
 all: bitcoind
 
 # auto-generated dependencies:
--include obj/nogui/*.P
--include obj/test/*.P
+-include obj/*.P
+-include obj-test/*.P
 
-obj/nogui/%.o: %.cpp
+obj/%.o: %.cpp
        $(CXX) -c $(CFLAGS) -MMD -o $@ $<
        @cp $(@:%.o=%.d) $(@:%.o=%.P); \
          sed -e 's/#.*//' -e 's/^[^:]*: *//' -e 's/ *\\$$//' \
              -e '/^$$/ d' -e 's/$$/ :/' < $(@:%.o=%.d) >> $(@:%.o=%.P); \
          rm -f $(@:%.o=%.d)
 
-bitcoind: $(OBJS:obj/%=obj/nogui/%)
+bitcoind: $(OBJS:obj/%=obj/%)
        $(CXX) $(CFLAGS) -o $@ $(LIBPATHS) $^ $(LIBS)
 
-TESTOBJS := $(patsubst test/%.cpp,obj/test/%.o,$(wildcard test/*.cpp))
+TESTOBJS := $(patsubst test/%.cpp,obj-test/%.o,$(wildcard test/*.cpp))
 
-obj/test/%.o: test/%.cpp
-       $(CXX) -c $(CFLAGS) -MMD -o $@ $<
+obj-test/%.o: test/%.cpp
+       $(CXX) -c $(TESTDEFS) $(CFLAGS) -MMD -o $@ $<
        @cp $(@:%.o=%.d) $(@:%.o=%.P); \
          sed -e 's/#.*//' -e 's/^[^:]*: *//' -e 's/ *\\$$//' \
              -e '/^$$/ d' -e 's/$$/ :/' < $(@:%.o=%.d) >> $(@:%.o=%.P); \
          rm -f $(@:%.o=%.d)
 
-test_bitcoin: $(TESTOBJS) $(filter-out obj/nogui/init.o,$(OBJS:obj/%=obj/nogui/%))
-       $(CXX) $(CFLAGS) -o $@ $(LIBPATHS) $^ $(LIBS) $(DEPSDIR)/lib/libboost_unit_test_framework-mt.a
+test_bitcoin: $(TESTOBJS) $(filter-out obj/init.o,$(OBJS:obj/%=obj/%))
+       $(CXX) $(CFLAGS) -o $@ $(LIBPATHS) $^ $(LIBS) $(TESTLIBS)
 
 clean:
        -rm -f bitcoind test_bitcoin
        -rm -f obj/*.o
-       -rm -f obj/nogui/*.o
-       -rm -f obj/test/*.o
+       -rm -f obj-test/*.o
        -rm -f obj/*.P
-       -rm -f obj/nogui/*.P
-       -rm -f obj/test/*.P
+       -rm -f obj-test/*.P
index 055f7ab..41452de 100644 (file)
@@ -16,6 +16,8 @@ ifdef STATIC
        ifeq (${STATIC}, all)
                LMODE2 = static
        endif
+else
+       TESTDEFS += -DBOOST_TEST_DYN_LINK
 endif
 
 # for boost 1.37, add -mt to the boost libraries
@@ -83,32 +85,12 @@ LIBS+= \
 
 DEBUGFLAGS=-g
 CXXFLAGS=-O2
-xCXXFLAGS=-pthread -Wno-invalid-offsetof -Wformat $(DEBUGFLAGS) $(DEFS) $(HARDENING) $(CXXFLAGS)
-HEADERS = \
-    base58.h \
-    bignum.h \
-    checkpoints.h \
-    crypter.h \
-    db.h \
-    headers.h \
-    init.h \
-    irc.h \
-    key.h \
-    keystore.h \
-    main.h \
-    net.h \
-    noui.h \
-    protocol.h \
-    bitcoinrpc.h \
-    script.h \
-    serialize.h \
-    strlcpy.h \
-    uint256.h \
-    util.h \
-    wallet.h
+xCXXFLAGS=-pthread -Wextra -Wno-sign-compare -Wno-char-subscripts -Wno-invalid-offsetof -Wformat-security \
+    $(DEBUGFLAGS) $(DEFS) $(HARDENING) $(CXXFLAGS)
 
 OBJS= \
     obj/checkpoints.o \
+    obj/netbase.o \
     obj/crypter.o \
     obj/key.o \
     obj/db.o \
@@ -128,36 +110,34 @@ OBJS= \
 all: bitcoind
 
 # auto-generated dependencies:
--include obj/nogui/*.P
--include obj/test/*.P
+-include obj/*.P
+-include obj-test/*.P
 
-obj/nogui/%.o: %.cpp
+obj/%.o: %.cpp
        $(CXX) -c $(xCXXFLAGS) -MMD -o $@ $<
        @cp $(@:%.o=%.d) $(@:%.o=%.P); \
          sed -e 's/#.*//' -e 's/^[^:]*: *//' -e 's/ *\\$$//' \
              -e '/^$$/ d' -e 's/$$/ :/' < $(@:%.o=%.d) >> $(@:%.o=%.P); \
          rm -f $(@:%.o=%.d)
 
-bitcoind: $(OBJS:obj/%=obj/nogui/%)
+bitcoind: $(OBJS:obj/%=obj/%)
        $(CXX) $(xCXXFLAGS) -o $@ $^ $(LDFLAGS) $(LIBS)
 
-TESTOBJS := $(patsubst test/%.cpp,obj/test/%.o,$(wildcard test/*.cpp))
+TESTOBJS := $(patsubst test/%.cpp,obj-test/%.o,$(wildcard test/*.cpp))
 
-obj/test/%.o: test/%.cpp
-       $(CXX) -c $(xCXXFLAGS) -MMD -o $@ $<
+obj-test/%.o: test/%.cpp
+       $(CXX) -c $(TESTDEFS) $(xCXXFLAGS) -MMD -o $@ $<
        @cp $(@:%.o=%.d) $(@:%.o=%.P); \
          sed -e 's/#.*//' -e 's/^[^:]*: *//' -e 's/ *\\$$//' \
              -e '/^$$/ d' -e 's/$$/ :/' < $(@:%.o=%.d) >> $(@:%.o=%.P); \
          rm -f $(@:%.o=%.d)
 
-test_bitcoin: $(TESTOBJS) $(filter-out obj/nogui/init.o,$(OBJS:obj/%=obj/nogui/%))
-       $(CXX) $(xCXXFLAGS) -o $@ $(LIBPATHS) $^ -Wl,-Bstatic -lboost_unit_test_framework $(LDFLAGS) $(LIBS)
+test_bitcoin: $(TESTOBJS) $(filter-out obj/init.o,$(OBJS:obj/%=obj/%))
+       $(CXX) $(xCXXFLAGS) -o $@ $(LIBPATHS) $^ -Wl,-B$(LMODE) -lboost_unit_test_framework $(LDFLAGS) $(LIBS)
 
 clean:
        -rm -f bitcoind test_bitcoin
        -rm -f obj/*.o
-       -rm -f obj/nogui/*.o
-       -rm -f obj/test/*.o
+       -rm -f obj-test/*.o
        -rm -f obj/*.P
-       -rm -f obj/nogui/*.P
-       -rm -f obj/test/*.P
+       -rm -f obj-test/*.P
diff --git a/src/makefile.vc b/src/makefile.vc
deleted file mode 100644 (file)
index 60f1e09..0000000
+++ /dev/null
@@ -1,153 +0,0 @@
-# Copyright (c) 2009-2010 Satoshi Nakamoto
-# Distributed under the MIT/X11 software license, see the accompanying
-# file license.txt or http://www.opensource.org/licenses/mit-license.php.
-
-
-INCLUDEPATHS= \
-  /I"/boost" \
-  /I"/db/build_windows" \
-  /I"/openssl/include" \
-  /I"/miniupnpc"
-
-LIBPATHS= \
-  /LIBPATH:"/boost/stage/lib" \
-  /LIBPATH:"/db/build_windows/Release" \
-  /LIBPATH:"/openssl/lib" \
-  /LIBPATH:"/miniupnpc/msvc/Release" \
-  /NODEFAULTLIB:libc.lib /NODEFAULTLIB:libcmt.lib \
-  /NODEFAULTLIB:libcd.lib /NODEFAULTLIB:libcmtd.lib \
-  /NODEFAULTLIB:msvcrtd.lib
-
-USE_UPNP=0
-
-DEFS=/DWIN32 /D_WINDOWS /DNOPCH /DNOMINMAX
-
-LIBS= \
-  libboost_system-vc100-mt.lib \
-  libboost_filesystem-vc100-mt.lib \
-  libboost_program_options-vc100-mt.lib \
-  libboost_thread-vc100-mt.lib \
-  libdb47s.lib \
-  libeay32.lib
-
-!IFDEF USE_UPNP
-LIBS=$(LIBS) miniupnpc.lib
-DEFS=$(DEFS) /DUSE_UPNP=$(USE_UPNP)
-!ENDIF
-
-LIBS=$(LIBS) \
-  kernel32.lib user32.lib gdi32.lib comdlg32.lib winspool.lib winmm.lib shell32.lib comctl32.lib ole32.lib oleaut32.lib uuid.lib rpcrt4.lib advapi32.lib ws2_32.lib shlwapi.lib iphlpapi.lib
-
-DEBUGFLAGS=/Os
-CFLAGS=/MD /c /nologo /EHsc /GR /Zm300 $(DEBUGFLAGS) $(DEFS) $(INCLUDEPATHS)
-HEADERS = \
-    base58.h \
-    bignum.h \
-    checkpoints.h \
-    crypter.h \
-    db.h \
-    headers.h \
-    init.h \
-    irc.h \
-    key.h \
-    keystore.h \
-    main.h \
-    net.h \
-    noui.h \
-    protocol.h \
-    bitcoinrpc.h \
-    script.h \
-    serialize.h \
-    strlcpy.h \
-    ui.h \
-    uibase.h \
-    uint256.h \
-    util.h \
-    wallet.h
-
-OBJS= \
-    obj\checkpoints.o \
-    obj\crypter.o \
-    obj\db.o \
-    obj\init.o \
-    obj\irc.o \
-    obj\keystore.o \
-    obj\main.o \
-    obj\net.o \
-    obj\rpc.o \
-    obj\protocol.o \
-    obj\script.o \
-    obj\util.o \
-    obj\wallet.o
-
-RC=../share
-
-
-all: bitcoind.exe
-
-
-.cpp{obj}.obj:
-    cl $(CFLAGS) /DGUI /Fo$@ %s
-
-obj\checkpoints.obj: $(HEADERS)
-
-obj\util.obj: $(HEADERS)
-
-obj\script.obj: $(HEADERS)
-
-obj\db.obj: $(HEADERS)
-
-obj\net.obj: $(HEADERS)
-
-obj\irc.obj: $(HEADERS)
-
-obj\keystore.obj: $(HEADERS)
-
-obj\main.obj: $(HEADERS)
-
-obj\wallet.obj: $(HEADERS)
-
-obj\rpc.obj: $(HEADERS)
-
-obj\init.obj: $(HEADERS)
-
-obj\crypter.obj: $(HEADERS)
-
-obj\ui.obj: $(HEADERS)
-
-obj\uibase.obj: $(HEADERS)
-
-.cpp{obj\nogui}.obj:
-    cl $(CFLAGS) /Fo$@ %s
-
-obj\nogui\checkpoints.obj: $(HEADERS)
-
-obj\nogui\util.obj: $(HEADERS)
-
-obj\nogui\script.obj: $(HEADERS)
-
-obj\nogui\db.obj: $(HEADERS)
-
-obj\nogui\net.obj: $(HEADERS)
-
-obj\nogui\irc.obj: $(HEADERS)
-
-obj\nogui\keystore.obj: $(HEADERS)
-
-obj\nogui\main.obj: $(HEADERS)
-
-obj\nogui\wallet.obj: $(HEADERS)
-
-obj\nogui\rpc.obj: $(HEADERS)
-
-obj\nogui\init.obj: $(HEADERS)
-
-bitcoind.exe: $(OBJS:obj\=obj\nogui\) obj\ui.res
-    link /nologo /OUT:$@ $(LIBPATHS) $** $(LIBS)
-
-clean:
-    -del /Q obj\*
-    -del /Q obj\nogui\*
-    -del /Q *.ilk
-    -del /Q *.pdb
-    -del /Q bitcoind.exe
index 6dab7e8..a0e093d 100644 (file)
@@ -29,6 +29,7 @@ static const int MAX_OUTBOUND_CONNECTIONS = 8;
 void ThreadMessageHandler2(void* parg);
 void ThreadSocketHandler2(void* parg);
 void ThreadOpenConnections2(void* parg);
+void ThreadOpenAddedConnections2(void* parg);
 #ifdef USE_UPNP
 void ThreadMapPort2(void* parg);
 #endif
@@ -45,7 +46,7 @@ bool OpenNetworkConnection(const CAddress& addrConnect);
 bool fClient = false;
 bool fAllowDNS = false;
 uint64 nLocalServices = (fClient ? 0 : NODE_NETWORK);
-CAddress addrLocalHost("0.0.0.0", 0, false, nLocalServices);
+CAddress addrLocalHost(CService("0.0.0.0", 0), nLocalServices);
 static CNode* pnodeLocalHost = NULL;
 uint64 nLocalHostNonce = 0;
 array<int, 10> vnThreadsRunning;
@@ -60,10 +61,9 @@ deque<pair<int64, CInv> > vRelayExpiration;
 CCriticalSection cs_mapRelay;
 map<CInv, int64> mapAlreadyAskedFor;
 
-// Settings
-int fUseProxy = false;
-int nConnectTimeout = 5000;
-CAddress addrProxy("127.0.0.1",9050);
+
+set<CNetAddr> setservAddNodeAddresses;
+CCriticalSection cs_setservAddNodeAddresses;
 
 
 
@@ -88,213 +88,7 @@ void CNode::PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd)
 
 
 
-bool ConnectSocket(const CAddress& addrConnect, SOCKET& hSocketRet, int nTimeout)
-{
-    hSocketRet = INVALID_SOCKET;
-
-    SOCKET hSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
-    if (hSocket == INVALID_SOCKET)
-        return false;
-#ifdef SO_NOSIGPIPE
-    int set = 1;
-    setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int));
-#endif
-
-    bool fProxy = (fUseProxy && addrConnect.IsRoutable());
-    struct sockaddr_in sockaddr = (fProxy ? addrProxy.GetSockAddr() : addrConnect.GetSockAddr());
-
-#ifdef WIN32
-    u_long fNonblock = 1;
-    if (ioctlsocket(hSocket, FIONBIO, &fNonblock) == SOCKET_ERROR)
-#else
-    int fFlags = fcntl(hSocket, F_GETFL, 0);
-    if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) == -1)
-#endif
-    {
-        closesocket(hSocket);
-        return false;
-    }
-
-
-    if (connect(hSocket, (struct sockaddr*)&sockaddr, sizeof(sockaddr)) == SOCKET_ERROR)
-    {
-        // WSAEINVAL is here because some legacy version of winsock uses it
-        if (WSAGetLastError() == WSAEINPROGRESS || WSAGetLastError() == WSAEWOULDBLOCK || WSAGetLastError() == WSAEINVAL)
-        {
-            struct timeval timeout;
-            timeout.tv_sec  = nTimeout / 1000;
-            timeout.tv_usec = (nTimeout % 1000) * 1000;
-
-            fd_set fdset;
-            FD_ZERO(&fdset);
-            FD_SET(hSocket, &fdset);
-            int nRet = select(hSocket + 1, NULL, &fdset, NULL, &timeout);
-            if (nRet == 0)
-            {
-                printf("connection timeout\n");
-                closesocket(hSocket);
-                return false;
-            }
-            if (nRet == SOCKET_ERROR)
-            {
-                printf("select() for connection failed: %i\n",WSAGetLastError());
-                closesocket(hSocket);
-                return false;
-            }
-            socklen_t nRetSize = sizeof(nRet);
-#ifdef WIN32
-            if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (char*)(&nRet), &nRetSize) == SOCKET_ERROR)
-#else
-            if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, &nRet, &nRetSize) == SOCKET_ERROR)
-#endif
-            {
-                printf("getsockopt() for connection failed: %i\n",WSAGetLastError());
-                closesocket(hSocket);
-                return false;
-            }
-            if (nRet != 0)
-            {
-                printf("connect() failed after select(): %s\n",strerror(nRet));
-                closesocket(hSocket);
-                return false;
-            }
-        }
-#ifdef WIN32
-        else if (WSAGetLastError() != WSAEISCONN)
-#else
-        else
-#endif
-        {
-            printf("connect() failed: %i\n",WSAGetLastError());
-            closesocket(hSocket);
-            return false;
-        }
-    }
-
-    /*
-    this isn't even strictly necessary
-    CNode::ConnectNode immediately turns the socket back to non-blocking
-    but we'll turn it back to blocking just in case
-    */
-#ifdef WIN32
-    fNonblock = 0;
-    if (ioctlsocket(hSocket, FIONBIO, &fNonblock) == SOCKET_ERROR)
-#else
-    fFlags = fcntl(hSocket, F_GETFL, 0);
-    if (fcntl(hSocket, F_SETFL, fFlags & !O_NONBLOCK) == SOCKET_ERROR)
-#endif
-    {
-        closesocket(hSocket);
-        return false;
-    }
-
-    if (fProxy)
-    {
-        printf("proxy connecting %s\n", addrConnect.ToString().c_str());
-        char pszSocks4IP[] = "\4\1\0\0\0\0\0\0user";
-        memcpy(pszSocks4IP + 2, &addrConnect.port, 2);
-        memcpy(pszSocks4IP + 4, &addrConnect.ip, 4);
-        char* pszSocks4 = pszSocks4IP;
-        int nSize = sizeof(pszSocks4IP);
-
-        int ret = send(hSocket, pszSocks4, nSize, MSG_NOSIGNAL);
-        if (ret != nSize)
-        {
-            closesocket(hSocket);
-            return error("Error sending to proxy");
-        }
-        char pchRet[8];
-        if (recv(hSocket, pchRet, 8, 0) != 8)
-        {
-            closesocket(hSocket);
-            return error("Error reading proxy response");
-        }
-        if (pchRet[1] != 0x5a)
-        {
-            closesocket(hSocket);
-            if (pchRet[1] != 0x5b)
-                printf("ERROR: Proxy returned error %d\n", pchRet[1]);
-            return false;
-        }
-        printf("proxy connected %s\n", addrConnect.ToString().c_str());
-    }
-
-    hSocketRet = hSocket;
-    return true;
-}
-
-// portDefault is in host order
-bool Lookup(const char *pszName, vector<CAddress>& vaddr, int nServices, int nMaxSolutions, bool fAllowLookup, int portDefault, bool fAllowPort)
-{
-    vaddr.clear();
-    if (pszName[0] == 0)
-        return false;
-    int port = portDefault;
-    char psz[256];
-    char *pszHost = psz;
-    strlcpy(psz, pszName, sizeof(psz));
-    if (fAllowPort)
-    {
-        char* pszColon = strrchr(psz+1,':');
-        char *pszPortEnd = NULL;
-        int portParsed = pszColon ? strtoul(pszColon+1, &pszPortEnd, 10) : 0;
-        if (pszColon && pszPortEnd && pszPortEnd[0] == 0)
-        {
-            if (psz[0] == '[' && pszColon[-1] == ']')
-            {
-                // Future: enable IPv6 colon-notation inside []
-                pszHost = psz+1;
-                pszColon[-1] = 0;
-            }
-            else
-                pszColon[0] = 0;
-            port = portParsed;
-            if (port < 0 || port > std::numeric_limits<unsigned short>::max())
-                port = std::numeric_limits<unsigned short>::max();
-        }
-    }
-
-    unsigned int addrIP = inet_addr(pszHost);
-    if (addrIP != INADDR_NONE)
-    {
-        // valid IP address passed
-        vaddr.push_back(CAddress(addrIP, port, nServices));
-        return true;
-    }
-
-    if (!fAllowLookup)
-        return false;
-
-    struct hostent* phostent = gethostbyname(pszHost);
-    if (!phostent)
-        return false;
-
-    if (phostent->h_addrtype != AF_INET)
-        return false;
-
-    char** ppAddr = phostent->h_addr_list;
-    while (*ppAddr != NULL && vaddr.size() != nMaxSolutions)
-    {
-        CAddress addr(((struct in_addr*)ppAddr[0])->s_addr, port, nServices);
-        if (addr.IsValid())
-            vaddr.push_back(addr);
-        ppAddr++;
-    }
-
-    return (vaddr.size() > 0);
-}
-
-// portDefault is in host order
-bool Lookup(const char *pszName, CAddress& addr, int nServices, bool fAllowLookup, int portDefault, bool fAllowPort)
-{
-    vector<CAddress> vaddr;
-    bool fRet = Lookup(pszName, vaddr, nServices, 1, fAllowLookup, portDefault, fAllowPort);
-    if (fRet)
-        addr = vaddr[0];
-    return fRet;
-}
-
-bool GetMyExternalIP2(const CAddress& addrConnect, const char* pszGet, const char* pszKeyword, unsigned int& ipRet)
+bool GetMyExternalIP2(const CService& addrConnect, const char* pszGet, const char* pszKeyword, CNetAddr& ipRet)
 {
     SOCKET hSocket;
     if (!ConnectSocket(addrConnect, hSocket))
@@ -328,11 +122,11 @@ bool GetMyExternalIP2(const CAddress& addrConnect, const char* pszGet, const cha
             strLine = strLine.substr(strspn(strLine.c_str(), " \t\n\r"));
             while (strLine.size() > 0 && isspace(strLine[strLine.size()-1]))
                 strLine.resize(strLine.size()-1);
-            CAddress addr(strLine,0,true);
+            CService addr(strLine,0,true);
             printf("GetMyExternalIP() received [%s] %s\n", strLine.c_str(), addr.ToString().c_str());
-            if (addr.ip == 0 || addr.ip == INADDR_NONE || !addr.IsRoutable())
+            if (!addr.IsValid() || !addr.IsRoutable())
                 return false;
-            ipRet = addr.ip;
+            ipRet.SetIP(addr);
             return true;
         }
     }
@@ -341,9 +135,9 @@ bool GetMyExternalIP2(const CAddress& addrConnect, const char* pszGet, const cha
 }
 
 // We now get our external IP from the IRC server first and only use this as a backup
-bool GetMyExternalIP(unsigned int& ipRet)
+bool GetMyExternalIP(CNetAddr& ipRet)
 {
-    CAddress addrConnect;
+    CService addrConnect;
     const char* pszGet;
     const char* pszKeyword;
 
@@ -359,11 +153,11 @@ bool GetMyExternalIP(unsigned int& ipRet)
         //  <?php echo $_SERVER["REMOTE_ADDR"]; ?>
         if (nHost == 1)
         {
-            addrConnect = CAddress("91.198.22.70",80); // checkip.dyndns.org
+            addrConnect = CService("91.198.22.70",80); // checkip.dyndns.org
 
             if (nLookup == 1)
             {
-                CAddress addrIP("checkip.dyndns.org", 80, true);
+                CService addrIP("checkip.dyndns.org", 80, true);
                 if (addrIP.IsValid())
                     addrConnect = addrIP;
             }
@@ -378,11 +172,11 @@ bool GetMyExternalIP(unsigned int& ipRet)
         }
         else if (nHost == 2)
         {
-            addrConnect = CAddress("74.208.43.192", 80); // www.showmyip.com
+            addrConnect = CService("74.208.43.192", 80); // www.showmyip.com
 
             if (nLookup == 1)
             {
-                CAddress addrIP("www.showmyip.com", 80, true);
+                CService addrIP("www.showmyip.com", 80, true);
                 if (addrIP.IsValid())
                     addrConnect = addrIP;
             }
@@ -417,7 +211,7 @@ void ThreadGetMyExternalIP(void* parg)
     }
 
     // Fallback in case IRC fails to get it
-    if (GetMyExternalIP(addrLocalHost.ip))
+    if (GetMyExternalIP(addrLocalHost))
     {
         printf("GetMyExternalIP() returned %s\n", addrLocalHost.ToStringIP().c_str());
         if (addrLocalHost.IsRoutable())
@@ -441,7 +235,7 @@ bool AddAddress(CAddress addr, int64 nTimePenalty, CAddrDB *pAddrDB)
 {
     if (!addr.IsRoutable())
         return false;
-    if (addr.ip == addrLocalHost.ip)
+    if ((CService)addr == (CService)addrLocalHost)
         return false;
     addr.nTime = max((int64)0, (int64)addr.nTime - nTimePenalty);
     bool fUpdated = false;
@@ -494,7 +288,7 @@ bool AddAddress(CAddress addr, int64 nTimePenalty, CAddrDB *pAddrDB)
     return fNew;
 }
 
-void AddressCurrentlyConnected(const CAddress& addr)
+void AddressCurrentlyConnected(const CService& addr)
 {
     CAddress *paddrFound = NULL;
 
@@ -624,23 +418,23 @@ void CNode::CancelSubscribe(unsigned int nChannel)
 
 
 
-CNode* FindNode(unsigned int ip)
+CNode* FindNode(const CNetAddr& ip)
 {
     CRITICAL_BLOCK(cs_vNodes)
     {
         BOOST_FOREACH(CNode* pnode, vNodes)
-            if (pnode->addr.ip == ip)
+            if ((CNetAddr)pnode->addr == ip)
                 return (pnode);
     }
     return NULL;
 }
 
-CNode* FindNode(CAddress addr)
+CNode* FindNode(const CService& addr)
 {
     CRITICAL_BLOCK(cs_vNodes)
     {
         BOOST_FOREACH(CNode* pnode, vNodes)
-            if (pnode->addr == addr)
+            if ((CService)pnode->addr == addr)
                 return (pnode);
     }
     return NULL;
@@ -648,11 +442,11 @@ CNode* FindNode(CAddress addr)
 
 CNode* ConnectNode(CAddress addrConnect, int64 nTimeout)
 {
-    if (addrConnect.ip == addrLocalHost.ip)
+    if ((CNetAddr)addrConnect == (CNetAddr)addrLocalHost)
         return NULL;
 
     // Look for an existing connection
-    CNode* pnode = FindNode(addrConnect.ip);
+    CNode* pnode = FindNode((CService)addrConnect);
     if (pnode)
     {
         if (nTimeout != 0)
@@ -735,8 +529,8 @@ void CNode::PushVersion()
 {
     /// when NTP implemented, change to just nTime = GetAdjustedTime()
     int64 nTime = (fInbound ? GetAdjustedTime() : GetTime());
-    CAddress addrYou = (fUseProxy ? CAddress("0.0.0.0") : addr);
-    CAddress addrMe = (fUseProxy ? CAddress("0.0.0.0") : addrLocalHost);
+    CAddress addrYou = (fUseProxy ? CAddress(CService("0.0.0.0",0)) : addr);
+    CAddress addrMe = (fUseProxy ? CAddress(CService("0.0.0.0",0)) : addrLocalHost);
     RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
     PushMessage("version", PROTOCOL_VERSION, nLocalServices, nTime, addrYou, addrMe,
                 nLocalHostNonce, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<string>()), nBestHeight);
@@ -746,7 +540,7 @@ void CNode::PushVersion()
 
 
 
-std::map<unsigned int, int64> CNode::setBanned;
+std::map<CNetAddr, int64> CNode::setBanned;
 CCriticalSection CNode::cs_setBanned;
 
 void CNode::ClearBanned()
@@ -754,12 +548,12 @@ void CNode::ClearBanned()
     setBanned.clear();
 }
 
-bool CNode::IsBanned(unsigned int ip)
+bool CNode::IsBanned(CNetAddr ip)
 {
     bool fResult = false;
     CRITICAL_BLOCK(cs_setBanned)
     {
-        std::map<unsigned int, int64>::iterator i = setBanned.find(ip);
+        std::map<CNetAddr, int64>::iterator i = setBanned.find(ip);
         if (i != setBanned.end())
         {
             int64 t = (*i).second;
@@ -783,8 +577,8 @@ bool CNode::Misbehaving(int howmuch)
     {
         int64 banTime = GetTime()+GetArg("-bantime", 60*60*24);  // Default 24-hour ban
         CRITICAL_BLOCK(cs_setBanned)
-            if (setBanned[addr.ip] < banTime)
-                setBanned[addr.ip] = banTime;
+            if (setBanned[addr] < banTime)
+                setBanned[addr] = banTime;
         CloseSocketDisconnect();
         printf("Disconnected %s for misbehavior (score=%d)\n", addr.ToString().c_str(), nMisbehavior);
         return true;
@@ -960,9 +754,11 @@ void ThreadSocketHandler2(void* parg)
             }
             else if (nInbound >= GetArg("-maxconnections", 125) - MAX_OUTBOUND_CONNECTIONS)
             {
-                closesocket(hSocket);
+                CRITICAL_BLOCK(cs_setservAddNodeAddresses)
+                    if (!setservAddNodeAddresses.count(addr))
+                        closesocket(hSocket);
             }
-            else if (CNode::IsBanned(addr.ip))
+            else if (CNode::IsBanned(addr))
             {
                 printf("connetion from %s dropped (banned)\n", addr.ToString().c_str());
                 closesocket(hSocket);
@@ -1148,7 +944,6 @@ void ThreadMapPort2(void* parg)
     char port[6];
     sprintf(port, "%d", GetListenPort());
 
-    const char * rootdescurl = 0;
     const char * multicastif = 0;
     const char * minissdpdpath = 0;
     struct UPNPDev * devlist = 0;
@@ -1170,17 +965,15 @@ void ThreadMapPort2(void* parg)
     r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr));
     if (r == 1)
     {
-        char intClient[16];
-        char intPort[6];
         string strDesc = "Bitcoin " + FormatFullVersion();
 #ifndef UPNPDISCOVER_SUCCESS
     /* miniupnpc 1.5 */
         r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
-                               port, port, lanaddr, strDesc.c_str(), "TCP", 0);
+                            port, port, lanaddr, strDesc.c_str(), "TCP", 0);
 #else
     /* miniupnpc 1.6 */
         r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
-                               port, port, lanaddr, strDesc.c_str(), "TCP", 0, "0");
+                            port, port, lanaddr, strDesc.c_str(), "TCP", 0, "0");
 #endif
 
         if(r!=UPNPCOMMAND_SUCCESS)
@@ -1277,15 +1070,16 @@ void ThreadDNSAddressSeed2(void* parg)
         printf("Loading addresses from DNS seeds (could take a while)\n");
 
         for (int seed_idx = 0; seed_idx < ARRAYLEN(strDNSSeed); seed_idx++) {
-            vector<CAddress> vaddr;
-            if (Lookup(strDNSSeed[seed_idx], vaddr, NODE_NETWORK, -1, true))
+            vector<CNetAddr> vaddr;
+            if (LookupHost(strDNSSeed[seed_idx], vaddr))
             {
                 CAddrDB addrDB;
                 addrDB.TxnBegin();
-                BOOST_FOREACH (CAddress& addr, vaddr)
+                BOOST_FOREACH (CNetAddr& ip, vaddr)
                 {
-                    if (addr.GetByte(3) != 127)
+                    if (ip.IsRoutable())
                     {
+                        CAddress addr(CService(ip, GetDefaultPort()), NODE_NETWORK);
                         addr.nTime = 0;
                         AddAddress(addr, 0, &addrDB);
                         found++;
@@ -1312,70 +1106,83 @@ void ThreadDNSAddressSeed2(void* parg)
 
 unsigned int pnSeed[] =
 {
-    0x6884ac63, 0x3ffecead, 0x2919b953, 0x0942fe50, 0x7a1d922e, 0xcdd6734a, 0x953a5bb6, 0x2c46922e,
-    0xe2a5f143, 0xaa39103a, 0xa06afa5c, 0x135ffd59, 0xe8e82863, 0xf61ef029, 0xf75f042e, 0x2b363532,
-    0x29b2df42, 0x16b1f64e, 0xd46e281b, 0x5280bf58, 0x60372229, 0x1be58e4f, 0xa8496f45, 0x1fb1a057,
-    0x756b3844, 0x3bb79445, 0x0b375518, 0xcccb0102, 0xb682bf2e, 0x46431c02, 0x3a81073a, 0xa3771f1f,
-    0x213a121f, 0x85dc2c1b, 0x56b4323b, 0xb34e8945, 0x3c40b33d, 0xfa276418, 0x1f818d29, 0xebe1e344,
-    0xf6160a18, 0xf4fa384a, 0x34b09558, 0xb882b543, 0xe3ce2253, 0x6abf56d8, 0xe91b1155, 0x688ee6ad,
-    0x2efc6058, 0x4792cd47, 0x0c32f757, 0x4c813a46, 0x8c93644a, 0x37507444, 0x813ad218, 0xdac06d4a,
-    0xe4c63e4b, 0x21a1ea3c, 0x8d88556f, 0x30e9173a, 0x041f681b, 0xdc77ba50, 0xc0072753, 0xceddd44f,
-    0x052d1743, 0xe3c77a4a, 0x13981c3a, 0x5685d918, 0x3c0e4e70, 0x3e56fb54, 0xb676ae0c, 0xac93c859,
-    0x22279f43, 0x975a4542, 0xe527f071, 0xea162f2e, 0x3c65a32e, 0x5be5713b, 0x961ec418, 0xb202922e,
-    0x5ef7be50, 0xce49f53e, 0x05803b47, 0x8463b055, 0x78576153, 0x3ec2ae3a, 0x4bbd7118, 0xafcee043,
-    0x56a3e8ba, 0x6174de4d, 0x8d01ba4b, 0xc9af564e, 0xdbc9c547, 0xa627474d, 0xdada9244, 0xd3b3083a,
-    0x523e071f, 0xd6b96f18, 0xbd527c46, 0xdf2bbb4d, 0xd37b4a4b, 0x3a6a2158, 0xc064b055, 0x18a8e055,
-    0xec4dae3b, 0x0540416c, 0x475b4fbe, 0x064803b2, 0x48e9f062, 0x2898524b, 0xd315ff43, 0xf786d247,
-    0xc7ea2f3e, 0xc087f043, 0xc163354b, 0x8250284d, 0xed300029, 0xbf36e05c, 0x8eb3ae4c, 0xe7aa623e,
-    0x7ced0274, 0xdd362c1b, 0x362b995a, 0xca26b629, 0x3fc41618, 0xb97b364e, 0xa05b8729, 0x0f5e3c43,
-    0xdf942618, 0x6aeb9b5b, 0xbf04762e, 0xfaaeb118, 0x87579958, 0x76520044, 0xc2660c5b, 0x628b201b,
-    0xf193932e, 0x1c0ad045, 0xff908346, 0x8da9d4da, 0xed201c1f, 0xa47a2b1b, 0x330007d4, 0x8ba1ed47,
-    0xb2f02d44, 0x7db62c1b, 0x781c454b, 0xc0300029, 0xb7062a45, 0x88b52e3a, 0x78dd6b63, 0x1cb9b718,
-    0x5d358e47, 0x59912c3b, 0x79607544, 0x5197f759, 0xc023be48, 0xd1013743, 0x0f354057, 0x8e3aac3b,
-    0x4114693e, 0x22316318, 0xe27dda50, 0x878eac3b, 0x4948a21f, 0x5db7f24c, 0x8ccb6157, 0x26a5de18,
-    0x0a11bd43, 0x27bb1e41, 0x60a7a951, 0x3e16b35e, 0x07888b53, 0x5648a853, 0x0149fe50, 0xd070a34f,
-    0x6454c96d, 0xd6e54758, 0xa96dc152, 0x65447861, 0xf6bdf95e, 0x10400202, 0x2c29d483, 0x18174732,
-    0x1d840618, 0x12e61818, 0x089d3f3c, 0x917e931f, 0xd1b0c90e, 0x25bd3c42, 0xeb05775b, 0x7d550c59,
-    0x6cfacb01, 0xe4224444, 0xa41dd943, 0x0f5aa643, 0x5e33731b, 0x81036d50, 0x6f46a0d1, 0x7731be43,
-    0x14840e18, 0xf1e8d059, 0x661d2b1f, 0x40a3201b, 0x9407b843, 0xedf0254d, 0x7bd1a5bc, 0x073dbe51,
-    0xe864a97b, 0x2efd947b, 0xb9ca0e45, 0x4e2113ad, 0xcc305731, 0xd39ca63c, 0x733df918, 0xda172b1f,
-    0xaa03b34d, 0x7230fd4d, 0xf1ce6e3a, 0x2e9fab43, 0xa4010750, 0xa928bd18, 0x6809be42, 0xb19de348,
-    0xff956270, 0x0d795f51, 0xd2dec247, 0x6df5774b, 0xbac11f79, 0xdfb05c75, 0x887683d8, 0xa1e83632,
-    0x2c0f7671, 0x28bcb65d, 0xac2a7545, 0x3eebfc60, 0x304ad7c4, 0xa215a462, 0xc86f0f58, 0xcfb92ebe,
-    0x5e23ed82, 0xf506184b, 0xec0f19b7, 0x060c59ad, 0x86ee3174, 0x85380774, 0xa199a562, 0x02b507ae,
-    0x33eb2163, 0xf2112b1f, 0xb702ba50, 0x131b9618, 0x90ccd04a, 0x08f3273b, 0xecb61718, 0x64b8b44d,
-    0x182bf4dc, 0xc7b68286, 0x6e318d5f, 0xfdb03654, 0xb3272e54, 0xe014ad4b, 0x274e4a31, 0x7806375c,
-    0xbc34a748, 0x1b5ad94a, 0x6b54d10e, 0x73e2ae6e, 0x5529d483, 0x8455a76d, 0x99c13f47, 0x1d811741,
-    0xa9782a78, 0x0b00464d, 0x7266ea50, 0x532dab46, 0x33e1413e, 0x780d0c18, 0x0fb0854e, 0x03370155,
-    0x2693042e, 0xfa3d824a, 0x2bb1681b, 0x37ea2a18, 0x7fb8414b, 0x32e0713b, 0xacf38d3f, 0xa282716f,
-    0xb1a09d7b, 0xa04b764b, 0x83c94d18, 0x05ee4c6d, 0x0e795f51, 0x46984352, 0xf80fc247, 0x3fccb946,
-    0xd7ae244b, 0x0a8e0a4c, 0x57b141bc, 0x3647bed1, 0x1431b052, 0x803a8bbb, 0xfc69056b, 0xf5991862,
-    0x14963b2e, 0xd35d5dda, 0xc6c73574, 0xc8f1405b, 0x0ca4224d, 0xecd36071, 0xa9461754, 0xe7a0ed72,
-    0x559e8346, 0x1c9beec1, 0xc786ea4a, 0x9561b44d, 0x9788074d, 0x1a69934f, 0x23c5614c, 0x07c79d4b,
-    0xc7ee52db, 0xc72df351, 0xcb135e44, 0xa0988346, 0xc211fc4c, 0x87dec34b, 0x1381074d, 0x04a65cb7,
-    0x4409083a, 0x4a407a4c, 0x92b8d37d, 0xacf50b4d, 0xa58aa5bc, 0x448f801f, 0x9c83762e, 0x6fd5734a,
-    0xfe2d454b, 0x84144c55, 0x05190e4c, 0xb2151448, 0x63867a3e, 0x16099018, 0x9c010d3c, 0x962d8f3d,
-    0xd51ee453, 0x9d86801f, 0x68e87b47, 0x6bf7bb73, 0x5fc7910e, 0x10d90118, 0x3db04442, 0x729d3e4b,
-    0xc397d842, 0x57bb15ad, 0x72f31f4e, 0xc9380043, 0x2bb24e18, 0xd9b8ab50, 0xb786801f, 0xf4dc4847,
-    0x85f4bb51, 0x4435995b, 0x5ba07e40, 0x2c57392e, 0x3628124b, 0x9839b64b, 0x6fe8b24d, 0xaddce847,
-    0x75260e45, 0x0c572a43, 0xfea21902, 0xb9f9742e, 0x5a70d443, 0x8fc5910e, 0x868d4744, 0x56245e02,
-    0xd7eb5f02, 0x35c12c1b, 0x4373034b, 0x8786554c, 0xa6facf18, 0x4b11a31f, 0x3570664e, 0x5a64bc42,
-    0x0b03983f, 0x8f457e4c, 0x0fd874c3, 0xb6cf31b2, 0x2bbc2d4e, 0x146ca5b2, 0x9d00b150, 0x048a4153,
-    0xca4dcd43, 0xc1607cca, 0x8234cf57, 0x9c7daead, 0x3dc07658, 0xea5c6e4c, 0xf1a0084e, 0x16d2ee53,
-    0x1b849418, 0xfe913a47, 0x1e988f62, 0x208b644c, 0xc55ee980, 0xbdbce747, 0xf59a384e, 0x0f56091b,
-    0x7417b745, 0x0c37344e, 0x2c62ab47, 0xf8533a4d, 0x8030084d, 0x76b93c4b, 0xda6ea0ad, 0x3c54f618,
-    0x63b0de1f, 0x7370d858, 0x1a70bb4c, 0xdda63b2e, 0x60b2ba50, 0x1ba7d048, 0xbe1b2c1b, 0xabea5747,
-    0x29ad2e4d, 0xe8cd7642, 0x66c80e18, 0x138bf34a, 0xc6145e44, 0x2586794c, 0x07bc5478, 0x0da0b14d,
-    0x8f95354e, 0x9eb11c62, 0xa1545e46, 0x2e7a2602, 0x408c9c3d, 0x59065d55, 0xf51d1a4c, 0x3bbc6a4e,
-    0xc71b2a2e, 0xcdaaa545, 0x17d659d0, 0x5202e7ad, 0xf1b68445, 0x93375961, 0xbd88a043, 0x066ad655,
-    0x890f6318, 0x7b7dca47, 0x99bdd662, 0x3bb4fc53, 0x1231efdc, 0xc0a99444, 0x96bbea47, 0x61ed8748,
-    0x27dfa73b, 0x8d4d1754, 0x3460042e, 0x551f0c4c, 0x8d0e0718, 0x162ddc53, 0x53231718, 0x1ecd65d0,
-    0x944d28bc, 0x3b79d058, 0xaff97fbc, 0x4860006c, 0xc101c90e, 0xace41743, 0xa5975d4c, 0x5cc2703e,
-    0xb55a4450, 0x02d18840, 0xee2765ae, 0xd6012fd5, 0x24c94d7d, 0x8c6eec47, 0x7520ba5d, 0x9e15e460,
-    0x8510b04c, 0x75ec3847, 0x1dfa6661, 0xe172b3ad, 0x5744c90e, 0x52a0a152, 0x8d6fad18, 0x67b74b6d,
-    0x93a089b2, 0x0f3ac5d5, 0xe5de1855, 0x43d25747, 0x4bad804a, 0x55b408d8, 0x60a36441, 0xf553e860,
-    0xdb2fa2c8, 0x03152b32, 0xdd27a7d5, 0x3116a8b8, 0x0a1d708c, 0xeee2f13c, 0x6acf436f, 0xce6eb4ca,
-    0x101cd3d9, 0x1c48a6b8, 0xe57d6f44, 0x93dcf562,
+    0x959bd347, 0xf8de42b2, 0x73bc0518, 0xea6edc50, 0x21b00a4d, 0xc725b43d, 0xd665464d, 0x1a2a770e,
+    0x27c93946, 0x65b2fa46, 0xb80ae255, 0x66b3b446, 0xb1877a3e, 0x6ee89e3e, 0xc3175b40, 0x2a01a83c,
+    0x95b1363a, 0xa079ad3d, 0xe6ca801f, 0x027f4f4a, 0x34f7f03a, 0xf790f04a, 0x16ca801f, 0x2f4d5e40,
+    0x3a4d5e40, 0xc43a322e, 0xc8159753, 0x14d4724c, 0x7919a118, 0xe0bdb34e, 0x68a16b2e, 0xff64b44d,
+    0x6099115b, 0x9b57b05b, 0x7bd1b4ad, 0xdf95944f, 0x29d2b73d, 0xafa8db79, 0xe247ba41, 0x24078348,
+    0xf722f03c, 0x33567ebc, 0xace64ed4, 0x984d3932, 0xb5f34e55, 0x27b7024d, 0x94579247, 0x8894042e,
+    0x9357d34c, 0x1063c24b, 0xcaa228b1, 0xa3c5a8b2, 0x5dc64857, 0xa2c23643, 0xa8369a54, 0x31203077,
+    0x00707c5c, 0x09fc0b3a, 0x272e9e2e, 0xf80f043e, 0x9449ca3e, 0x5512c33e, 0xd106b555, 0xe8024157,
+    0xe288ec29, 0xc79c5461, 0xafb63932, 0xdb02ab4b, 0x0e512777, 0x8a145a4c, 0xb201ff4f, 0x5e09314b,
+    0xcd9bfbcd, 0x1c023765, 0x4394e75c, 0xa728bd4d, 0x65331552, 0xa98420b1, 0x89ecf559, 0x6e80801f,
+    0xf404f118, 0xefd62b51, 0x05918346, 0x9b186d5f, 0xacabab46, 0xf912e255, 0xc188ea62, 0xcc55734e,
+    0xc668064d, 0xd77a4558, 0x46201c55, 0xf17dfc80, 0xf7142f2e, 0x87bfb718, 0x8aa54fb2, 0xc451d518,
+    0xc4ae8831, 0x8dd44d55, 0x5bbd206c, 0x64536b5d, 0x5c667e60, 0x3b064242, 0xfe963a42, 0xa28e6dc8,
+    0xe8a9604a, 0xc989464e, 0xd124a659, 0x50065140, 0xa44dfe5e, 0x1079e655, 0x3fb986d5, 0x47895b18,
+    0x7d3ce4ad, 0x4561ba50, 0x296eec62, 0x255b41ad, 0xaed35ec9, 0x55556f12, 0xc7d3154d, 0x3297b65d,
+    0x8930121f, 0xabf42e4e, 0x4a29e044, 0x1212685d, 0x676c1e40, 0xce009744, 0x383a8948, 0xa2dbd0ad,
+    0xecc2564d, 0x07dbc252, 0x887ee24b, 0x5171644c, 0x6bb798c1, 0x847f495d, 0x4cbb7145, 0x3bb81c32,
+    0x45eb262e, 0xc8015a4e, 0x250a361b, 0xf694f946, 0xd64a183e, 0xd4f1dd59, 0x8f20ffd4, 0x51d9e55c,
+    0x09521763, 0x5e02002e, 0x32c8074d, 0xe685762e, 0x8290b0bc, 0x762a922e, 0xfc5ee754, 0x83a24829,
+    0x775b224d, 0x6295bb4d, 0x38ec0555, 0xbffbba50, 0xe5560260, 0x86b16a7c, 0xd372234e, 0x49a3c24b,
+    0x2f6a171f, 0x4d75ed60, 0xae94115b, 0xcb543744, 0x63080c59, 0x3f9c724c, 0xc977ce18, 0x532efb18,
+    0x69dc3b2e, 0x5f94d929, 0x1732bb4d, 0x9c814b4d, 0xe6b3762e, 0xc024f662, 0x8face35b, 0x6b5b044d,
+    0x798c7b57, 0x79a6b44c, 0x067d3057, 0xf9e94e5f, 0x91cbe15b, 0x71405eb2, 0x2662234e, 0xcbcc4a6d,
+    0xbf69d54b, 0xa79b4e55, 0xec6d3e51, 0x7c0b3c02, 0x60f83653, 0x24c1e15c, 0x1110b62e, 0x10350f59,
+    0xa56f1d55, 0x3509e7a9, 0xeb128354, 0x14268e2e, 0x934e28bc, 0x8e32692e, 0x8331a21f, 0x3e633932,
+    0xc812b12e, 0xc684bf2e, 0x80112d2e, 0xe0ddc96c, 0xc630ca4a, 0x5c09b3b2, 0x0b580518, 0xc8e9d54b,
+    0xd169aa43, 0x17d0d655, 0x1d029963, 0x7ff87559, 0xcb701f1f, 0x6fa3e85d, 0xe45e9a54, 0xf05d1802,
+    0x44d03b2e, 0x837b692e, 0xccd4354e, 0x3d6da13c, 0x3423084d, 0xf707c34a, 0x55f6db3a, 0xad26e442,
+    0x6233a21f, 0x09e80e59, 0x8caeb54d, 0xbe870941, 0xb407d20e, 0x20b51018, 0x56fb152e, 0x460d2a4e,
+    0xbb9a2946, 0x560eb12e, 0xed83dd29, 0xd6724f53, 0xa50aafb8, 0x451346d9, 0x88348e2e, 0x7312fead,
+    0x8ecaf96f, 0x1bda4e5f, 0xf1671e40, 0x3c8c3e3b, 0x4716324d, 0xdde24ede, 0xf98cd17d, 0xa91d4644,
+    0x28124eb2, 0x147d5129, 0xd022042e, 0x61733d3b, 0xad0d5e02, 0x8ce2932e, 0xe5c18502, 0x549c1e32,
+    0x9685801f, 0x86e217ad, 0xd948214b, 0x4110f462, 0x3a2e894e, 0xbd35492e, 0x87e0d558, 0x64b8ef7d,
+    0x7c3eb962, 0x72a84b3e, 0x7cd667c9, 0x28370a2e, 0x4bc60e7b, 0x6fc1ec60, 0x14a6983f, 0x86739a4b,
+    0x46954e5f, 0x32e2e15c, 0x2e9326cf, 0xe5801c5e, 0x379607b2, 0x32151145, 0xf0e39744, 0xacb54c55,
+    0xa37dfb60, 0x83b55cc9, 0x388f7ca5, 0x15034f5f, 0x3e94965b, 0x68e0ffad, 0x35280f59, 0x8fe190cf,
+    0x7c6ba5b2, 0xa5e9db43, 0x4ee1fc60, 0xd9d94e5f, 0x04040677, 0x0ea9b35e, 0x5961f14f, 0x67fda063,
+    0xa48a5a31, 0xc6524e55, 0x283d325e, 0x3f37515f, 0x96b94b3e, 0xacce620e, 0x6481cc5b, 0xa4a06d4b,
+    0x9e95d2d9, 0xe40c03d5, 0xc2f4514b, 0xb79aad44, 0xf64be843, 0xb2064070, 0xfca00455, 0x429dfa4e,
+    0x2323f173, 0xeda4185e, 0xabd5227d, 0x9efd4d58, 0xb1104758, 0x4811e955, 0xbd9ab355, 0xe921f44b,
+    0x9f166dce, 0x09e279b2, 0xe0c9ac7b, 0x7901a5ad, 0xa145d4b0, 0x79104671, 0xec31e35a, 0x4fe0b555,
+    0xc7d9cbad, 0xad057f55, 0xe94cc759, 0x7fe0b043, 0xe4529f2e, 0x0d4dd4b2, 0x9f11a54d, 0x031e2e4e,
+    0xe6014f5f, 0x11d1ca6c, 0x26bd7f61, 0xeb86854f, 0x4d347b57, 0x116bbe2e, 0xdba7234e, 0x7bcbfd2e,
+    0x174dd4b2, 0x6686762e, 0xb089ba50, 0xc6258246, 0x087e767b, 0xc4a8cb4a, 0x595dba50, 0x7f0ae502,
+    0x7b1dbd5a, 0xa0603492, 0x57d1af4b, 0x9e21ffd4, 0x6393064d, 0x7407376e, 0xe484762e, 0x122a4e53,
+    0x4a37aa43, 0x3888a6be, 0xee77864e, 0x039c8dd5, 0x688d89af, 0x0e988f62, 0x08218246, 0xfc2f8246,
+    0xd1d97040, 0xd64cd4b2, 0x5ae4a6b8, 0x7d0de9bc, 0x8d304d61, 0x06c5c672, 0xa4c8bd4d, 0xe0fd373b,
+    0x575ebe4d, 0x72d26277, 0x55570f55, 0x77b154d9, 0xe214293a, 0xfc740f4b, 0xfe3f6a57, 0xa9c55f02,
+    0xae4054db, 0x2394d918, 0xb511b24a, 0xb8741ab2, 0x0758e65e, 0xc7b5795b, 0xb0a30a4c, 0xaf7f170c,
+    0xf3b4762e, 0x8179576d, 0x738a1581, 0x4b95b64c, 0x9829b618, 0x1bea932e, 0x7bdeaa4b, 0xcb5e0281,
+    0x65618f54, 0x0658474b, 0x27066acf, 0x40556d65, 0x7d204d53, 0xf28bc244, 0xdce23455, 0xadc0ff54,
+    0x3863c948, 0xcee34e5f, 0xdeb85e02, 0x2ed17a61, 0x6a7b094d, 0x7f0cfc40, 0x59603f54, 0x3220afbc,
+    0xb5dfd962, 0x125d21c0, 0x13f8d243, 0xacfefb4e, 0x86c2c147, 0x3d8bbd59, 0xbd02a21f, 0x2593042e,
+    0xc6a17a7c, 0x28925861, 0xb487ed44, 0xb5f4fd6d, 0x90c28a45, 0x5a14f74d, 0x43d71b4c, 0x728ebb5d,
+    0x885bf950, 0x08134dd0, 0x38ec046e, 0xc575684b, 0x50082d2e, 0xa2f47757, 0x270f86ae, 0xf3ff6462,
+    0x10ed3f4e, 0x4b58d462, 0xe01ce23e, 0x8c5b092e, 0x63e52f4e, 0x22c1e85d, 0xa908f54e, 0x8591624f,
+    0x2c0fb94e, 0xa280ba3c, 0xb6f41b4c, 0x24f9aa47, 0x27201647, 0x3a3ea6dc, 0xa14fc3be, 0x3c34bdd5,
+    0x5b8d4f5b, 0xaadeaf4b, 0xc71cab50, 0x15697a4c, 0x9a1a734c, 0x2a037d81, 0x2590bd59, 0x48ec2741,
+    0x53489c5b, 0x7f00314b, 0x2170d362, 0xf2e92542, 0x42c10b44, 0x98f0f118, 0x883a3456, 0x099a932e,
+    0xea38f7bc, 0x644e9247, 0xbb61b62e, 0x30e0863d, 0x5f51be54, 0x207215c7, 0x5f306c45, 0xaa7f3932,
+    0x98da7d45, 0x4e339b59, 0x2e411581, 0xa808f618, 0xad2c0c59, 0x54476741, 0x09e99fd1, 0x5db8f752,
+    0xc16df8bd, 0x1dd4b44f, 0x106edf2e, 0x9e15c180, 0x2ad6b56f, 0x633a5332, 0xff33787c, 0x077cb545,
+    0x6610be6d, 0x75aad2c4, 0x72fb4d5b, 0xe81e0f59, 0x576f6332, 0x47333373, 0x351ed783, 0x2d90fb50,
+    0x8d5e0f6c, 0x5b27a552, 0xdb293ebb, 0xe55ef950, 0x4b133ad8, 0x75df975a, 0x7b6a8740, 0xa899464b,
+    0xfab15161, 0x10f8b64d, 0xd055ea4d, 0xee8e146b, 0x4b14afb8, 0x4bc1c44a, 0x9b961dcc, 0xd111ff43,
+    0xfca0b745, 0xc800e412, 0x0afad9d1, 0xf751c350, 0xf9f0cccf, 0xa290a545, 0x8ef13763, 0x7ec70d59,
+    0x2b066acf, 0x65496c45, 0xade02c1b, 0xae6eb077, 0x92c1e65b, 0xc064e6a9, 0xc649e56d, 0x5287a243,
+    0x36de4f5b, 0x5b1df6ad, 0x65c39a59, 0xdba805b2, 0x20067aa8, 0x6457e56d, 0x3cee26cf, 0xfd3ff26d,
+    0x04f86d4a, 0x06b8e048, 0xa93bcd5c, 0x91135852, 0xbe90a643, 0x8fa0094d, 0x06d8215f, 0x2677094d,
+    0xd735685c, 0x164a00c9, 0x5209ac5f, 0xa9564c5c, 0x3b504f5f, 0xcc826bd0, 0x4615042e, 0x5fe13b4a,
+    0x8c81b86d, 0x879ab68c, 0x1de564b8, 0x434487d8, 0x2dcb1b63, 0x82ab524a, 0xb0676abb, 0xa13d9c62,
+    0xdbb5b86d, 0x5b7f4b59, 0xaddfb44d, 0xad773532, 0x3997054c, 0x72cebd89, 0xb194544c, 0xc5b8046e,
+    0x6e1adeb2, 0xaa5abb51, 0xefb54b44, 0x15efc54f, 0xe9f1bc4d, 0x5f401b6c, 0x97f018ad, 0xc82f9252,
+    0x2cdc762e, 0x8e52e56d, 0x1827175e, 0x9b7d7d80, 0xb2ad6845, 0x51065140, 0x71180a18, 0x5b27006c,
+    0x0621e255, 0x721cbe58, 0x670c0cb8, 0xf8bd715d, 0xe0bdc5d9, 0xed843501, 0x4b84554d, 0x7f1a18bc,
+    0x53bcaf47, 0x5729d35f, 0xf0dda246, 0x22382bd0, 0x4d641fb0, 0x316afcde, 0x50a22f1f, 0x73608046,
+    0xc461d84a, 0xb2dbe247,
 };
 
 
@@ -1410,7 +1217,7 @@ void ThreadOpenConnections2(void* parg)
         {
             BOOST_FOREACH(string strAddr, mapMultiArgs["-connect"])
             {
-                CAddress addr(strAddr, fAllowDNS);
+                CAddress addr(CService(strAddr, GetDefaultPort(), fAllowDNS));
                 if (addr.IsValid())
                     OpenNetworkConnection(addr);
                 for (int i = 0; i < 10 && i < nLoop; i++)
@@ -1423,22 +1230,6 @@ void ThreadOpenConnections2(void* parg)
         }
     }
 
-    // Connect to manually added nodes first
-    if (mapArgs.count("-addnode"))
-    {
-        BOOST_FOREACH(string strAddr, mapMultiArgs["-addnode"])
-        {
-            CAddress addr(strAddr, fAllowDNS);
-            if (addr.IsValid())
-            {
-                OpenNetworkConnection(addr);
-                Sleep(500);
-                if (fShutdown)
-                    return;
-            }
-        }
-    }
-
     // Initiate network connections
     int64 nStart = GetTime();
     loop
@@ -1470,8 +1261,8 @@ void ThreadOpenConnections2(void* parg)
         CRITICAL_BLOCK(cs_mapAddresses)
         {
             // Add seed nodes if IRC isn't working
-            bool fTOR = (fUseProxy && addrProxy.port == htons(9050));
-            if (mapAddresses.empty() && (GetTime() - nStart > 60 || fUseProxy) && !fTestNet)
+            bool fTOR = (fUseProxy && addrProxy.GetPort() == 9050);
+            if (mapAddresses.empty() && (GetTime() - nStart > 60 || fTOR) && !fTestNet)
                 fAddSeeds = true;
         }
 
@@ -1484,8 +1275,9 @@ void ThreadOpenConnections2(void* parg)
                 // Seed nodes are given a random 'last seen time' of between one and two
                 // weeks ago.
                 const int64 nOneWeek = 7*24*60*60;
-                CAddress addr;
-                addr.ip = pnSeed[i];
+                struct in_addr ip;
+                memcpy(&ip, &pnSeed[i], sizeof(ip));
+                CAddress addr(CService(ip, GetDefaultPort()));
                 addr.nTime = GetTime()-GetRand(nOneWeek)-nOneWeek;
                 AddAddress(addr);
             }
@@ -1499,10 +1291,10 @@ void ThreadOpenConnections2(void* parg)
 
         // Only connect to one address per a.b.?.? range.
         // Do this here so we don't have to critsect vNodes inside mapAddresses critsect.
-        set<unsigned int> setConnected;
+        set<vector<unsigned char> > setConnected;
         CRITICAL_BLOCK(cs_vNodes)
             BOOST_FOREACH(CNode* pnode, vNodes)
-                setConnected.insert(pnode->addr.ip & 0x0000ffff);
+                setConnected.insert(pnode->addr.GetGroup());
 
         int64 nANow = GetAdjustedTime();
 
@@ -1511,14 +1303,14 @@ void ThreadOpenConnections2(void* parg)
             BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
             {
                 const CAddress& addr = item.second;
-                if (!addr.IsIPv4() || !addr.IsValid() || setConnected.count(addr.ip & 0x0000ffff))
+                if (!addr.IsIPv4() || !addr.IsValid() || setConnected.count(addr.GetGroup()))
                     continue;
                 int64 nSinceLastSeen = nANow - addr.nTime;
                 int64 nSinceLastTry = nANow - addr.nLastTry;
 
                 // Randomize the order in a deterministic way, putting the standard port first
-                int64 nRandomizer = (uint64)(nStart * 4951 + addr.nLastTry * 9567851 + addr.ip * 7789) % (2 * 60 * 60);
-                if (addr.port != htons(GetDefaultPort()))
+                int64 nRandomizer = (uint64)(nStart * 4951 + addr.nLastTry * 9567851 + addr.GetHash()) % (2 * 60 * 60);
+                if (addr.GetPort() != GetDefaultPort())
                     nRandomizer += 2 * 60 * 60;
 
                 // Last seen  Base retry frequency
@@ -1566,6 +1358,76 @@ void ThreadOpenConnections2(void* parg)
     }
 }
 
+void ThreadOpenAddedConnections(void* parg)
+{
+    IMPLEMENT_RANDOMIZE_STACK(ThreadOpenAddedConnections(parg));
+    try
+    {
+        vnThreadsRunning[7]++;
+        ThreadOpenAddedConnections2(parg);
+        vnThreadsRunning[7]--;
+    }
+    catch (std::exception& e) {
+        vnThreadsRunning[7]--;
+        PrintException(&e, "ThreadOpenAddedConnections()");
+    } catch (...) {
+        vnThreadsRunning[7]--;
+        PrintException(NULL, "ThreadOpenAddedConnections()");
+    }
+    printf("ThreadOpenAddedConnections exiting\n");
+}
+
+void ThreadOpenAddedConnections2(void* parg)
+{
+    printf("ThreadOpenAddedConnections started\n");
+
+    if (mapArgs.count("-addnode") == 0)
+        return;
+
+    vector<vector<CService> > vservAddressesToAdd(0);
+    BOOST_FOREACH(string& strAddNode, mapMultiArgs["-addnode"])
+    {
+        vector<CService> vservNode(0);
+        if(Lookup(strAddNode.c_str(), vservNode, GetDefaultPort(), fAllowDNS, 0))
+        {
+            vservAddressesToAdd.push_back(vservNode);
+            CRITICAL_BLOCK(cs_setservAddNodeAddresses)
+                BOOST_FOREACH(CService& serv, vservNode)
+                    setservAddNodeAddresses.insert(serv);
+        }
+    }
+    loop
+    {
+        vector<vector<CService> > vservConnectAddresses = vservAddressesToAdd;
+        // Attempt to connect to each IP for each addnode entry until at least one is successful per addnode entry
+        // (keeping in mind that addnode entries can have many IPs if fAllowDNS)
+        CRITICAL_BLOCK(cs_vNodes)
+            BOOST_FOREACH(CNode* pnode, vNodes)
+                for (vector<vector<CService> >::iterator it = vservConnectAddresses.begin(); it != vservConnectAddresses.end(); it++)
+                    BOOST_FOREACH(CService& addrNode, *(it))
+                        if (pnode->addr == addrNode)
+                        {
+                            it = vservConnectAddresses.erase(it);
+                            it--;
+                            break;
+                        }
+        BOOST_FOREACH(vector<CService>& vserv, vservConnectAddresses)
+        {
+            OpenNetworkConnection(CAddress(*(vserv.begin())));
+            Sleep(500);
+            if (fShutdown)
+                return;
+        }
+        if (fShutdown)
+            return;
+        vnThreadsRunning[7]--;
+        Sleep(120000); // Retry every 2 minutes
+        vnThreadsRunning[7]++;
+        if (fShutdown)
+            return;
+    }
+}
+
 bool OpenNetworkConnection(const CAddress& addrConnect)
 {
     //
@@ -1573,8 +1435,8 @@ bool OpenNetworkConnection(const CAddress& addrConnect)
     //
     if (fShutdown)
         return false;
-    if (addrConnect.ip == addrLocalHost.ip || !addrConnect.IsIPv4() ||
-        FindNode(addrConnect.ip) || CNode::IsBanned(addrConnect.ip))
+    if ((CNetAddr)addrConnect == (CNetAddr)addrLocalHost || !addrConnect.IsIPv4() ||
+        FindNode((CNetAddr)addrConnect) || CNode::IsBanned(addrConnect))
         return false;
 
     vnThreadsRunning[1]--;
@@ -1676,7 +1538,7 @@ bool BindListenPort(string& strError)
 {
     strError = "";
     int nOne = 1;
-    addrLocalHost.port = htons(GetListenPort());
+    addrLocalHost.SetPort(GetListenPort());
 
 #ifdef WIN32
     // Initialize Windows Sockets
@@ -1755,19 +1617,19 @@ bool BindListenPort(string& strError)
 void StartNode(void* parg)
 {
     if (pnodeLocalHost == NULL)
-        pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress("127.0.0.1", 0, false, nLocalServices));
+        pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress(CService("127.0.0.1", 0), nLocalServices));
 
 #ifdef WIN32
     // Get local host ip
     char pszHostName[1000] = "";
     if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR)
     {
-        vector<CAddress> vaddr;
-        if (Lookup(pszHostName, vaddr, nLocalServices, -1, true))
-            BOOST_FOREACH (const CAddress &addr, vaddr)
-                if (addr.GetByte(3) != 127)
+        vector<CNetAddr> vaddr;
+        if (LookupHost(pszHostName, vaddr))
+            BOOST_FOREACH (const CNetAddr &addr, vaddr)
+                if (!addr.IsLocal())
                 {
-                    addrLocalHost = addr;
+                    addrLocalHost.SetIP(addr);
                     break;
                 }
     }
@@ -1790,8 +1652,8 @@ void StartNode(void* parg)
                     printf("ipv4 %s: %s\n", ifa->ifa_name, pszIP);
 
                 // Take the first IP that isn't loopback 127.x.x.x
-                CAddress addr(*(unsigned int*)&s4->sin_addr, GetListenPort(), nLocalServices);
-                if (addr.IsValid() && addr.GetByte(3) != 127)
+                CAddress addr(CService(s4->sin_addr, GetListenPort()), nLocalServices);
+                if (addr.IsValid() && !addr.IsLocal())
                 {
                     addrLocalHost = addr;
                     break;
@@ -1812,7 +1674,7 @@ void StartNode(void* parg)
     if (fUseProxy || mapArgs.count("-connect") || fNoListen)
     {
         // Proxies can't take incoming connections
-        addrLocalHost.ip = CAddress("0.0.0.0").ip;
+        addrLocalHost.SetIP(CNetAddr("0.0.0.0"));
         printf("addrLocalHost = %s\n", addrLocalHost.ToString().c_str());
     }
     else
@@ -1842,6 +1704,10 @@ void StartNode(void* parg)
     if (!CreateThread(ThreadSocketHandler, NULL))
         printf("Error: CreateThread(ThreadSocketHandler) failed\n");
 
+    // Initiate outbound connections from -addnode
+    if (!CreateThread(ThreadOpenAddedConnections, NULL))
+        printf("Error: CreateThread(ThreadOpenAddedConnections) failed\n");
+
     // Initiate outbound connections
     if (!CreateThread(ThreadOpenConnections, NULL))
         printf("Error: CreateThread(ThreadOpenConnections) failed\n");
@@ -1861,9 +1727,7 @@ bool StopNode()
     nTransactionsUpdated++;
     int64 nStart = GetTime();
     while (vnThreadsRunning[0] > 0 || vnThreadsRunning[2] > 0 || vnThreadsRunning[3] > 0 || vnThreadsRunning[4] > 0
-#ifdef USE_UPNP
-        || vnThreadsRunning[5] > 0
-#endif
+        || (fHaveUPnP && vnThreadsRunning[5] > 0) || vnThreadsRunning[6] > 0 || vnThreadsRunning[7] > 0
     )
     {
         if (GetTime() - nStart > 20)
@@ -1877,6 +1741,7 @@ bool StopNode()
     if (vnThreadsRunning[4] > 0) printf("ThreadRPCServer still running\n");
     if (fHaveUPnP && vnThreadsRunning[5] > 0) printf("ThreadMapPort still running\n");
     if (vnThreadsRunning[6] > 0) printf("ThreadDNSAddressSeed still running\n");
+    if (vnThreadsRunning[7] > 0) printf("ThreadOpenAddedConnections still running\n");
     while (vnThreadsRunning[2] > 0 || vnThreadsRunning[4] > 0)
         Sleep(20);
     Sleep(50);
index c2637dc..9f58d1e 100644 (file)
--- a/src/net.h
+++ b/src/net.h
@@ -14,6 +14,7 @@
 #include <arpa/inet.h>
 #endif
 
+#include "netbase.h"
 #include "protocol.h"
 
 class CAddrDB;
@@ -21,7 +22,6 @@ class CRequestTracker;
 class CNode;
 class CBlockIndex;
 extern int nBestHeight;
-extern int nConnectTimeout;
 
 
 
@@ -29,13 +29,11 @@ inline unsigned int ReceiveBufferSize() { return 1000*GetArg("-maxreceivebuffer"
 inline unsigned int SendBufferSize() { return 1000*GetArg("-maxsendbuffer", 10*1000); }
 static const unsigned int PUBLISH_HOPS = 5;
 
-bool ConnectSocket(const CAddress& addrConnect, SOCKET& hSocketRet, int nTimeout=nConnectTimeout);
-bool Lookup(const char *pszName, std::vector<CAddress>& vaddr, int nServices, int nMaxSolutions, bool fAllowLookup = false, int portDefault = 0, bool fAllowPort = false);
-bool Lookup(const char *pszName, CAddress& addr, int nServices, bool fAllowLookup = false, int portDefault = 0, bool fAllowPort = false);
-bool GetMyExternalIP(unsigned int& ipRet);
+bool GetMyExternalIP(CNetAddr& ipRet);
 bool AddAddress(CAddress addr, int64 nTimePenalty=0, CAddrDB *pAddrDB=NULL);
-void AddressCurrentlyConnected(const CAddress& addr);
-CNode* FindNode(unsigned int ip);
+void AddressCurrentlyConnected(const CService& addr);
+CNode* FindNode(const CNetAddr& ip);
+CNode* FindNode(const CService& ip);
 CNode* ConnectNode(CAddress addrConnect, int64 nTimeout=0);
 void AbandonRequests(void (*fn)(void*, CDataStream&), void* param1);
 bool AnySubscribed(unsigned int nChannel);
@@ -88,9 +86,6 @@ extern std::deque<std::pair<int64, CInv> > vRelayExpiration;
 extern CCriticalSection cs_mapRelay;
 extern std::map<CInv, int64> mapAlreadyAskedFor;
 
-// Settings
-extern int fUseProxy;
-extern CAddress addrProxy;
 
 
 
@@ -126,7 +121,7 @@ protected:
 
     // Denial-of-service detection/prevention
     // Key is ip address, value is banned-until-time
-    static std::map<unsigned int, int64> setBanned;
+    static std::map<CNetAddr, int64> setBanned;
     static CCriticalSection cs_setBanned;
     int nMisbehavior;
 
@@ -271,7 +266,9 @@ public:
         // Make sure not to reuse time indexes to keep things in the same order
         int64 nNow = (GetTime() - 1) * 1000000;
         static int64 nLastTime;
-        nLastTime = nNow = std::max(nNow, ++nLastTime);
+        ++nLastTime;
+        nNow = std::max(nNow, nLastTime);
+        nLastTime = nNow;
 
         // Each retry is 2 minutes after the last
         nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
@@ -355,7 +352,6 @@ public:
 
 
 
-
     void PushVersion();
 
 
@@ -581,7 +577,7 @@ public:
     // between nodes running old code and nodes running
     // new code.
     static void ClearBanned(); // needed for unit testing
-    static bool IsBanned(unsigned int ip);
+    static bool IsBanned(CNetAddr ip);
     bool Misbehaving(int howmuch); // 1 == a little, 100 == a lot
 };
 
diff --git a/src/netbase.cpp b/src/netbase.cpp
new file mode 100644 (file)
index 0000000..54e3119
--- /dev/null
@@ -0,0 +1,731 @@
+// Copyright (c) 2009-2010 Satoshi Nakamoto
+// Copyright (c) 2011 The Bitcoin developers
+// Distributed under the MIT/X11 software license, see the accompanying
+// file license.txt or http://www.opensource.org/licenses/mit-license.php.
+
+#include "netbase.h"
+#include "util.h"
+
+#ifndef WIN32
+#include <sys/fcntl.h>
+#endif
+
+#include "strlcpy.h"
+
+using namespace std;
+
+// Settings
+int fUseProxy = false;
+CService addrProxy("127.0.0.1",9050);
+int nConnectTimeout = 5000;
+
+
+static const unsigned char pchIPv4[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff };
+
+bool static LookupIntern(const char *pszName, std::vector<CNetAddr>& vIP, int nMaxSolutions, bool fAllowLookup)
+{
+    vIP.clear();
+    struct addrinfo aiHint;
+    memset(&aiHint, 0, sizeof(struct addrinfo));
+
+    aiHint.ai_socktype = SOCK_STREAM;
+    aiHint.ai_protocol = IPPROTO_TCP;
+#ifdef WIN32
+#  ifdef USE_IPV6
+    aiHint.ai_family = AF_UNSPEC;
+    aiHint.ai_flags = fAllowLookup ? 0 : AI_NUMERICHOST;
+#  else
+    aiHint.ai_family = AF_INET;
+    aiHint.ai_flags = fAllowLookup ? 0 : AI_NUMERICHOST;
+#  endif
+#else
+#  ifdef USE_IPV6
+    aiHint.ai_family = AF_UNSPEC;
+    aiHint.ai_flags = AI_ADDRCONFIG | (fAllowLookup ? 0 : AI_NUMERICHOST);
+#  else
+    aiHint.ai_family = AF_INET;
+    aiHint.ai_flags = AI_ADDRCONFIG | (fAllowLookup ? 0 : AI_NUMERICHOST);
+#  endif
+#endif
+    struct addrinfo *aiRes = NULL;
+    int nErr = getaddrinfo(pszName, NULL, &aiHint, &aiRes);
+    if (nErr)
+        return false;
+
+    struct addrinfo *aiTrav = aiRes;
+    while (aiTrav != NULL && (nMaxSolutions == 0 || vIP.size() < nMaxSolutions))
+    {
+        if (aiTrav->ai_family == AF_INET)
+        {
+            assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in));
+            vIP.push_back(CNetAddr(((struct sockaddr_in*)(aiTrav->ai_addr))->sin_addr));
+        }
+
+#ifdef USE_IPV6
+        if (aiTrav->ai_family == AF_INET6)
+        {
+            assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in6));
+            vIP.push_back(CNetAddr(((struct sockaddr_in6*)(aiTrav->ai_addr))->sin6_addr));
+        }
+#endif
+
+        aiTrav = aiTrav->ai_next;
+    }
+
+    freeaddrinfo(aiRes);
+
+    return (vIP.size() > 0);
+}
+
+bool LookupHost(const char *pszName, std::vector<CNetAddr>& vIP, int nMaxSolutions, bool fAllowLookup)
+{
+    if (pszName[0] == 0)
+        return false;
+    char psz[256];
+    char *pszHost = psz;
+    strlcpy(psz, pszName, sizeof(psz));
+    if (psz[0] == '[' && psz[strlen(psz)-1] == ']')
+    {
+        pszHost = psz+1;
+        psz[strlen(psz)-1] = 0;
+    }
+
+    return LookupIntern(pszHost, vIP, nMaxSolutions, fAllowLookup);
+}
+
+bool LookupHostNumeric(const char *pszName, std::vector<CNetAddr>& vIP, int nMaxSolutions)
+{
+    return LookupHost(pszName, vIP, nMaxSolutions, false);
+}
+
+bool Lookup(const char *pszName, std::vector<CService>& vAddr, int portDefault, bool fAllowLookup, int nMaxSolutions)
+{
+    if (pszName[0] == 0)
+        return false;
+    int port = portDefault;
+    char psz[256];
+    char *pszHost = psz;
+    strlcpy(psz, pszName, sizeof(psz));
+    char* pszColon = strrchr(psz+1,':');
+    char *pszPortEnd = NULL;
+    int portParsed = pszColon ? strtoul(pszColon+1, &pszPortEnd, 10) : 0;
+    if (pszColon && pszPortEnd && pszPortEnd[0] == 0)
+    {
+        if (psz[0] == '[' && pszColon[-1] == ']')
+        {
+            pszHost = psz+1;
+            pszColon[-1] = 0;
+        }
+        else
+            pszColon[0] = 0;
+        if (port >= 0 && port <= USHRT_MAX)
+            port = portParsed;
+    }
+    else
+    {
+        if (psz[0] == '[' && psz[strlen(psz)-1] == ']')
+        {
+            pszHost = psz+1;
+            psz[strlen(psz)-1] = 0;
+        }
+
+    }
+
+    std::vector<CNetAddr> vIP;
+    bool fRet = LookupIntern(pszHost, vIP, nMaxSolutions, fAllowLookup);
+    if (!fRet)
+        return false;
+    vAddr.resize(vIP.size());
+    for (int i = 0; i < vIP.size(); i++)
+        vAddr[i] = CService(vIP[i], port);
+    return true;
+}
+
+bool Lookup(const char *pszName, CService& addr, int portDefault, bool fAllowLookup)
+{
+    std::vector<CService> vService;
+    bool fRet = Lookup(pszName, vService, portDefault, fAllowLookup, 1);
+    if (!fRet)
+        return false;
+    addr = vService[0];
+    return true;
+}
+
+bool LookupNumeric(const char *pszName, CService& addr, int portDefault)
+{
+    return Lookup(pszName, addr, portDefault, false);
+}
+
+bool ConnectSocket(const CService &addrDest, SOCKET& hSocketRet, int nTimeout)
+{
+    hSocketRet = INVALID_SOCKET;
+
+    SOCKET hSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
+    if (hSocket == INVALID_SOCKET)
+        return false;
+#ifdef SO_NOSIGPIPE
+    int set = 1;
+    setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int));
+#endif
+
+    bool fProxy = (fUseProxy && addrDest.IsRoutable());
+    struct sockaddr_in sockaddr;
+    if (fProxy)
+        addrProxy.GetSockAddr(&sockaddr);
+    else
+        addrDest.GetSockAddr(&sockaddr);
+
+#ifdef WIN32
+    u_long fNonblock = 1;
+    if (ioctlsocket(hSocket, FIONBIO, &fNonblock) == SOCKET_ERROR)
+#else
+    int fFlags = fcntl(hSocket, F_GETFL, 0);
+    if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) == -1)
+#endif
+    {
+        closesocket(hSocket);
+        return false;
+    }
+
+
+    if (connect(hSocket, (struct sockaddr*)&sockaddr, sizeof(sockaddr)) == SOCKET_ERROR)
+    {
+        // WSAEINVAL is here because some legacy version of winsock uses it
+        if (WSAGetLastError() == WSAEINPROGRESS || WSAGetLastError() == WSAEWOULDBLOCK || WSAGetLastError() == WSAEINVAL)
+        {
+            struct timeval timeout;
+            timeout.tv_sec  = nTimeout / 1000;
+            timeout.tv_usec = (nTimeout % 1000) * 1000;
+
+            fd_set fdset;
+            FD_ZERO(&fdset);
+            FD_SET(hSocket, &fdset);
+            int nRet = select(hSocket + 1, NULL, &fdset, NULL, &timeout);
+            if (nRet == 0)
+            {
+                printf("connection timeout\n");
+                closesocket(hSocket);
+                return false;
+            }
+            if (nRet == SOCKET_ERROR)
+            {
+                printf("select() for connection failed: %i\n",WSAGetLastError());
+                closesocket(hSocket);
+                return false;
+            }
+            socklen_t nRetSize = sizeof(nRet);
+#ifdef WIN32
+            if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (char*)(&nRet), &nRetSize) == SOCKET_ERROR)
+#else
+            if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, &nRet, &nRetSize) == SOCKET_ERROR)
+#endif
+            {
+                printf("getsockopt() for connection failed: %i\n",WSAGetLastError());
+                closesocket(hSocket);
+                return false;
+            }
+            if (nRet != 0)
+            {
+                printf("connect() failed after select(): %s\n",strerror(nRet));
+                closesocket(hSocket);
+                return false;
+            }
+        }
+#ifdef WIN32
+        else if (WSAGetLastError() != WSAEISCONN)
+#else
+        else
+#endif
+        {
+            printf("connect() failed: %i\n",WSAGetLastError());
+            closesocket(hSocket);
+            return false;
+        }
+    }
+
+    // this isn't even strictly necessary
+    // CNode::ConnectNode immediately turns the socket back to non-blocking
+    // but we'll turn it back to blocking just in case
+#ifdef WIN32
+    fNonblock = 0;
+    if (ioctlsocket(hSocket, FIONBIO, &fNonblock) == SOCKET_ERROR)
+#else
+    fFlags = fcntl(hSocket, F_GETFL, 0);
+    if (fcntl(hSocket, F_SETFL, fFlags & !O_NONBLOCK) == SOCKET_ERROR)
+#endif
+    {
+        closesocket(hSocket);
+        return false;
+    }
+
+    if (fProxy)
+    {
+        printf("proxy connecting %s\n", addrDest.ToString().c_str());
+        char pszSocks4IP[] = "\4\1\0\0\0\0\0\0user";
+        struct sockaddr_in addr;
+        addrDest.GetSockAddr(&addr);
+        memcpy(pszSocks4IP + 2, &addr.sin_port, 2);
+        memcpy(pszSocks4IP + 4, &addr.sin_addr, 4);
+        char* pszSocks4 = pszSocks4IP;
+        int nSize = sizeof(pszSocks4IP);
+
+        int ret = send(hSocket, pszSocks4, nSize, MSG_NOSIGNAL);
+        if (ret != nSize)
+        {
+            closesocket(hSocket);
+            return error("Error sending to proxy");
+        }
+        char pchRet[8];
+        if (recv(hSocket, pchRet, 8, 0) != 8)
+        {
+            closesocket(hSocket);
+            return error("Error reading proxy response");
+        }
+        if (pchRet[1] != 0x5a)
+        {
+            closesocket(hSocket);
+            if (pchRet[1] != 0x5b)
+                printf("ERROR: Proxy returned error %d\n", pchRet[1]);
+            return false;
+        }
+        printf("proxy connected %s\n", addrDest.ToString().c_str());
+    }
+
+    hSocketRet = hSocket;
+    return true;
+}
+
+void CNetAddr::Init()
+{
+    memset(ip, 0, 16);
+}
+
+void CNetAddr::SetIP(const CNetAddr& ipIn)
+{
+    memcpy(ip, ipIn.ip, sizeof(ip));
+}
+
+CNetAddr::CNetAddr()
+{
+    Init();
+}
+
+CNetAddr::CNetAddr(const struct in_addr& ipv4Addr)
+{
+    memcpy(ip,    pchIPv4, 12);
+    memcpy(ip+12, &ipv4Addr, 4);
+}
+
+#ifdef USE_IPV6
+CNetAddr::CNetAddr(const struct in6_addr& ipv6Addr)
+{
+    memcpy(ip, &ipv6Addr, 16);
+}
+#endif
+
+CNetAddr::CNetAddr(const char *pszIp, bool fAllowLookup)
+{
+    Init();
+    std::vector<CNetAddr> vIP;
+    if (LookupHost(pszIp, vIP, 1, fAllowLookup))
+        *this = vIP[0];
+}
+
+CNetAddr::CNetAddr(const std::string &strIp, bool fAllowLookup)
+{
+    Init();
+    std::vector<CNetAddr> vIP;
+    if (LookupHost(strIp.c_str(), vIP, 1, fAllowLookup))
+        *this = vIP[0];
+}
+
+int CNetAddr::GetByte(int n) const
+{
+    return ip[15-n];
+}
+
+bool CNetAddr::IsIPv4() const
+{
+    return (memcmp(ip, pchIPv4, sizeof(pchIPv4)) == 0);
+}
+
+bool CNetAddr::IsRFC1918() const
+{
+    return IsIPv4() && (
+        GetByte(3) == 10 || 
+        (GetByte(3) == 192 && GetByte(2) == 168) || 
+        (GetByte(3) == 172 && (GetByte(2) >= 16 && GetByte(2) <= 31)));
+}
+
+bool CNetAddr::IsRFC3927() const
+{
+    return IsIPv4() && (GetByte(3) == 169 && GetByte(2) == 254);
+}
+
+bool CNetAddr::IsRFC3849() const
+{
+    return GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x0D && GetByte(12) == 0xB8;
+}
+
+bool CNetAddr::IsRFC3964() const
+{
+    return (GetByte(15) == 0x20 && GetByte(14) == 0x02);
+}
+
+bool CNetAddr::IsRFC6052() const
+{
+    static const unsigned char pchRFC6052[] = {0,0x64,0xFF,0x9B,0,0,0,0,0,0,0,0};
+    return (memcmp(ip, pchRFC6052, sizeof(pchRFC6052)) == 0);
+}
+
+bool CNetAddr::IsRFC4380() const
+{
+    return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0 && GetByte(12) == 0);
+}
+
+bool CNetAddr::IsRFC4862() const
+{
+    static const unsigned char pchRFC4862[] = {0xFE,0x80,0,0,0,0,0,0};
+    return (memcmp(ip, pchRFC4862, sizeof(pchRFC4862)) == 0);
+}
+
+bool CNetAddr::IsRFC4193() const
+{
+    return ((GetByte(15) & 0xFE) == 0xFC);
+}
+
+bool CNetAddr::IsRFC6145() const
+{
+    static const unsigned char pchRFC6145[] = {0,0,0,0,0,0,0,0,0xFF,0xFF,0,0};
+    return (memcmp(ip, pchRFC6145, sizeof(pchRFC6145)) == 0);
+}
+
+bool CNetAddr::IsRFC4843() const
+{
+    return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x00 && GetByte(12) & 0xF0 == 0x10);
+}
+
+bool CNetAddr::IsLocal() const
+{
+    // IPv4 loopback
+   if (IsIPv4() && (GetByte(3) == 127 || GetByte(3) == 0))
+       return true;
+
+   // IPv6 loopback (::1/128)
+   static const unsigned char pchLocal[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
+   if (memcmp(ip, pchLocal, 16) == 0)
+       return true;
+
+   return false;
+}
+
+bool CNetAddr::IsMulticast() const
+{
+    return    (IsIPv4() && (GetByte(3) & 0xF0) == 0xE0)
+           || (GetByte(15) == 0xFF);
+}
+
+bool CNetAddr::IsValid() const
+{
+    // Clean up 3-byte shifted addresses caused by garbage in size field
+    // of addr messages from versions before 0.2.9 checksum.
+    // Two consecutive addr messages look like this:
+    // header20 vectorlen3 addr26 addr26 addr26 header20 vectorlen3 addr26 addr26 addr26...
+    // so if the first length field is garbled, it reads the second batch
+    // of addr misaligned by 3 bytes.
+    if (memcmp(ip, pchIPv4+3, sizeof(pchIPv4)-3) == 0)
+        return false;
+
+    // unspecified IPv6 address (::/128)
+    unsigned char ipNone[16] = {};
+    if (memcmp(ip, ipNone, 16) == 0)
+        return false;
+
+    // documentation IPv6 address
+    if (IsRFC3849())
+        return false;
+
+    if (IsIPv4())
+    {
+        // INADDR_NONE
+        uint32_t ipNone = INADDR_NONE;
+        if (memcmp(ip+12, &ipNone, 4) == 0)
+            return false;
+
+        // 0
+        ipNone = 0;
+        if (memcmp(ip+12, &ipNone, 4) == 0)
+            return false;
+    }
+
+    return true;
+}
+
+bool CNetAddr::IsRoutable() const
+{
+    return IsValid() && !(IsRFC1918() || IsRFC3927() || IsRFC4862() || IsRFC4193() || IsRFC4843() || IsLocal());
+}
+
+std::string CNetAddr::ToStringIP() const
+{
+    if (IsIPv4())
+        return strprintf("%u.%u.%u.%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0));
+    else
+        return strprintf("%x:%x:%x:%x:%x:%x:%x:%x",
+                         GetByte(15) << 8 | GetByte(14), GetByte(13) << 8 | GetByte(12),
+                         GetByte(11) << 8 | GetByte(10), GetByte(9) << 8 | GetByte(8),
+                         GetByte(7) << 8 | GetByte(6), GetByte(5) << 8 | GetByte(4),
+                         GetByte(3) << 8 | GetByte(2), GetByte(1) << 8 | GetByte(0));
+}
+
+std::string CNetAddr::ToString() const
+{
+    return ToStringIP();
+}
+
+bool operator==(const CNetAddr& a, const CNetAddr& b)
+{
+    return (memcmp(a.ip, b.ip, 16) == 0);
+}
+
+bool operator!=(const CNetAddr& a, const CNetAddr& b)
+{
+    return (memcmp(a.ip, b.ip, 16) != 0);
+}
+
+bool operator<(const CNetAddr& a, const CNetAddr& b)
+{
+    return (memcmp(a.ip, b.ip, 16) < 0);
+}
+
+bool CNetAddr::GetInAddr(struct in_addr* pipv4Addr) const
+{
+    if (!IsIPv4())
+        return false;
+    memcpy(pipv4Addr, ip+12, 4);
+    return true;
+}
+
+#ifdef USE_IPV6
+bool CNetAddr::GetIn6Addr(struct in6_addr* pipv6Addr) const
+{
+    memcpy(pipv6Addr, ip, 16);
+    return true;
+}
+#endif
+
+// get canonical identifier of an address' group
+// no two connections will be attempted to addresses with the same group
+std::vector<unsigned char> CNetAddr::GetGroup() const
+{
+    std::vector<unsigned char> vchRet;
+    int nClass = 0; // 0=IPv6, 1=IPv4, 255=unroutable
+    int nStartByte = 0;
+    int nBits = 16;
+
+    // for unroutable addresses, each address is considered different
+    if (!IsRoutable())
+    {
+        nClass = 255;
+        nBits = 128;
+    }
+    // for IPv4 addresses, '1' + the 16 higher-order bits of the IP
+    // includes mapped IPv4, SIIT translated IPv4, and the well-known prefix
+    else if (IsIPv4() || IsRFC6145() || IsRFC6052())
+    {
+        nClass = 1;
+        nStartByte = 12;
+    }
+    // for 6to4 tunneled addresses, use the encapsulated IPv4 address
+    else if (IsRFC3964())
+    {
+        nClass = 1;
+        nStartByte = 2;
+    }
+    // for Teredo-tunneled IPv6 addresses, use the encapsulated IPv4 address
+    else if (IsRFC4380())
+    {
+        vchRet.push_back(1);
+        vchRet.push_back(GetByte(3) ^ 0xFF);
+        vchRet.push_back(GetByte(2) ^ 0xFF);
+        return vchRet;
+    }
+    // for he.net, use /36 groups
+    else if (GetByte(15) == 0x20 && GetByte(14) == 0x11 && GetByte(13) == 0x04 && GetByte(12) == 0x70)
+        nBits = 36;
+    // for the rest of the IPv6 network, use /32 groups
+    else
+        nBits = 32;
+
+    vchRet.push_back(nClass);
+    while (nBits >= 8)
+    {
+        vchRet.push_back(GetByte(15 - nStartByte));
+        nStartByte++;
+        nBits -= 8;
+    }
+    if (nBits > 0)
+        vchRet.push_back(GetByte(15 - nStartByte) | ((1 << nBits) - 1));
+
+    return vchRet;
+}
+
+int64 CNetAddr::GetHash() const
+{
+    uint256 hash = Hash(&ip[0], &ip[16]);
+    int64 nRet;
+    memcpy(&nRet, &hash, sizeof(nRet));
+    return nRet;
+}
+
+void CNetAddr::print() const
+{
+    printf("CNetAddr(%s)\n", ToString().c_str());
+}
+
+void CService::Init()
+{
+    port = 0;
+}
+
+CService::CService()
+{
+    Init();
+}
+
+CService::CService(const CNetAddr& cip, unsigned short portIn) : CNetAddr(cip), port(portIn)
+{
+}
+
+CService::CService(const struct in_addr& ipv4Addr, unsigned short portIn) : CNetAddr(ipv4Addr), port(portIn)
+{
+}
+
+#ifdef USE_IPV6
+CService::CService(const struct in6_addr& ipv6Addr, unsigned short portIn) : CNetAddr(ipv6Addr), port(portIn)
+{
+}
+#endif
+
+CService::CService(const struct sockaddr_in& addr) : CNetAddr(addr.sin_addr), port(ntohs(addr.sin_port))
+{
+    assert(addr.sin_family == AF_INET);
+}
+
+#ifdef USE_IPV6
+CService::CService(const struct sockaddr_in6 &addr) : CNetAddr(addr.sin6_addr), port(ntohs(addr.sin6_port))
+{
+   assert(addr.sin6_family == AF_INET6);
+}
+#endif
+
+CService::CService(const char *pszIpPort, bool fAllowLookup)
+{
+    Init();
+    CService ip;
+    if (Lookup(pszIpPort, ip, 0, fAllowLookup))
+        *this = ip;
+}
+
+CService::CService(const char *pszIpPort, int portDefault, bool fAllowLookup)
+{
+    Init();
+    CService ip;
+    if (Lookup(pszIpPort, ip, portDefault, fAllowLookup))
+        *this = ip;
+}
+
+CService::CService(const std::string &strIpPort, bool fAllowLookup)
+{
+    Init();
+    CService ip;
+    if (Lookup(strIpPort.c_str(), ip, 0, fAllowLookup))
+        *this = ip;
+}
+
+CService::CService(const std::string &strIpPort, int portDefault, bool fAllowLookup)
+{
+    Init();
+    CService ip;
+    if (Lookup(strIpPort.c_str(), ip, portDefault, fAllowLookup))
+        *this = ip;
+}
+
+unsigned short CService::GetPort() const
+{
+    return port;
+}
+
+bool operator==(const CService& a, const CService& b)
+{
+    return (CNetAddr)a == (CNetAddr)b && a.port == b.port;
+}
+
+bool operator!=(const CService& a, const CService& b)
+{
+    return (CNetAddr)a != (CNetAddr)b || a.port != b.port;
+}
+
+bool operator<(const CService& a, const CService& b)
+{
+    return (CNetAddr)a < (CNetAddr)b || ((CNetAddr)a == (CNetAddr)b && a.port < b.port);
+}
+
+bool CService::GetSockAddr(struct sockaddr_in* paddr) const
+{
+    if (!IsIPv4())
+        return false;
+    memset(paddr, 0, sizeof(struct sockaddr_in));
+    if (!GetInAddr(&paddr->sin_addr))
+        return false;
+    paddr->sin_family = AF_INET;
+    paddr->sin_port = htons(port);
+    return true;
+}
+
+#ifdef USE_IPV6
+bool CService::GetSockAddr6(struct sockaddr_in6* paddr) const
+{
+    memset(paddr, 0, sizeof(struct sockaddr_in6));
+    if (!GetIn6Addr(&paddr->sin6_addr))
+        return false;
+    paddr->sin6_family = AF_INET6;
+    paddr->sin6_port = htons(port);
+    return true;
+}
+#endif
+
+std::vector<unsigned char> CService::GetKey() const
+{
+     std::vector<unsigned char> vKey;
+     vKey.resize(18);
+     memcpy(&vKey[0], ip, 16);
+     vKey[16] = port / 0x100;
+     vKey[17] = port & 0x0FF;
+     return vKey;
+}
+
+std::string CService::ToStringPort() const
+{
+    return strprintf(":%i", port);
+}
+
+std::string CService::ToStringIPPort() const
+{
+    return ToStringIP() + ToStringPort();
+}
+
+std::string CService::ToString() const
+{
+    return ToStringIPPort();
+}
+
+void CService::print() const
+{
+    printf("CService(%s)\n", ToString().c_str());
+}
+
+void CService::SetPort(unsigned short portIn)
+{
+    port = portIn;
+}
diff --git a/src/netbase.h b/src/netbase.h
new file mode 100644 (file)
index 0000000..04ced18
--- /dev/null
@@ -0,0 +1,139 @@
+// Copyright (c) 2011 The Bitcoin developers
+// Distributed under the MIT/X11 software license, see the accompanying
+// file license.txt or http://www.opensource.org/licenses/mit-license.php.
+#ifndef BITCOIN_NETBASE_H
+#define BITCOIN_NETBASE_H
+
+#include <string>
+#include <vector>
+
+#ifdef WIN32
+#define _WIN32_WINNT 0x0501
+#include <winsock2.h>
+#include <mswsock.h>
+#include <ws2tcpip.h>
+#else
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <arpa/inet.h>
+#include <netdb.h>
+#include <net/if.h>
+#include <ifaddrs.h>
+#endif
+#ifdef BSD
+#include <netinet/in.h>
+#endif
+
+#include "serialize.h"
+#include "compat.h"
+
+extern int nConnectTimeout;
+
+
+// IP address (IPv6, or IPv4 using mapped IPv6 range (::FFFF:0:0/96))
+class CNetAddr
+{
+    protected:
+        unsigned char ip[16]; // in network byte order
+
+    public:
+        CNetAddr();
+        CNetAddr(const struct in_addr& ipv4Addr);
+        explicit CNetAddr(const char *pszIp, bool fAllowLookup = false);
+        explicit CNetAddr(const std::string &strIp, bool fAllowLookup = false);
+        void Init();
+        void SetIP(const CNetAddr& ip);
+        bool IsIPv4() const;    // IPv4 mapped address (::FFFF:0:0/96, 0.0.0.0/0)
+        bool IsRFC1918() const; // IPv4 private networks (10.0.0.0/8, 192.168.0.0/16, 172.16.0.0/12)
+        bool IsRFC3849() const; // IPv6 documentation address (2001:0DB8::/32)
+        bool IsRFC3927() const; // IPv4 autoconfig (169.254.0.0/16)
+        bool IsRFC3964() const; // IPv6 6to4 tunneling (2002::/16)
+        bool IsRFC4193() const; // IPv6 unique local (FC00::/15)
+        bool IsRFC4380() const; // IPv6 Teredo tunneling (2001::/32)
+        bool IsRFC4843() const; // IPv6 ORCHID (2001:10::/28)
+        bool IsRFC4862() const; // IPv6 autoconfig (FE80::/64)
+        bool IsRFC6052() const; // IPv6 well-known prefix (64:FF9B::/96)
+        bool IsRFC6145() const; // IPv6 IPv4-translated address (::FFFF:0:0:0/96)
+        bool IsLocal() const;
+        bool IsRoutable() const;
+        bool IsValid() const;
+        bool IsMulticast() const;
+        std::string ToString() const;
+        std::string ToStringIP() const;
+        int GetByte(int n) const;
+        int64 GetHash() const;
+        bool GetInAddr(struct in_addr* pipv4Addr) const;
+        std::vector<unsigned char> GetGroup() const;
+        void print() const;
+
+#ifdef USE_IPV6
+        CNetAddr(const struct in6_addr& pipv6Addr);
+        bool GetIn6Addr(struct in6_addr* pipv6Addr) const;
+#endif
+
+        friend bool operator==(const CNetAddr& a, const CNetAddr& b);
+        friend bool operator!=(const CNetAddr& a, const CNetAddr& b);
+        friend bool operator<(const CNetAddr& a, const CNetAddr& b);
+
+        IMPLEMENT_SERIALIZE
+            (
+             READWRITE(FLATDATA(ip));
+            )
+};
+
+class CService : public CNetAddr
+{
+    protected:
+        unsigned short port; // host order
+
+    public:
+        CService();
+        CService(const CNetAddr& ip, unsigned short port);
+        CService(const struct in_addr& ipv4Addr, unsigned short port);
+        CService(const struct sockaddr_in& addr);
+        explicit CService(const char *pszIpPort, int portDefault, bool fAllowLookup = false);
+        explicit CService(const char *pszIpPort, bool fAllowLookup = false);
+        explicit CService(const std::string& strIpPort, int portDefault, bool fAllowLookup = false);
+        explicit CService(const std::string& strIpPort, bool fAllowLookup = false);
+        void Init();
+        void SetPort(unsigned short portIn);
+        unsigned short GetPort() const;
+        bool GetSockAddr(struct sockaddr_in* paddr) const;
+        friend bool operator==(const CService& a, const CService& b);
+        friend bool operator!=(const CService& a, const CService& b);
+        friend bool operator<(const CService& a, const CService& b);
+        std::vector<unsigned char> GetKey() const;
+        std::string ToString() const;
+        std::string ToStringPort() const;
+        std::string ToStringIPPort() const;
+        void print() const;
+
+#ifdef USE_IPV6
+        CService(const struct in6_addr& ipv6Addr, unsigned short port);
+        bool GetSockAddr6(struct sockaddr_in6* paddr) const;
+        CService(const struct sockaddr_in6& addr);
+#endif
+
+        IMPLEMENT_SERIALIZE
+            (
+             CService* pthis = const_cast<CService*>(this);
+             READWRITE(FLATDATA(ip));
+             unsigned short portN = htons(port);
+             READWRITE(portN);
+             if (fRead)
+                 pthis->port = ntohs(portN);
+            )
+};
+
+bool LookupHost(const char *pszName, std::vector<CNetAddr>& vIP, int nMaxSolutions = 0, bool fAllowLookup = true);
+bool LookupHostNumeric(const char *pszName, std::vector<CNetAddr>& vIP, int nMaxSolutions = 0);
+bool Lookup(const char *pszName, CService& addr, int portDefault = 0, bool fAllowLookup = true);
+bool Lookup(const char *pszName, std::vector<CService>& vAddr, int portDefault = 0, bool fAllowLookup = true, int nMaxSolutions = 0);
+bool LookupNumeric(const char *pszName, CService& addr, int portDefault = 0);
+bool ConnectSocket(const CService &addr, SOCKET& hSocketRet, int nTimeout = nConnectTimeout);
+
+// Settings
+extern int fUseProxy;
+extern CService addrProxy;
+
+#endif
diff --git a/src/obj-test/.gitignore b/src/obj-test/.gitignore
new file mode 100644 (file)
index 0000000..d6b7ef3
--- /dev/null
@@ -0,0 +1,2 @@
+*
+!.gitignore
index 27efb8f..45f0808 100644 (file)
@@ -5,16 +5,12 @@
 
 #include "protocol.h"
 #include "util.h"
+#include "netbase.h"
 
 #ifndef WIN32
 # include <arpa/inet.h>
 #endif
 
-// Prototypes from net.h, but that header (currently) stinks, can't #include it without breaking things
-bool Lookup(const char *pszName, std::vector<CAddress>& vaddr, int nServices, int nMaxSolutions, bool fAllowLookup = false, int portDefault = 0, bool fAllowPort = false);
-bool Lookup(const char *pszName, CAddress& addr, int nServices, bool fAllowLookup = false, int portDefault = 0, bool fAllowPort = false);
-
-static const unsigned char pchIPv4[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff };
 static const char* ppszTypeName[] =
 {
     "ERROR",
@@ -77,185 +73,26 @@ bool CMessageHeader::IsValid() const
     return true;
 }
 
-CAddress::CAddress()
-{
-    Init();
-}
-
-CAddress::CAddress(unsigned int ipIn, unsigned short portIn, uint64 nServicesIn)
-{
-    Init();
-    ip = ipIn;
-    port = htons(portIn == 0 ? GetDefaultPort() : portIn);
-    nServices = nServicesIn;
-}
-
-CAddress::CAddress(const struct sockaddr_in& sockaddr, uint64 nServicesIn)
-{
-    Init();
-    ip = sockaddr.sin_addr.s_addr;
-    port = sockaddr.sin_port;
-    nServices = nServicesIn;
-}
-
-CAddress::CAddress(const char* pszIn, int portIn, bool fNameLookup, uint64 nServicesIn)
-{
-    Init();
-    Lookup(pszIn, *this, nServicesIn, fNameLookup, portIn);
-}
 
-CAddress::CAddress(const char* pszIn, bool fNameLookup, uint64 nServicesIn)
-{
-    Init();
-    Lookup(pszIn, *this, nServicesIn, fNameLookup, 0, true);
-}
 
-CAddress::CAddress(std::string strIn, int portIn, bool fNameLookup, uint64 nServicesIn)
+CAddress::CAddress() : CService()
 {
     Init();
-    Lookup(strIn.c_str(), *this, nServicesIn, fNameLookup, portIn);
 }
 
-CAddress::CAddress(std::string strIn, bool fNameLookup, uint64 nServicesIn)
+CAddress::CAddress(CService ipIn, uint64 nServicesIn) : CService(ipIn)
 {
     Init();
-    Lookup(strIn.c_str(), *this, nServicesIn, fNameLookup, 0, true);
+    nServices = nServicesIn;
 }
 
 void CAddress::Init()
 {
     nServices = NODE_NETWORK;
-    memcpy(pchReserved, pchIPv4, sizeof(pchReserved));
-    ip = INADDR_NONE;
-    port = htons(GetDefaultPort());
     nTime = 100000000;
     nLastTry = 0;
 }
 
-bool operator==(const CAddress& a, const CAddress& b)
-{
-    return (memcmp(a.pchReserved, b.pchReserved, sizeof(a.pchReserved)) == 0 &&
-            a.ip   == b.ip &&
-            a.port == b.port);
-}
-
-bool operator!=(const CAddress& a, const CAddress& b)
-{
-    return (!(a == b));
-}
-
-bool operator<(const CAddress& a, const CAddress& b)
-{
-    int ret = memcmp(a.pchReserved, b.pchReserved, sizeof(a.pchReserved));
-    if (ret < 0)
-        return true;
-    else if (ret == 0)
-    {
-        if (ntohl(a.ip) < ntohl(b.ip))
-            return true;
-        else if (a.ip == b.ip)
-            return ntohs(a.port) < ntohs(b.port);
-    }
-    return false;
-}
-
-std::vector<unsigned char> CAddress::GetKey() const
-{
-    CDataStream ss;
-    ss.reserve(18);
-    ss << FLATDATA(pchReserved) << ip << port;
-
-    #if defined(_MSC_VER) && _MSC_VER < 1300
-    return std::vector<unsigned char>((unsigned char*)&ss.begin()[0], (unsigned char*)&ss.end()[0]);
-    #else
-    return std::vector<unsigned char>(ss.begin(), ss.end());
-    #endif
-}
-
-struct sockaddr_in CAddress::GetSockAddr() const
-{
-    struct sockaddr_in sockaddr;
-    memset(&sockaddr, 0, sizeof(sockaddr));
-    sockaddr.sin_family = AF_INET;
-    sockaddr.sin_addr.s_addr = ip;
-    sockaddr.sin_port = port;
-    return sockaddr;
-}
-
-bool CAddress::IsIPv4() const
-{
-    return (memcmp(pchReserved, pchIPv4, sizeof(pchIPv4)) == 0);
-}
-
-bool CAddress::IsRFC1918() const
-{
-  return IsIPv4() && (GetByte(3) == 10 ||
-    (GetByte(3) == 192 && GetByte(2) == 168) ||
-    (GetByte(3) == 172 &&
-      (GetByte(2) >= 16 && GetByte(2) <= 31)));
-}
-
-bool CAddress::IsRFC3927() const
-{
-  return IsIPv4() && (GetByte(3) == 169 && GetByte(2) == 254);
-}
-
-bool CAddress::IsLocal() const
-{
-  return IsIPv4() && (GetByte(3) == 127 ||
-      GetByte(3) == 0);
-}
-
-bool CAddress::IsRoutable() const
-{
-    return IsValid() &&
-        !(IsRFC1918() || IsRFC3927() || IsLocal());
-}
-
-bool CAddress::IsValid() const
-{
-    // Clean up 3-byte shifted addresses caused by garbage in size field
-    // of addr messages from versions before 0.2.9 checksum.
-    // Two consecutive addr messages look like this:
-    // header20 vectorlen3 addr26 addr26 addr26 header20 vectorlen3 addr26 addr26 addr26...
-    // so if the first length field is garbled, it reads the second batch
-    // of addr misaligned by 3 bytes.
-    if (memcmp(pchReserved, pchIPv4+3, sizeof(pchIPv4)-3) == 0)
-        return false;
-
-    return (ip != 0 && ip != INADDR_NONE && port != htons(std::numeric_limits<unsigned short>::max()));
-}
-
-unsigned char CAddress::GetByte(int n) const
-{
-    return ((unsigned char*)&ip)[3-n];
-}
-
-std::string CAddress::ToStringIPPort() const
-{
-    return strprintf("%u.%u.%u.%u:%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0), ntohs(port));
-}
-
-std::string CAddress::ToStringIP() const
-{
-    return strprintf("%u.%u.%u.%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0));
-}
-
-std::string CAddress::ToStringPort() const
-{
-    return strprintf("%u", ntohs(port));
-}
-
-std::string CAddress::ToString() const
-{
-    return strprintf("%u.%u.%u.%u:%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0), ntohs(port));
-}
-
-void CAddress::print() const
-{
-    printf("CAddress(%s)\n", ToString().c_str());
-}
-
 CInv::CInv()
 {
     type = 0;
@@ -310,3 +147,4 @@ void CInv::print() const
 {
     printf("CInv(%s)\n", ToString().c_str());
 }
+
index 53d3eef..a0bf677 100644 (file)
@@ -11,6 +11,8 @@
 #define __INCLUDED_PROTOCOL_H__
 
 #include "serialize.h"
+#include "netbase.h"
+#include "util.h"
 #include <string>
 #include "uint256.h"
 
@@ -61,58 +63,33 @@ enum
     NODE_NETWORK = (1 << 0),
 };
 
-class CAddress
+class CAddress : public CService
 {
     public:
         CAddress();
-        CAddress(unsigned int ipIn, unsigned short portIn=0, uint64 nServicesIn=NODE_NETWORK);
-        explicit CAddress(const struct sockaddr_in& sockaddr, uint64 nServicesIn=NODE_NETWORK);
-        explicit CAddress(const char* pszIn, int portIn, bool fNameLookup = false, uint64 nServicesIn=NODE_NETWORK);
-        explicit CAddress(const char* pszIn, bool fNameLookup = false, uint64 nServicesIn=NODE_NETWORK);
-        explicit CAddress(std::string strIn, int portIn, bool fNameLookup = false, uint64 nServicesIn=NODE_NETWORK);
-        explicit CAddress(std::string strIn, bool fNameLookup = false, uint64 nServicesIn=NODE_NETWORK);
+        explicit CAddress(CService ipIn, uint64 nServicesIn=NODE_NETWORK);
 
         void Init();
 
         IMPLEMENT_SERIALIZE
             (
+             CAddress* pthis = const_cast<CAddress*>(this);
+             CService* pip = (CService*)pthis;
              if (fRead)
-             const_cast<CAddress*>(this)->Init();
+                 pthis->Init();
              if (nType & SER_DISK)
              READWRITE(nVersion);
              if ((nType & SER_DISK) || (nVersion >= 31402 && !(nType & SER_GETHASH)))
              READWRITE(nTime);
              READWRITE(nServices);
-             READWRITE(FLATDATA(pchReserved)); // for IPv6
-             READWRITE(ip);
-             READWRITE(port);
+             READWRITE(*pip);
             )
 
-        friend bool operator==(const CAddress& a, const CAddress& b);
-        friend bool operator!=(const CAddress& a, const CAddress& b);
-        friend bool operator<(const CAddress& a, const CAddress& b);
-
-        std::vector<unsigned char> GetKey() const;
-        struct sockaddr_in GetSockAddr() const;
-        bool IsIPv4() const;
-        bool IsRFC1918() const;
-        bool IsRFC3927() const;
-        bool IsLocal() const;
-        bool IsRoutable() const;
-        bool IsValid() const;
-        unsigned char GetByte(int n) const;
-        std::string ToStringIPPort() const;
-        std::string ToStringIP() const;
-        std::string ToStringPort() const;
-        std::string ToString() const;
         void print() const;
 
     // TODO: make private (improves encapsulation)
     public:
         uint64 nServices;
-        unsigned char pchReserved[12];
-        unsigned int ip;
-        unsigned short port;
 
         // disk and network only
         unsigned int nTime;
index c9381a6..f9f92f0 100644 (file)
@@ -417,7 +417,6 @@ void BitcoinGUI::setNumBlocks(int count)
 {
     if(!clientModel)
         return;
-    int initTotal = clientModel->getNumBlocksAtStartup();
     int total = clientModel->getNumBlocksOfPeers();
     QString tooltip;
 
@@ -428,8 +427,8 @@ void BitcoinGUI::setNumBlocks(int count)
             progressBarLabel->setVisible(true);
             progressBarLabel->setText(tr("Synchronizing with network..."));
             progressBar->setVisible(true);
-            progressBar->setMaximum(total - initTotal);
-            progressBar->setValue(count - initTotal);
+            progressBar->setMaximum(total);
+            progressBar->setValue(count);
         }
         else
         {
index cf79973..127b909 100644 (file)
@@ -82,7 +82,7 @@
      <item>
       <widget class="QLabel" name="label_2">
        <property name="text">
-        <string>Copyright Â© 2009-2011 Bitcoin Developers
+        <string>Copyright Â© 2009-2012 Bitcoin Developers
 
 This is experimental software.
 
index e5e19e1..04cf404 100644 (file)
@@ -80,6 +80,9 @@
          <verstretch>0</verstretch>
         </sizepolicy>
        </property>
+       <property name="toolTip">
+        <string>Remove all transaction fields</string>
+       </property>
        <property name="text">
         <string>Clear all</string>
        </property>
index 2f70a38..9a9f6db 100644 (file)
@@ -19,6 +19,9 @@
      <property name="toolTip">
       <string>This pane shows a detailed description of the transaction</string>
      </property>
+     <property name="readOnly">
+      <bool>true</bool>
+     </property>
     </widget>
    </item>
    <item>
index a68c84c..edc1d61 100644 (file)
@@ -40,7 +40,7 @@ QVariant OptionsModel::data(const QModelIndex & index, int role) const
         case ProxyIP:
             return QVariant(QString::fromStdString(addrProxy.ToStringIP()));
         case ProxyPort:
-            return QVariant(QString::fromStdString(addrProxy.ToStringPort()));
+            return QVariant(addrProxy.GetPort());
         case Fee:
             return QVariant(nTransactionFee);
         case DisplayUnit:
@@ -87,10 +87,10 @@ bool OptionsModel::setData(const QModelIndex & index, const QVariant & value, in
         case ProxyIP:
             {
                 // Use CAddress to parse and check IP
-                CAddress addr(value.toString().toStdString() + ":1");
-                if (addr.ip != INADDR_NONE)
+                CNetAddr addr(value.toString().toStdString());
+                if (addr.IsValid())
                 {
-                    addrProxy.ip = addr.ip;
+                    addrProxy.SetIP(addr);
                     walletdb.WriteSetting("addrProxy", addrProxy);
                 }
                 else
@@ -104,7 +104,7 @@ bool OptionsModel::setData(const QModelIndex & index, const QVariant & value, in
                 int nPort = atoi(value.toString().toAscii().data());
                 if (nPort > 0 && nPort < std::numeric_limits<unsigned short>::max())
                 {
-                    addrProxy.port = htons(nPort);
+                    addrProxy.SetPort(nPort);
                     walletdb.WriteSetting("addrProxy", addrProxy);
                 }
                 else
index 8de63c1..089fe75 100644 (file)
@@ -218,6 +218,8 @@ QString TransactionDesc::toHTML(CWallet *wallet, CWalletTx &wtx)
         if (!wtx.mapValue["comment"].empty())
             strHTML += QString("<br><b>") + tr("Comment:") + "</b><br>" + GUIUtil::HtmlEscape(wtx.mapValue["comment"], true) + "<br>";
 
+        strHTML += QString("<b>") + tr("Transaction ID:") + "</b> " + wtx.GetHash().ToString().c_str() + "<br>";
+
         if (wtx.IsCoinBase())
             strHTML += QString("<br>") + tr("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>";
 
index 76cf46f..8d6829d 100644 (file)
@@ -31,7 +31,7 @@ public:
     /** Set maximum number of rows returned, -1 if unlimited. */
     void setLimit(int limit);
 
-    int        rowCount(const QModelIndex &parent = QModelIndex()) const;
+    int rowCount(const QModelIndex &parent = QModelIndex()) const;
 protected:
     bool filterAcceptsRow(int source_row, const QModelIndex & source_parent) const;
 
index f3978fb..471421e 100644 (file)
@@ -62,7 +62,9 @@ Value importprivkey(const Array& params, bool fHelp)
     if (!fGood) throw JSONRPCError(-5,"Invalid private key");
 
     CKey key;
-    key.SetSecret(vchSecret.GetSecret());
+    bool fCompressed;
+    CSecret secret = vchSecret.GetSecret(fCompressed);
+    key.SetSecret(secret, fCompressed);
     CBitcoinAddress vchAddress = CBitcoinAddress(key.GetPubKey());
 
     CRITICAL_BLOCK(cs_main)
@@ -95,7 +97,8 @@ Value dumpprivkey(const Array& params, bool fHelp)
     if (!address.SetString(strAddress))
         throw JSONRPCError(-5, "Invalid bitcoin address");
     CSecret vchSecret;
-    if (!pwalletMain->GetSecret(address, vchSecret))
+    bool fCompressed;
+    if (!pwalletMain->GetSecret(address, vchSecret, fCompressed))
         throw JSONRPCError(-4,"Private key for address " + strAddress + " is not known");
-    return CBitcoinSecret(vchSecret).ToString();
+    return CBitcoinSecret(vchSecret, fCompressed).ToString();
 }
index 3487280..66962d7 100644 (file)
@@ -203,10 +203,8 @@ const char* GetOpName(opcodetype opcode)
     case OP_CHECKMULTISIG          : return "OP_CHECKMULTISIG";
     case OP_CHECKMULTISIGVERIFY    : return "OP_CHECKMULTISIGVERIFY";
 
-    // meta
-    case OP_EVAL                   : return "OP_EVAL";
-
     // expanson
+    case OP_NOP1                   : return "OP_NOP1";
     case OP_NOP2                   : return "OP_NOP2";
     case OP_NOP3                   : return "OP_NOP3";
     case OP_NOP4                   : return "OP_NOP4";
@@ -220,7 +218,6 @@ const char* GetOpName(opcodetype opcode)
 
 
     // template matching params
-    case OP_SCRIPTHASH             : return "OP_SCRIPTHASH";
     case OP_PUBKEYHASH             : return "OP_PUBKEYHASH";
     case OP_PUBKEY                 : return "OP_PUBKEY";
 
@@ -230,26 +227,20 @@ const char* GetOpName(opcodetype opcode)
     }
 }
 
-//
-// Returns true if script is valid.
-//
-bool EvalScriptInner(vector<vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, int nHashType,
-                     CScript::const_iterator pbegincodehash, CScript::const_iterator pendcodehash, int& nOpCount, int& nSigOpCount,
-                     bool fStrictOpEval, int nRecurseDepth)
+bool EvalScript(vector<vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, int nHashType)
 {
     CAutoBN_CTX pctx;
     CScript::const_iterator pc = script.begin();
     CScript::const_iterator pend = script.end();
+    CScript::const_iterator pbegincodehash = script.begin();
     opcodetype opcode;
     valtype vchPushValue;
     vector<bool> vfExec;
     vector<valtype> altstack;
     if (script.size() > 10000)
         return false;
+    int nOpCount = 0;
 
-    // Limit OP_EVAL recursion
-    if (nRecurseDepth > 2)
-        return false;
 
     try
     {
@@ -321,7 +312,7 @@ bool EvalScriptInner(vector<vector<unsigned char> >& stack, const CScript& scrip
                 // Control
                 //
                 case OP_NOP:
-                case OP_NOP2: case OP_NOP3: case OP_NOP4: case OP_NOP5:
+                case OP_NOP1: case OP_NOP2: case OP_NOP3: case OP_NOP4: case OP_NOP5:
                 case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
                 break;
 
@@ -917,13 +908,12 @@ bool EvalScriptInner(vector<vector<unsigned char> >& stack, const CScript& scrip
                     //PrintHex(vchPubKey.begin(), vchPubKey.end(), "pubkey: %s\n");
 
                     // Subset of script starting at the most recent codeseparator
-                    CScript scriptCode(pbegincodehash, pendcodehash);
+                    CScript scriptCode(pbegincodehash, pend);
 
                     // Drop the signature, since there's no way for a signature to sign itself
                     scriptCode.FindAndDelete(CScript(vchSig));
 
                     bool fSuccess = CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType);
-                    nSigOpCount++;
 
                     popstack(stack);
                     popstack(stack);
@@ -967,7 +957,7 @@ bool EvalScriptInner(vector<vector<unsigned char> >& stack, const CScript& scrip
                         return false;
 
                     // Subset of script starting at the most recent codeseparator
-                    CScript scriptCode(pbegincodehash, pendcodehash);
+                    CScript scriptCode(pbegincodehash, pend);
 
                     // Drop the signatures, since there's no way for a signature to sign itself
                     for (int k = 0; k < nSigsCount; k++)
@@ -990,7 +980,6 @@ bool EvalScriptInner(vector<vector<unsigned char> >& stack, const CScript& scrip
                         }
                         ikey++;
                         nKeysCount--;
-                        nSigOpCount++;
 
                         // If there are more signatures left than keys left,
                         // then too many signatures have failed
@@ -1012,32 +1001,6 @@ bool EvalScriptInner(vector<vector<unsigned char> >& stack, const CScript& scrip
                 }
                 break;
 
-                case OP_EVAL:
-                {
-                    if (!fStrictOpEval)
-                        break; // Act as a NO_OP
-
-
-                    // Evaluate the top item on the stack as a Script
-                    // [serialized script ] -- [result(s) of executing script]
-                    if (stack.size() < 1)
-                        return false;
-                    valtype& vchScript = stacktop(-1);
-                    CScript subscript(vchScript.begin(), vchScript.end());
-                    popstack(stack);
-
-                    // Codeseparators not allowed; they don't make sense 'inside' an OP_EVAL, because
-                    // their purpose is to change which parts of the scriptPubKey script is copied
-                    // and signed by OP_CHECKSIG, but OP_EVAl'ed code is in the scriptSig, not the scriptPubKey.
-                    if (subscript.Find(OP_CODESEPARATOR))
-                        return false;
-
-                    if (!EvalScriptInner(stack, subscript, txTo, nIn, nHashType,
-                                         pbegincodehash, pendcodehash, nOpCount, nSigOpCount, fStrictOpEval, nRecurseDepth+1))
-                        return false;
-                }
-                break;
-
                 default:
                     return false;
             }
@@ -1059,18 +1022,6 @@ bool EvalScriptInner(vector<vector<unsigned char> >& stack, const CScript& scrip
     return true;
 }
 
-bool EvalScript(vector<vector<unsigned char> >& stack, const CScript& script,
-                const CTransaction& txTo, unsigned int nIn, int nHashType,
-                bool fStrictOpEval, int& nSigOpCountRet)
-{
-    CScript::const_iterator pbegincodehash = script.begin();
-    CScript::const_iterator pendcodehash = script.end();
-
-    int nOpCount = 0;
-    return EvalScriptInner(stack, script, txTo, nIn, nHashType, pbegincodehash, pendcodehash,
-                           nOpCount, nSigOpCountRet, fStrictOpEval, 0);
-}
-
 
 
 
@@ -1186,10 +1137,16 @@ bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, vector<vector<unsi
 
         // Sender provides N pubkeys, receivers provides M signatures
         mTemplates.insert(make_pair(TX_MULTISIG, CScript() << OP_SMALLINTEGER << OP_PUBKEYS << OP_SMALLINTEGER << OP_CHECKMULTISIG));
+    }
 
-        // Sender provides script hash, receiver provides script and
-        // as many signatures as required to satisfy script
-        mTemplates.insert(make_pair(TX_SCRIPTHASH, CScript() << OP_DUP << OP_HASH160 << OP_SCRIPTHASH << OP_EQUALVERIFY << OP_EVAL));
+    // Shortcut for pay-to-script-hash, which are more constrained than the other types:
+    // it is always OP_HASH160 20 [20 byte hash] OP_EQUAL
+    if (scriptPubKey.IsPayToScriptHash())
+    {
+        typeRet = TX_SCRIPTHASH;
+        vector<unsigned char> hashBytes(scriptPubKey.begin()+2, scriptPubKey.begin()+22);
+        vSolutionsRet.push_back(hashBytes);
+        return true;
     }
 
     // Scan templates
@@ -1253,12 +1210,6 @@ bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, vector<vector<unsi
                     break;
                 vSolutionsRet.push_back(vch1);
             }
-            else if (opcode2 == OP_SCRIPTHASH)
-            {
-                if (vch1.size() != sizeof(uint160))
-                    break;
-                vSolutionsRet.push_back(vch1);
-            }
             else if (opcode2 == OP_SMALLINTEGER)
             {   // Single-byte small integer pushed onto vSolutions
                 if (opcode1 == OP_0 ||
@@ -1319,21 +1270,21 @@ bool SignN(const vector<valtype>& multisigdata, const CKeyStore& keystore, uint2
 
 //
 // Sign scriptPubKey with private keys stored in keystore, given transaction hash and hash type.
-// Signatures are returned in scriptSigRet (or returns false if scriptPubKey can't be signed).
-// Returns true if scriptPubKey could be completely satisified.
+// Signatures are returned in scriptSigRet (or returns false if scriptPubKey can't be signed),
+// unless whichTypeRet is TX_SCRIPTHASH, in which case scriptSigRet is the redemption script.
+// Returns false if scriptPubKey could not be completely satisified.
 //
-bool Solver(const CKeyStore& keystore, const CScript& scriptPubKey, uint256 hash, int nHashType, CScript& scriptSigRet)
+bool Solver(const CKeyStore& keystore, const CScript& scriptPubKey, uint256 hash, int nHashType,
+                  CScript& scriptSigRet, txnouttype& whichTypeRet)
 {
     scriptSigRet.clear();
 
-    txnouttype whichType;
     vector<valtype> vSolutions;
-    if (!Solver(scriptPubKey, whichType, vSolutions))
+    if (!Solver(scriptPubKey, whichTypeRet, vSolutions))
         return false;
 
     CBitcoinAddress address;
-    CScript subscript;
-    switch (whichType)
+    switch (whichTypeRet)
     {
     case TX_NONSTANDARD:
         return false;
@@ -1350,21 +1301,15 @@ bool Solver(const CKeyStore& keystore, const CScript& scriptPubKey, uint256 hash
             keystore.GetPubKey(address, vch);
             scriptSigRet << vch;
         }
-        break;
+        return true;
     case TX_SCRIPTHASH:
-        if (!keystore.GetCScript(uint160(vSolutions[0]), subscript))
-            return false;
-        if (!Solver(keystore, subscript, hash, nHashType, scriptSigRet))
-            return false;
-        if (hash != 0)
-            // static_cast to get vector.operator<< instead of CScript.operator<<
-            scriptSigRet << static_cast<valtype>(subscript); // signatures AND serialized script
-        break;
+        return keystore.GetCScript(uint160(vSolutions[0]), scriptSigRet);
+
     case TX_MULTISIG:
         scriptSigRet << OP_0; // workaround CHECKMULTISIG bug
         return (SignN(vSolutions, keystore, hash, nHashType, scriptSigRet));
     }
-    return true;
+    return false;
 }
 
 
@@ -1503,29 +1448,44 @@ bool ExtractAddresses(const CScript& scriptPubKey, txnouttype& typeRet, vector<C
     return true;
 }
 
-bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn, int& nSigOpCountRet,
-                  int nHashType, bool fStrictOpEval)
+bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
+                  bool fValidatePayToScriptHash, int nHashType)
 {
-    vector<vector<unsigned char> > stack;
-    if (!EvalScript(stack, scriptSig, txTo, nIn, nHashType, fStrictOpEval, nSigOpCountRet))
+    vector<vector<unsigned char> > stack, stackCopy;
+    if (!EvalScript(stack, scriptSig, txTo, nIn, nHashType))
         return false;
-    if (!EvalScript(stack, scriptPubKey, txTo, nIn, nHashType, fStrictOpEval, nSigOpCountRet))
+    if (fValidatePayToScriptHash)
+        stackCopy = stack;
+    if (!EvalScript(stack, scriptPubKey, txTo, nIn, nHashType))
         return false;
     if (stack.empty())
         return false;
-    bool fResult = CastToBool(stack.back());
 
-    // This code should be removed when a compatibility-breaking block chain split has passed.
-    // Special check for OP_EVAL backwards-compatibility: if scriptPubKey or scriptSig contains
-    // OP_EVAL, then result must be identical if OP_EVAL is treated as a no-op:
-    if (fResult && fStrictOpEval && (scriptPubKey.Find(OP_EVAL) || scriptSig.Find(OP_EVAL)))
-        return VerifyScript(scriptSig, scriptPubKey, txTo, nIn, nSigOpCountRet, nHashType, false);
+    if (CastToBool(stack.back()) == false)
+        return false;
+
+    // Additional validation for spend-to-script-hash transactions:
+    if (fValidatePayToScriptHash && scriptPubKey.IsPayToScriptHash())
+    {
+        if (!scriptSig.IsPushOnly()) // scriptSig must be literals-only
+            return false;            // or validation fails
 
-    return fResult;
+        const valtype& pubKeySerialized = stackCopy.back();
+        CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
+        popstack(stackCopy);
+
+        if (!EvalScript(stackCopy, pubKey2, txTo, nIn, nHashType))
+            return false;
+        if (stackCopy.empty())
+            return false;
+        return CastToBool(stackCopy.back());
+    }
+
+    return true;
 }
 
 
-bool SignSignature(const CKeyStore &keystore, const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType, CScript scriptPrereq)
+bool SignSignature(const CKeyStore &keystore, const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType)
 {
     assert(nIn < txTo.vin.size());
     CTxIn& txin = txTo.vin[nIn];
@@ -1534,24 +1494,38 @@ bool SignSignature(const CKeyStore &keystore, const CTransaction& txFrom, CTrans
 
     // Leave out the signature from the hash, since a signature can't sign itself.
     // The checksig op will also drop the signatures from its hash.
-    uint256 hash = SignatureHash(scriptPrereq + txout.scriptPubKey, txTo, nIn, nHashType);
+    uint256 hash = SignatureHash(txout.scriptPubKey, txTo, nIn, nHashType);
 
-    if (!Solver(keystore, txout.scriptPubKey, hash, nHashType, txin.scriptSig))
+    txnouttype whichType;
+    if (!Solver(keystore, txout.scriptPubKey, hash, nHashType, txin.scriptSig, whichType))
         return false;
 
-    txin.scriptSig = scriptPrereq + txin.scriptSig;
+    if (whichType == TX_SCRIPTHASH)
+    {
+        // Solver returns the subscript that need to be evaluated;
+        // the final scriptSig is the signatures from that
+        // and then the serialized subscript:
+        CScript subscript = txin.scriptSig;
+
+        // Recompute txn hash using subscript in place of scriptPubKey:
+        uint256 hash2 = SignatureHash(subscript, txTo, nIn, nHashType);
+        txnouttype subType;
+        if (!Solver(keystore, subscript, hash2, nHashType, txin.scriptSig, subType))
+            return false;
+        if (subType == TX_SCRIPTHASH)
+            return false;
+        txin.scriptSig << static_cast<valtype>(subscript); // Append serialized subscript
+    }
 
     // Test solution
-    int nUnused = 0;
-    if (scriptPrereq.empty())
-        if (!VerifyScript(txin.scriptSig, txout.scriptPubKey, txTo, nIn, nUnused, 0, true))
-            return false;
+    if (!VerifyScript(txin.scriptSig, txout.scriptPubKey, txTo, nIn, true, 0))
+        return false;
 
     return true;
 }
 
 
-bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, unsigned int nIn, int& nSigOpCountRet, int nHashType, bool fStrictOpEval)
+bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, unsigned int nIn, bool fValidatePayToScriptHash, int nHashType)
 {
     assert(nIn < txTo.vin.size());
     const CTxIn& txin = txTo.vin[nIn];
@@ -1562,17 +1536,74 @@ bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, unsig
     if (txin.prevout.hash != txFrom.GetHash())
         return false;
 
-    if (!VerifyScript(txin.scriptSig, txout.scriptPubKey, txTo, nIn, nSigOpCountRet, nHashType, fStrictOpEval))
+    if (!VerifyScript(txin.scriptSig, txout.scriptPubKey, txTo, nIn, fValidatePayToScriptHash, nHashType))
         return false;
 
     return true;
 }
 
+int CScript::GetSigOpCount(bool fAccurate) const
+{
+    int n = 0;
+    const_iterator pc = begin();
+    opcodetype lastOpcode = OP_INVALIDOPCODE;
+    while (pc < end())
+    {
+        opcodetype opcode;
+        if (!GetOp(pc, opcode))
+            break;
+        if (opcode == OP_CHECKSIG || opcode == OP_CHECKSIGVERIFY)
+            n++;
+        else if (opcode == OP_CHECKMULTISIG || opcode == OP_CHECKMULTISIGVERIFY)
+        {
+            if (fAccurate && lastOpcode >= OP_1 && lastOpcode <= OP_16)
+                n += DecodeOP_N(lastOpcode);
+            else
+                n += 20;
+        }
+        lastOpcode = opcode;
+    }
+    return n;
+}
+
+int CScript::GetSigOpCount(const CScript& scriptSig) const
+{
+    if (!IsPayToScriptHash())
+        return GetSigOpCount(true);
+
+    // This is a pay-to-script-hash scriptPubKey;
+    // get the last item that the scriptSig
+    // pushes onto the stack:
+    const_iterator pc = scriptSig.begin();
+    vector<unsigned char> data;
+    while (pc < scriptSig.end())
+    {
+        opcodetype opcode;
+        if (!scriptSig.GetOp(pc, opcode, data))
+            return 0;
+        if (opcode > OP_16)
+            return 0;
+    }
+
+    /// ... and return it's opcount:
+    CScript subscript(data.begin(), data.end());
+    return subscript.GetSigOpCount(true);
+}
+
+bool CScript::IsPayToScriptHash() const
+{
+    // Extra-fast test for pay-to-script-hash CScripts:
+    return (this->size() == 23 &&
+            this->at(0) == OP_HASH160 &&
+            this->at(1) == 0x14 &&
+            this->at(22) == OP_EQUAL);
+}
+
 void CScript::SetBitcoinAddress(const CBitcoinAddress& address)
 {
     this->clear();
     if (address.IsScript())
-        *this << OP_DUP << OP_HASH160 << address.GetHash160() << OP_EQUALVERIFY << OP_EVAL;
+        *this << OP_HASH160 << address.GetHash160() << OP_EQUAL;
     else
         *this << OP_DUP << OP_HASH160 << address.GetHash160() << OP_EQUALVERIFY << OP_CHECKSIG;
 }
@@ -1587,10 +1618,10 @@ void CScript::SetMultisig(int nRequired, const std::vector<CKey>& keys)
     *this << EncodeOP_N(keys.size()) << OP_CHECKMULTISIG;
 }
 
-void CScript::SetEval(const CScript& subscript)
+void CScript::SetPayToScriptHash(const CScript& subscript)
 {
     assert(!subscript.empty());
     uint160 subscriptHash = Hash160(subscript);
     this->clear();
-    *this << OP_DUP << OP_HASH160 << subscriptHash << OP_EQUALVERIFY << OP_EVAL;
+    *this << OP_HASH160 << subscriptHash << OP_EQUAL;
 }
index 0080f5b..63f9f93 100644 (file)
@@ -158,10 +158,8 @@ enum opcodetype
     OP_CHECKMULTISIG,
     OP_CHECKMULTISIGVERIFY,
 
-    // meta
-    OP_EVAL, // Was OP_NOP1
-
     // expansion
+    OP_NOP1,
     OP_NOP2,
     OP_NOP3,
     OP_NOP4,
@@ -177,7 +175,6 @@ enum opcodetype
     // template matching params
     OP_SMALLINTEGER = 0xfa,
     OP_PUBKEYS = 0xfb,
-    OP_SCRIPTHASH = 0xfc,
     OP_PUBKEYHASH = 0xfd,
     OP_PUBKEY = 0xfe,
 
@@ -485,24 +482,18 @@ public:
         return nFound;
     }
 
-    // This method should be removed when a compatibility-breaking block chain split has passed.
-    // Compatibility method for old clients that count sigops differently:
-    int GetSigOpCount() const
-    {
-        int n = 0;
-        const_iterator pc = begin();
-        while (pc < end())
-        {
-            opcodetype opcode;
-            if (!GetOp(pc, opcode))
-                break;
-            if (opcode == OP_CHECKSIG || opcode == OP_CHECKSIGVERIFY)
-                n++;
-            else if (opcode == OP_CHECKMULTISIG || opcode == OP_CHECKMULTISIGVERIFY)
-                n += 20;
-        }
-        return n;
-    }
+    // Pre-version-0.6, Bitcoin always counted CHECKMULTISIGs
+    // as 20 sigops. With pay-to-script-hash, that changed:
+    // CHECKMULTISIGs serialized in scriptSigs are
+    // counted more accurately, assuming they are of the form
+    //  ... OP_N CHECKMULTISIG ...
+    int GetSigOpCount(bool fAccurate) const;
+
+    // Accurately count sigOps, including sigOps in
+    // pay-to-script-hash transactions:
+    int GetSigOpCount(const CScript& scriptSig) const;
+
+    bool IsPayToScriptHash() const;
 
     // Called by CTransaction::IsStandard
     bool IsPushOnly() const
@@ -526,7 +517,7 @@ public:
         SetBitcoinAddress(CBitcoinAddress(vchPubKey));
     }
     void SetMultisig(int nRequired, const std::vector<CKey>& keys);
-    void SetEval(const CScript& subscript);
+    void SetPayToScriptHash(const CScript& subscript);
 
 
     void PrintHex() const
@@ -567,14 +558,13 @@ public:
 
 
 
-bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, int nHashType, bool fStrictOpEval, int& nSigOpCountRet);
-
+bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, int nHashType);
 bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<std::vector<unsigned char> >& vSolutionsRet);
 bool IsStandard(const CScript& scriptPubKey);
 bool IsMine(const CKeyStore& keystore, const CScript& scriptPubKey);
 bool ExtractAddress(const CScript& scriptPubKey, CBitcoinAddress& addressRet);
 bool ExtractAddresses(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<CBitcoinAddress>& addressRet, int& nRequiredRet);
-bool SignSignature(const CKeyStore& keystore, const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType=SIGHASH_ALL, CScript scriptPrereq=CScript());
-bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, unsigned int nIn, int& nSigOpCountRet, int nHashType=0, bool fStrictOpEval=true);
+bool SignSignature(const CKeyStore& keystore, const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType=SIGHASH_ALL);
+bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, unsigned int nIn, bool fValidatePayToScriptHash, int nHashType);
 
 #endif
index 5455590..c9dbdf7 100644 (file)
@@ -89,6 +89,7 @@ enum
         const bool fRead = false;               \
         unsigned int nSerSize = 0;              \
         ser_streamplaceholder s;                \
+        assert(fGetSize||fWrite||fRead); /* suppress warning */ \
         s.nType = nType;                        \
         s.nVersion = nVersion;                  \
         {statements}                            \
@@ -102,6 +103,7 @@ enum
         const bool fWrite = true;               \
         const bool fRead = false;               \
         unsigned int nSerSize = 0;              \
+        assert(fGetSize||fWrite||fRead); /* suppress warning */ \
         {statements}                            \
     }                                           \
     template<typename Stream>                   \
@@ -112,6 +114,7 @@ enum
         const bool fWrite = false;              \
         const bool fRead = true;                \
         unsigned int nSerSize = 0;              \
+        assert(fGetSize||fWrite||fRead); /* suppress warning */ \
         {statements}                            \
     }
 
@@ -819,6 +822,38 @@ struct secure_allocator : public std::allocator<T>
 };
 
 
+//
+// Allocator that clears its contents before deletion.
+//
+template<typename T>
+struct zero_after_free_allocator : public std::allocator<T>
+{
+    // MSVC8 default copy constructor is broken
+    typedef std::allocator<T> base;
+    typedef typename base::size_type size_type;
+    typedef typename base::difference_type  difference_type;
+    typedef typename base::pointer pointer;
+    typedef typename base::const_pointer const_pointer;
+    typedef typename base::reference reference;
+    typedef typename base::const_reference const_reference;
+    typedef typename base::value_type value_type;
+    zero_after_free_allocator() throw() {}
+    zero_after_free_allocator(const zero_after_free_allocator& a) throw() : base(a) {}
+    template <typename U>
+    zero_after_free_allocator(const zero_after_free_allocator<U>& a) throw() : base(a) {}
+    ~zero_after_free_allocator() throw() {}
+    template<typename _Other> struct rebind
+    { typedef zero_after_free_allocator<_Other> other; };
+
+    void deallocate(T* p, std::size_t n)
+    {
+        if (p != NULL)
+            memset(p, 0, sizeof(T) * n);
+        std::allocator<T>::deallocate(p, n);
+    }
+};
+
+
 
 //
 // Double ended buffer combining vector and stream-like interfaces.
@@ -828,7 +863,7 @@ struct secure_allocator : public std::allocator<T>
 class CDataStream
 {
 protected:
-    typedef std::vector<char, secure_allocator<char> > vector_type;
+    typedef std::vector<char, zero_after_free_allocator<char> > vector_type;
     vector_type vch;
     unsigned int nReadPos;
     short state;
index e9b7b45..f29f036 100644 (file)
 #include "net.h"
 #include "util.h"
 
-using namespace std;
+#include <stdint.h>
+
+CService ip(uint32_t i)
+{
+    struct in_addr s;
+    s.s_addr = i;
+    return CService(CNetAddr(s), GetDefaultPort());
+}
 
 BOOST_AUTO_TEST_SUITE(DoS_tests)
 
 BOOST_AUTO_TEST_CASE(DoS_banning)
 {
     CNode::ClearBanned();
-    CAddress addr1(0xa0b0c001);
+    CAddress addr1(ip(0xa0b0c001));
     CNode dummyNode1(INVALID_SOCKET, addr1, true);
     dummyNode1.Misbehaving(100); // Should get banned
-    BOOST_CHECK(CNode::IsBanned(addr1.ip));
-    BOOST_CHECK(!CNode::IsBanned(addr1.ip|0x0000ff00)); // Different ip, not banned
+    BOOST_CHECK(CNode::IsBanned(addr1));
+    BOOST_CHECK(!CNode::IsBanned(ip(0xa0b0c001|0x0000ff00))); // Different ip, not banned
 
-    CAddress addr2(0xa0b0c002);
+    CAddress addr2(ip(0xa0b0c002));
     CNode dummyNode2(INVALID_SOCKET, addr2, true);
     dummyNode2.Misbehaving(50);
-    BOOST_CHECK(!CNode::IsBanned(addr2.ip)); // 2 not banned yet...
-    BOOST_CHECK(CNode::IsBanned(addr1.ip));  // ... but 1 still should be
+    BOOST_CHECK(!CNode::IsBanned(addr2)); // 2 not banned yet...
+    BOOST_CHECK(CNode::IsBanned(addr1));  // ... but 1 still should be
     dummyNode2.Misbehaving(50);
-    BOOST_CHECK(CNode::IsBanned(addr2.ip));
+    BOOST_CHECK(CNode::IsBanned(addr2));
 }    
 
 BOOST_AUTO_TEST_CASE(DoS_banscore)
 {
     CNode::ClearBanned();
     mapArgs["-banscore"] = "111"; // because 11 is my favorite number
-    CAddress addr1(0xa0b0c001);
+    CAddress addr1(ip(0xa0b0c001));
     CNode dummyNode1(INVALID_SOCKET, addr1, true);
     dummyNode1.Misbehaving(100);
-    BOOST_CHECK(!CNode::IsBanned(addr1.ip));
+    BOOST_CHECK(!CNode::IsBanned(addr1));
     dummyNode1.Misbehaving(10);
-    BOOST_CHECK(!CNode::IsBanned(addr1.ip));
+    BOOST_CHECK(!CNode::IsBanned(addr1));
     dummyNode1.Misbehaving(1);
-    BOOST_CHECK(CNode::IsBanned(addr1.ip));
+    BOOST_CHECK(CNode::IsBanned(addr1));
     mapArgs["-banscore"] = "100";
 }
 
@@ -53,20 +60,20 @@ BOOST_AUTO_TEST_CASE(DoS_bantime)
     int64 nStartTime = GetTime();
     SetMockTime(nStartTime); // Overrides future calls to GetTime()
 
-    CAddress addr(0xa0b0c001);
+    CAddress addr(ip(0xa0b0c001));
     CNode dummyNode(INVALID_SOCKET, addr, true);
 
     dummyNode.Misbehaving(100);
-    BOOST_CHECK(CNode::IsBanned(addr.ip));
+    BOOST_CHECK(CNode::IsBanned(addr));
 
     SetMockTime(nStartTime+60*60);
-    BOOST_CHECK(CNode::IsBanned(addr.ip));
+    BOOST_CHECK(CNode::IsBanned(addr));
 
     SetMockTime(nStartTime+60*60*24+1);
-    BOOST_CHECK(!CNode::IsBanned(addr.ip));
-}    
+    BOOST_CHECK(!CNode::IsBanned(addr));
+}
 
-static bool CheckNBits(unsigned int nbits1, int64 time1, unsigned int nbits2, int64 time2)
+static bool CheckNBits(unsigned int nbits1, int64 time1, unsigned int nbits2, int64 time2)\
 {
     if (time1 > time2)
         return CheckNBits(nbits2, time2, nbits1, time1);
diff --git a/src/test/key_tests.cpp b/src/test/key_tests.cpp
new file mode 100644 (file)
index 0000000..bc8759b
--- /dev/null
@@ -0,0 +1,138 @@
+#include <boost/test/unit_test.hpp>
+
+#include <string>
+#include <vector>
+
+#include "key.h"
+#include "base58.h"
+#include "uint256.h"
+#include "util.h"
+
+using namespace std;
+
+static const string strSecret1 ("5HxWvvfubhXpYYpS3tJkw6fq9jE9j18THftkZjHHfmFiWtmAbrj");
+static const string strSecret2 ("5KC4ejrDjv152FGwP386VD1i2NYc5KkfSMyv1nGy1VGDxGHqVY3");
+static const string strSecret1C("Kwr371tjA9u2rFSMZjTNun2PXXP3WPZu2afRHTcta6KxEUdm1vEw");
+static const string strSecret2C("L3Hq7a8FEQwJkW1M2GNKDW28546Vp5miewcCzSqUD9kCAXrJdS3g");
+
+#ifdef KEY_TESTS_DUMPINFO
+void dumpKeyInfo(uint256 privkey)
+{
+    CSecret secret;
+    secret.resize(32);
+    memcpy(&secret[0], &privkey, 32);
+    vector<unsigned char> sec;
+    sec.resize(32);
+    memcpy(&sec[0], &secret[0], 32);
+    printf("  * secret (hex): %s\n", HexStr(sec).c_str());
+
+    for (int nCompressed=0; nCompressed<2; nCompressed++)
+    {
+        bool fCompressed = nCompressed == 1;
+        printf("  * %s:\n", fCompressed ? "compressed" : "uncompressed");
+        CBitcoinSecret bsecret;
+        bsecret.SetSecret(secret, fCompressed);
+        printf("    * secret (base58): %s\n", bsecret.ToString().c_str());
+        CKey key;
+        key.SetSecret(secret, fCompressed);
+        vector<unsigned char> vchPubKey = key.GetPubKey();
+        printf("    * pubkey (hex): %s\n", HexStr(vchPubKey).c_str());
+        printf("    * address (base58): %s\n", CBitcoinAddress(vchPubKey).ToString().c_str());
+    }
+}
+#endif
+
+
+BOOST_AUTO_TEST_SUITE(key_tests)
+
+BOOST_AUTO_TEST_CASE(key_test1)
+{
+    CBitcoinSecret bsecret1, bsecret2, bsecret1C, bsecret2C;
+    bsecret1.SetString (strSecret1);
+    bsecret2.SetString (strSecret2);
+    bsecret1C.SetString(strSecret1C);
+    bsecret2C.SetString(strSecret2C);
+
+    bool fCompressed;
+    CSecret secret1  = bsecret1.GetSecret (fCompressed);
+    BOOST_CHECK(fCompressed == false);
+    CSecret secret2  = bsecret2.GetSecret (fCompressed);
+    BOOST_CHECK(fCompressed == false);
+    CSecret secret1C = bsecret1C.GetSecret(fCompressed);
+    BOOST_CHECK(fCompressed == true);
+    CSecret secret2C = bsecret2C.GetSecret(fCompressed);
+    BOOST_CHECK(fCompressed == true);
+
+    BOOST_CHECK(secret1 == secret1C);
+    BOOST_CHECK(secret2 == secret2C);
+
+    CKey key1, key2, key1C, key2C;
+    key1.SetSecret(secret1, false);
+    key2.SetSecret(secret2, false);
+    key1C.SetSecret(secret1, true);
+    key2C.SetSecret(secret2, true);
+
+    BOOST_CHECK(CBitcoinAddress(key1.GetPubKey ()).ToString() == "1QFqqMUD55ZV3PJEJZtaKCsQmjLT6JkjvJ");
+    BOOST_CHECK(CBitcoinAddress(key2.GetPubKey ()).ToString() == "1F5y5E5FMc5YzdJtB9hLaUe43GDxEKXENJ");
+    BOOST_CHECK(CBitcoinAddress(key1C.GetPubKey()).ToString() == "1NoJrossxPBKfCHuJXT4HadJrXRE9Fxiqs");
+    BOOST_CHECK(CBitcoinAddress(key2C.GetPubKey()).ToString() == "1CRj2HyM1CXWzHAXLQtiGLyggNT9WQqsDs");
+
+    for (int n=0; n<16; n++)
+    {
+        string strMsg = strprintf("Very secret message %i: 11", n);
+        uint256 hashMsg = Hash(strMsg.begin(), strMsg.end());
+
+        // normal signatures
+
+        vector<unsigned char> sign1, sign2, sign1C, sign2C;
+
+        BOOST_CHECK(key1.Sign (hashMsg, sign1));
+        BOOST_CHECK(key2.Sign (hashMsg, sign2));
+        BOOST_CHECK(key1C.Sign(hashMsg, sign1C));
+        BOOST_CHECK(key2C.Sign(hashMsg, sign2C));
+
+        BOOST_CHECK( key1.Verify(hashMsg, sign1));
+        BOOST_CHECK(!key1.Verify(hashMsg, sign2));
+        BOOST_CHECK( key1.Verify(hashMsg, sign1C));
+        BOOST_CHECK(!key1.Verify(hashMsg, sign2C));
+
+        BOOST_CHECK(!key2.Verify(hashMsg, sign1));
+        BOOST_CHECK( key2.Verify(hashMsg, sign2));
+        BOOST_CHECK(!key2.Verify(hashMsg, sign1C));
+        BOOST_CHECK( key2.Verify(hashMsg, sign2C));
+
+        BOOST_CHECK( key1C.Verify(hashMsg, sign1));
+        BOOST_CHECK(!key1C.Verify(hashMsg, sign2));
+        BOOST_CHECK( key1C.Verify(hashMsg, sign1C));
+        BOOST_CHECK(!key1C.Verify(hashMsg, sign2C));
+
+        BOOST_CHECK(!key2C.Verify(hashMsg, sign1));
+        BOOST_CHECK( key2C.Verify(hashMsg, sign2));
+        BOOST_CHECK(!key2C.Verify(hashMsg, sign1C));
+        BOOST_CHECK( key2C.Verify(hashMsg, sign2C));
+
+        // compact signatures (with key recovery)
+
+        vector<unsigned char> csign1, csign2, csign1C, csign2C;
+
+        BOOST_CHECK(key1.SignCompact (hashMsg, csign1));
+        BOOST_CHECK(key2.SignCompact (hashMsg, csign2));
+        BOOST_CHECK(key1C.SignCompact(hashMsg, csign1C));
+        BOOST_CHECK(key2C.SignCompact(hashMsg, csign2C));
+
+        CKey rkey1, rkey2, rkey1C, rkey2C;
+
+        BOOST_CHECK(rkey1.SetCompactSignature (hashMsg, csign1));
+        BOOST_CHECK(rkey2.SetCompactSignature (hashMsg, csign2));
+        BOOST_CHECK(rkey1C.SetCompactSignature(hashMsg, csign1C));
+        BOOST_CHECK(rkey2C.SetCompactSignature(hashMsg, csign2C));
+
+
+        BOOST_CHECK(rkey1.GetPubKey()  == key1.GetPubKey());
+        BOOST_CHECK(rkey2.GetPubKey()  == key2.GetPubKey());
+        BOOST_CHECK(rkey1C.GetPubKey() == key1C.GetPubKey());
+        BOOST_CHECK(rkey2C.GetPubKey() == key2C.GetPubKey());
+    }
+}
+
+BOOST_AUTO_TEST_SUITE_END()
index 0c2e41a..56b1804 100644 (file)
@@ -20,8 +20,8 @@ using namespace boost::assign;
 typedef vector<unsigned char> valtype;
 
 extern uint256 SignatureHash(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType);
-extern bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn, int& nSigOpCount,
-                         int nHashType, bool fStrictOpEval);
+extern bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
+                         bool fValidatePayToScriptHash, int nHashType);
 
 BOOST_AUTO_TEST_SUITE(multisig_tests)
 
@@ -75,25 +75,24 @@ BOOST_AUTO_TEST_CASE(multisig_verify)
 
     vector<CKey> keys;
     CScript s;
-    int nUnused = 0;
 
     // Test a AND b:
     keys.clear();
     keys += key[0],key[1]; // magic operator+= from boost.assign
     s = sign_multisig(a_and_b, keys, txTo[0], 0);
-    BOOST_CHECK(VerifyScript(s, a_and_b, txTo[0], 0, nUnused, 0, true));
+    BOOST_CHECK(VerifyScript(s, a_and_b, txTo[0], 0, true, 0));
 
     for (int i = 0; i < 4; i++)
     {
         keys.clear();
         keys += key[i];
         s = sign_multisig(a_and_b, keys, txTo[0], 0);
-        BOOST_CHECK_MESSAGE(!VerifyScript(s, a_and_b, txTo[0], 0, nUnused, 0, true), strprintf("a&b 1: %d", i));
+        BOOST_CHECK_MESSAGE(!VerifyScript(s, a_and_b, txTo[0], 0, true, 0), strprintf("a&b 1: %d", i));
 
         keys.clear();
         keys += key[1],key[i];
         s = sign_multisig(a_and_b, keys, txTo[0], 0);
-        BOOST_CHECK_MESSAGE(!VerifyScript(s, a_and_b, txTo[0], 0, nUnused, 0, true), strprintf("a&b 2: %d", i));
+        BOOST_CHECK_MESSAGE(!VerifyScript(s, a_and_b, txTo[0], 0, true, 0), strprintf("a&b 2: %d", i));
     }
 
     // Test a OR b:
@@ -103,16 +102,16 @@ BOOST_AUTO_TEST_CASE(multisig_verify)
         keys += key[i];
         s = sign_multisig(a_or_b, keys, txTo[1], 0);
         if (i == 0 || i == 1)
-            BOOST_CHECK_MESSAGE(VerifyScript(s, a_or_b, txTo[1], 0, nUnused, 0, true), strprintf("a|b: %d", i));
+            BOOST_CHECK_MESSAGE(VerifyScript(s, a_or_b, txTo[1], 0, true, 0), strprintf("a|b: %d", i));
         else
-            BOOST_CHECK_MESSAGE(!VerifyScript(s, a_or_b, txTo[1], 0, nUnused, 0, true), strprintf("a|b: %d", i));
+            BOOST_CHECK_MESSAGE(!VerifyScript(s, a_or_b, txTo[1], 0, true, 0), strprintf("a|b: %d", i));
     }
     s.clear();
     s << OP_0 << OP_0;
-    BOOST_CHECK(!VerifyScript(s, a_or_b, txTo[1], 0, nUnused, 0, true));
+    BOOST_CHECK(!VerifyScript(s, a_or_b, txTo[1], 0, true, 0));
     s.clear();
     s << OP_0 << OP_1;
-    BOOST_CHECK(!VerifyScript(s, a_or_b, txTo[1], 0, nUnused, 0, true));
+    BOOST_CHECK(!VerifyScript(s, a_or_b, txTo[1], 0, true, 0));
 
 
     for (int i = 0; i < 4; i++)
@@ -122,9 +121,9 @@ BOOST_AUTO_TEST_CASE(multisig_verify)
             keys += key[i],key[j];
             s = sign_multisig(escrow, keys, txTo[2], 0);
             if (i < j && i < 3 && j < 3)
-                BOOST_CHECK_MESSAGE(VerifyScript(s, escrow, txTo[2], 0, nUnused, 0, true), strprintf("escrow 1: %d %d", i, j));
+                BOOST_CHECK_MESSAGE(VerifyScript(s, escrow, txTo[2], 0, true, 0), strprintf("escrow 1: %d %d", i, j));
             else
-                BOOST_CHECK_MESSAGE(!VerifyScript(s, escrow, txTo[2], 0, nUnused, 0, true), strprintf("escrow 2: %d %d", i, j));
+                BOOST_CHECK_MESSAGE(!VerifyScript(s, escrow, txTo[2], 0, true, 0), strprintf("escrow 2: %d %d", i, j));
         }
 }
 
diff --git a/src/test/rpc_tests.cpp b/src/test/rpc_tests.cpp
new file mode 100644 (file)
index 0000000..87462f7
--- /dev/null
@@ -0,0 +1,74 @@
+#include <boost/test/unit_test.hpp>
+#include <boost/foreach.hpp>
+
+#include "base58.h"
+#include "util.h"
+#include "json/json_spirit_reader_template.h"
+#include "json/json_spirit_writer_template.h"
+#include "json/json_spirit_utils.h"
+
+using namespace std;
+using namespace json_spirit;
+
+typedef Value(*rpcfn_type)(const Array& params, bool fHelp);
+extern map<string, rpcfn_type> mapCallTable;
+
+BOOST_AUTO_TEST_SUITE(rpc_tests)
+
+static Array
+createArgs(int nRequired, const char* address1=NULL, const char* address2=NULL)
+{
+    Array result;
+    result.push_back(nRequired);
+    Array addresses;
+    if (address1) addresses.push_back(address1);
+    if (address2) addresses.push_back(address1);
+    result.push_back(addresses);
+    return result;
+}
+
+// This can be removed this when addmultisigaddress is enabled on main net:
+struct TestNetFixture
+{
+    TestNetFixture() { fTestNet = true; }
+    ~TestNetFixture() { fTestNet = false; }
+};
+
+BOOST_FIXTURE_TEST_CASE(rpc_addmultisig, TestNetFixture)
+{
+    rpcfn_type addmultisig = mapCallTable["addmultisigaddress"];
+
+    // old, 65-byte-long:
+    const char* address1Hex = "0434e3e09f49ea168c5bbf53f877ff4206923858aab7c7e1df25bc263978107c95e35065a27ef6f1b27222db0ec97e0e895eaca603d3ee0d4c060ce3d8a00286c8";
+    // new, compressed:
+    const char* address2Hex = "0388c2037017c62240b6b72ac1a2a5f94da790596ebd06177c8572752922165cb4";
+
+    Value v;
+    CBitcoinAddress address;
+    BOOST_CHECK_NO_THROW(v = addmultisig(createArgs(1, address1Hex), false));
+    address.SetString(v.get_str());
+    BOOST_CHECK(address.IsValid() && address.IsScript());
+
+    BOOST_CHECK_NO_THROW(v = addmultisig(createArgs(1, address1Hex, address2Hex), false));
+    address.SetString(v.get_str());
+    BOOST_CHECK(address.IsValid() && address.IsScript());
+
+    BOOST_CHECK_NO_THROW(v = addmultisig(createArgs(2, address1Hex, address2Hex), false));
+    address.SetString(v.get_str());
+    BOOST_CHECK(address.IsValid() && address.IsScript());
+
+    BOOST_CHECK_THROW(addmultisig(createArgs(0), false), runtime_error);
+    BOOST_CHECK_THROW(addmultisig(createArgs(1), false), runtime_error);
+    BOOST_CHECK_THROW(addmultisig(createArgs(2, address1Hex), false), runtime_error);
+
+    BOOST_CHECK_THROW(addmultisig(createArgs(1, ""), false), runtime_error);
+    BOOST_CHECK_THROW(addmultisig(createArgs(1, "NotAValidPubkey"), false), runtime_error);
+
+    string short1(address1Hex, address1Hex+sizeof(address1Hex)-2); // last byte missing
+    BOOST_CHECK_THROW(addmultisig(createArgs(2, short1.c_str()), false), runtime_error);
+
+    string short2(address1Hex+2, address1Hex+sizeof(address1Hex)); // first byte missing
+    BOOST_CHECK_THROW(addmultisig(createArgs(2, short2.c_str()), false), runtime_error);
+}
+
+BOOST_AUTO_TEST_SUITE_END()
diff --git a/src/test/script_P2SH_tests.cpp b/src/test/script_P2SH_tests.cpp
new file mode 100644 (file)
index 0000000..c782e0c
--- /dev/null
@@ -0,0 +1,321 @@
+#include <boost/assert.hpp>
+#include <boost/assign/list_of.hpp>
+#include <boost/assign/list_inserter.hpp>
+#include <boost/assign/std/vector.hpp>
+#include <boost/test/unit_test.hpp>
+#include <boost/foreach.hpp>
+
+#include "../main.h"
+#include "../script.h"
+#include "../wallet.h"
+
+using namespace std;
+
+// Test routines internal to script.cpp:
+extern uint256 SignatureHash(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType);
+extern bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
+                         bool fValidatePayToScriptHash, int nHashType);
+
+// Helpers:
+static std::vector<unsigned char>
+Serialize(const CScript& s)
+{
+    std::vector<unsigned char> sSerialized(s);
+    return sSerialized;
+}
+
+static bool
+Verify(const CScript& scriptSig, const CScript& scriptPubKey, bool fStrict)
+{
+    // Create dummy to/from transactions:
+    CTransaction txFrom;
+    txFrom.vout.resize(1);
+    txFrom.vout[0].scriptPubKey = scriptPubKey;
+
+    CTransaction txTo;
+    txTo.vin.resize(1);
+    txTo.vout.resize(1);
+    txTo.vin[0].prevout.n = 0;
+    txTo.vin[0].prevout.hash = txFrom.GetHash();
+    txTo.vin[0].scriptSig = scriptSig;
+    txTo.vout[0].nValue = 1;
+
+    return VerifyScript(scriptSig, scriptPubKey, txTo, 0, fStrict, 0);
+}
+
+
+BOOST_AUTO_TEST_SUITE(script_P2SH_tests)
+
+BOOST_AUTO_TEST_CASE(sign)
+{
+    // Pay-to-script-hash looks like this:
+    // scriptSig:    <sig> <sig...> <serialized_script>
+    // scriptPubKey: HASH160 <hash> EQUAL
+
+    // Test SignSignature() (and therefore the version of Solver() that signs transactions)
+    CBasicKeyStore keystore;
+    CKey key[4];
+    for (int i = 0; i < 4; i++)
+    {
+        key[i].MakeNewKey();
+        keystore.AddKey(key[i]);
+    }
+
+    // 8 Scripts: checking all combinations of
+    // different keys, straight/P2SH, pubkey/pubkeyhash
+    CScript standardScripts[4];
+    standardScripts[0] << key[0].GetPubKey() << OP_CHECKSIG;
+    standardScripts[1].SetBitcoinAddress(key[1].GetPubKey());
+    standardScripts[2] << key[1].GetPubKey() << OP_CHECKSIG;
+    standardScripts[3].SetBitcoinAddress(key[2].GetPubKey());
+    CScript evalScripts[4];
+    for (int i = 0; i < 4; i++)
+    {
+        keystore.AddCScript(standardScripts[i]);
+        evalScripts[i].SetPayToScriptHash(standardScripts[i]);
+    }
+
+    CTransaction txFrom;  // Funding transaction:
+    txFrom.vout.resize(8);
+    for (int i = 0; i < 4; i++)
+    {
+        txFrom.vout[i].scriptPubKey = evalScripts[i];
+        txFrom.vout[i+4].scriptPubKey = standardScripts[i];
+    }
+    BOOST_CHECK(txFrom.IsStandard());
+
+    CTransaction txTo[8]; // Spending transactions
+    for (int i = 0; i < 8; i++)
+    {
+        txTo[i].vin.resize(1);
+        txTo[i].vout.resize(1);
+        txTo[i].vin[0].prevout.n = i;
+        txTo[i].vin[0].prevout.hash = txFrom.GetHash();
+        txTo[i].vout[0].nValue = 1;
+        BOOST_CHECK_MESSAGE(IsMine(keystore, txFrom.vout[i].scriptPubKey), strprintf("IsMine %d", i));
+    }
+    for (int i = 0; i < 8; i++)
+    {
+        BOOST_CHECK_MESSAGE(SignSignature(keystore, txFrom, txTo[i], 0), strprintf("SignSignature %d", i));
+    }
+    // All of the above should be OK, and the txTos have valid signatures
+    // Check to make sure signature verification fails if we use the wrong ScriptSig:
+    for (int i = 0; i < 8; i++)
+        for (int j = 0; j < 8; j++)
+        {
+            CScript sigSave = txTo[i].vin[0].scriptSig;
+            txTo[i].vin[0].scriptSig = txTo[j].vin[0].scriptSig;
+            bool sigOK = VerifySignature(txFrom, txTo[i], 0, true, 0);
+            if (i == j)
+                BOOST_CHECK_MESSAGE(sigOK, strprintf("VerifySignature %d %d", i, j));
+            else
+                BOOST_CHECK_MESSAGE(!sigOK, strprintf("VerifySignature %d %d", i, j));
+            txTo[i].vin[0].scriptSig = sigSave;
+        }
+}
+
+BOOST_AUTO_TEST_CASE(norecurse)
+{
+    // Make sure only the outer pay-to-script-hash does the
+    // extra-validation thing:
+    CScript invalidAsScript;
+    invalidAsScript << OP_INVALIDOPCODE << OP_INVALIDOPCODE;
+
+    CScript p2sh;
+    p2sh.SetPayToScriptHash(invalidAsScript);
+
+    CScript scriptSig;
+    scriptSig << Serialize(invalidAsScript);
+
+    // Should not verify, because it will try to execute OP_INVALIDOPCODE
+    BOOST_CHECK(!Verify(scriptSig, p2sh, true));
+
+    // Try to recurse, and verification should succeed because
+    // the inner HASH160 <> EQUAL should only check the hash:
+    CScript p2sh2;
+    p2sh2.SetPayToScriptHash(p2sh);
+    CScript scriptSig2;
+    scriptSig2 << Serialize(invalidAsScript) << Serialize(p2sh);
+
+    BOOST_CHECK(Verify(scriptSig2, p2sh2, true));
+}
+
+BOOST_AUTO_TEST_CASE(set)
+{
+    // Test the CScript::Set* methods
+    CBasicKeyStore keystore;
+    CKey key[4];
+    std::vector<CKey> keys;
+    for (int i = 0; i < 4; i++)
+    {
+        key[i].MakeNewKey();
+        keystore.AddKey(key[i]);
+        keys.push_back(key[i]);
+    }
+
+    CScript inner[4];
+    inner[0].SetBitcoinAddress(key[0].GetPubKey());
+    inner[1].SetMultisig(2, std::vector<CKey>(keys.begin(), keys.begin()+2));
+    inner[2].SetMultisig(1, std::vector<CKey>(keys.begin(), keys.begin()+2));
+    inner[3].SetMultisig(2, std::vector<CKey>(keys.begin(), keys.begin()+3));
+
+    CScript outer[4];
+    for (int i = 0; i < 4; i++)
+    {
+        outer[i].SetPayToScriptHash(inner[i]);
+        keystore.AddCScript(inner[i]);
+    }
+
+    CTransaction txFrom;  // Funding transaction:
+    txFrom.vout.resize(4);
+    for (int i = 0; i < 4; i++)
+    {
+        txFrom.vout[i].scriptPubKey = outer[i];
+    }
+    BOOST_CHECK(txFrom.IsStandard());
+
+    CTransaction txTo[4]; // Spending transactions
+    for (int i = 0; i < 4; i++)
+    {
+        txTo[i].vin.resize(1);
+        txTo[i].vout.resize(1);
+        txTo[i].vin[0].prevout.n = i;
+        txTo[i].vin[0].prevout.hash = txFrom.GetHash();
+        txTo[i].vout[0].nValue = 1;
+        txTo[i].vout[0].scriptPubKey = inner[i];
+        BOOST_CHECK_MESSAGE(IsMine(keystore, txFrom.vout[i].scriptPubKey), strprintf("IsMine %d", i));
+    }
+    for (int i = 0; i < 4; i++)
+    {
+        BOOST_CHECK_MESSAGE(SignSignature(keystore, txFrom, txTo[i], 0), strprintf("SignSignature %d", i));
+        BOOST_CHECK_MESSAGE(txTo[i].IsStandard(), strprintf("txTo[%d].IsStandard", i));
+    }
+}
+
+BOOST_AUTO_TEST_CASE(is)
+{
+    // Test CScript::IsPayToScriptHash()
+    uint160 dummy;
+    CScript p2sh;
+    p2sh << OP_HASH160 << dummy << OP_EQUAL;
+    BOOST_CHECK(p2sh.IsPayToScriptHash());
+
+    // Not considered pay-to-script-hash if using one of the OP_PUSHDATA opcodes:
+    static const unsigned char direct[] =    { OP_HASH160, 20, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, OP_EQUAL };
+    BOOST_CHECK(CScript(direct, direct+sizeof(direct)).IsPayToScriptHash());
+    static const unsigned char pushdata1[] = { OP_HASH160, OP_PUSHDATA1, 20, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, OP_EQUAL };
+    BOOST_CHECK(!CScript(pushdata1, pushdata1+sizeof(pushdata1)).IsPayToScriptHash());
+    static const unsigned char pushdata2[] = { OP_HASH160, OP_PUSHDATA2, 20,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, OP_EQUAL };
+    BOOST_CHECK(!CScript(pushdata2, pushdata2+sizeof(pushdata2)).IsPayToScriptHash());
+    static const unsigned char pushdata4[] = { OP_HASH160, OP_PUSHDATA4, 20,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, OP_EQUAL };
+    BOOST_CHECK(!CScript(pushdata4, pushdata4+sizeof(pushdata4)).IsPayToScriptHash());
+
+    CScript not_p2sh;
+    BOOST_CHECK(!not_p2sh.IsPayToScriptHash());
+
+    not_p2sh.clear(); not_p2sh << OP_HASH160 << dummy << dummy << OP_EQUAL;
+    BOOST_CHECK(!not_p2sh.IsPayToScriptHash());
+
+    not_p2sh.clear(); not_p2sh << OP_NOP << dummy << OP_EQUAL;
+    BOOST_CHECK(!not_p2sh.IsPayToScriptHash());
+
+    not_p2sh.clear(); not_p2sh << OP_HASH160 << dummy << OP_CHECKSIG;
+    BOOST_CHECK(!not_p2sh.IsPayToScriptHash());
+}
+
+BOOST_AUTO_TEST_CASE(switchover)
+{
+    // Test switchover code
+    CScript notValid;
+    notValid << OP_11 << OP_12 << OP_EQUALVERIFY;
+    CScript scriptSig;
+    scriptSig << Serialize(notValid);
+
+    CScript fund;
+    fund.SetPayToScriptHash(notValid);
+
+
+    // Validation should succeed under old rules (hash is correct):
+    BOOST_CHECK(Verify(scriptSig, fund, false));
+    // Fail under new:
+    BOOST_CHECK(!Verify(scriptSig, fund, true));
+}
+
+BOOST_AUTO_TEST_CASE(AreInputsStandard)
+{
+    std::map<uint256, std::pair<CTxIndex, CTransaction> > mapInputs;
+    CBasicKeyStore keystore;
+    CKey key[3];
+    vector<CKey> keys;
+    for (int i = 0; i < 3; i++)
+    {
+        key[i].MakeNewKey();
+        keystore.AddKey(key[i]);
+        keys.push_back(key[i]);
+    }
+
+    CTransaction txFrom;
+    txFrom.vout.resize(6);
+
+    // First three are standard:
+    CScript pay1; pay1.SetBitcoinAddress(key[0].GetPubKey());
+    keystore.AddCScript(pay1);
+    CScript payScriptHash1; payScriptHash1.SetPayToScriptHash(pay1);
+    CScript pay1of3; pay1of3.SetMultisig(1, keys);
+
+    txFrom.vout[0].scriptPubKey = payScriptHash1;
+    txFrom.vout[1].scriptPubKey = pay1;
+    txFrom.vout[2].scriptPubKey = pay1of3;
+
+    // Last three non-standard:
+    CScript empty;
+    keystore.AddCScript(empty);
+    txFrom.vout[3].scriptPubKey = empty;
+    // Can't use SetPayToScriptHash, it checks for the empty Script. So:
+    txFrom.vout[4].scriptPubKey << OP_HASH160 << Hash160(empty) << OP_EQUAL;
+    CScript oneOfEleven;
+    oneOfEleven << OP_1;
+    for (int i = 0; i < 11; i++)
+        oneOfEleven << key[0].GetPubKey();
+    oneOfEleven << OP_11 << OP_CHECKMULTISIG;
+    txFrom.vout[5].scriptPubKey.SetPayToScriptHash(oneOfEleven);
+
+    mapInputs[txFrom.GetHash()] = make_pair(CTxIndex(), txFrom);
+
+    CTransaction txTo;
+    txTo.vout.resize(1);
+    txTo.vout[0].scriptPubKey.SetBitcoinAddress(key[1].GetPubKey());
+
+    txTo.vin.resize(3);
+    txTo.vin[0].prevout.n = 0;
+    txTo.vin[0].prevout.hash = txFrom.GetHash();
+    BOOST_CHECK(SignSignature(keystore, txFrom, txTo, 0));
+    txTo.vin[1].prevout.n = 1;
+    txTo.vin[1].prevout.hash = txFrom.GetHash();
+    BOOST_CHECK(SignSignature(keystore, txFrom, txTo, 1));
+    txTo.vin[2].prevout.n = 2;
+    txTo.vin[2].prevout.hash = txFrom.GetHash();
+    BOOST_CHECK(SignSignature(keystore, txFrom, txTo, 2));
+
+    BOOST_CHECK(txTo.AreInputsStandard(mapInputs));
+    BOOST_CHECK_EQUAL(txTo.GetP2SHSigOpCount(mapInputs), 1);
+
+    CTransaction txToNonStd;
+    txToNonStd.vout.resize(1);
+    txToNonStd.vout[0].scriptPubKey.SetBitcoinAddress(key[1].GetPubKey());
+    txToNonStd.vin.resize(2);
+    txToNonStd.vin[0].prevout.n = 4;
+    txToNonStd.vin[0].prevout.hash = txFrom.GetHash();
+    txToNonStd.vin[0].scriptSig << Serialize(empty);
+    txToNonStd.vin[1].prevout.n = 5;
+    txToNonStd.vin[1].prevout.hash = txFrom.GetHash();
+    txToNonStd.vin[1].scriptSig << OP_0 << Serialize(oneOfEleven);
+
+    BOOST_CHECK(!txToNonStd.AreInputsStandard(mapInputs));
+    BOOST_CHECK_EQUAL(txToNonStd.GetP2SHSigOpCount(mapInputs), 11);
+
+    txToNonStd.vin[0].scriptSig.clear();
+    BOOST_CHECK(!txToNonStd.AreInputsStandard(mapInputs));
+}
+
+BOOST_AUTO_TEST_SUITE_END()
diff --git a/src/test/script_op_eval_tests.cpp b/src/test/script_op_eval_tests.cpp
deleted file mode 100644 (file)
index b1bd52c..0000000
+++ /dev/null
@@ -1,268 +0,0 @@
-#include <boost/assert.hpp>
-#include <boost/assign/list_of.hpp>
-#include <boost/assign/list_inserter.hpp>
-#include <boost/assign/std/vector.hpp>
-#include <boost/test/unit_test.hpp>
-#include <boost/foreach.hpp>
-
-#include "../main.h"
-#include "../script.h"
-#include "../wallet.h"
-
-using namespace std;
-
-// Test routines internal to script.cpp:
-extern uint256 SignatureHash(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType);
-extern bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn, int& nSigOps,
-                         int nHashType, bool fStrictOpEval);
-
-BOOST_AUTO_TEST_SUITE(script_op_eval_tests)
-
-BOOST_AUTO_TEST_CASE(script_op_eval1)
-{
-    // OP_EVAL looks like this:
-    // scriptSig:    <sig> <sig...> <serialized_script>
-    // scriptPubKey: DUP HASH160 <hash> EQUALVERIFY EVAL
-
-    // Test SignSignature() (and therefore the version of Solver() that signs transactions)
-    CBasicKeyStore keystore;
-    CKey key[4];
-    for (int i = 0; i < 4; i++)
-    {
-        key[i].MakeNewKey();
-        keystore.AddKey(key[i]);
-    }
-
-    // 8 Scripts: checking all combinations of
-    // different keys, straight/EVAL, pubkey/pubkeyhash
-    CScript standardScripts[4];
-    standardScripts[0] << key[0].GetPubKey() << OP_CHECKSIG;
-    standardScripts[1].SetBitcoinAddress(key[1].GetPubKey());
-    standardScripts[2] << key[1].GetPubKey() << OP_CHECKSIG;
-    standardScripts[3].SetBitcoinAddress(key[2].GetPubKey());
-    CScript evalScripts[4];
-    uint160 sigScriptHashes[4];
-    for (int i = 0; i < 4; i++)
-    {
-        sigScriptHashes[i] = Hash160(standardScripts[i]);
-        keystore.AddCScript(sigScriptHashes[i], standardScripts[i]);
-        evalScripts[i] << OP_DUP << OP_HASH160 << sigScriptHashes[i] << OP_EQUALVERIFY << OP_EVAL;
-    }
-
-    CTransaction txFrom;  // Funding transaction:
-    txFrom.vout.resize(8);
-    for (int i = 0; i < 4; i++)
-    {
-        txFrom.vout[i].scriptPubKey = evalScripts[i];
-        txFrom.vout[i+4].scriptPubKey = standardScripts[i];
-    }
-    BOOST_CHECK(txFrom.IsStandard());
-
-    CTransaction txTo[8]; // Spending transactions
-    for (int i = 0; i < 8; i++)
-    {
-        txTo[i].vin.resize(1);
-        txTo[i].vout.resize(1);
-        txTo[i].vin[0].prevout.n = i;
-        txTo[i].vin[0].prevout.hash = txFrom.GetHash();
-        txTo[i].vout[0].nValue = 1;
-        BOOST_CHECK_MESSAGE(IsMine(keystore, txFrom.vout[i].scriptPubKey), strprintf("IsMine %d", i));
-    }
-    for (int i = 0; i < 8; i++)
-    {
-        BOOST_CHECK_MESSAGE(SignSignature(keystore, txFrom, txTo[i], 0), strprintf("SignSignature %d", i));
-    }
-    // All of the above should be OK, and the txTos have valid signatures
-    // Check to make sure signature verification fails if we use the wrong ScriptSig:
-    for (int i = 0; i < 8; i++)
-        for (int j = 0; j < 8; j++)
-        {
-            CScript sigSave = txTo[i].vin[0].scriptSig;
-            txTo[i].vin[0].scriptSig = txTo[j].vin[0].scriptSig;
-            int nUnused = 0;
-            bool sigOK = VerifySignature(txFrom, txTo[i], 0, nUnused);
-            if (i == j)
-                BOOST_CHECK_MESSAGE(sigOK, strprintf("VerifySignature %d %d", i, j));
-            else
-                BOOST_CHECK_MESSAGE(!sigOK, strprintf("VerifySignature %d %d", i, j));
-            txTo[i].vin[0].scriptSig = sigSave;
-        }
-}
-
-BOOST_AUTO_TEST_CASE(script_op_eval2)
-{
-    // Test OP_EVAL edge cases
-
-    // Make sure infinite recursion fails to validate:
-    CScript infiniteRecurse;
-    infiniteRecurse << OP_DUP << OP_EVAL;
-
-    uint160 infiniteRecurseHash = Hash160(infiniteRecurse);
-
-    CScript fund1;
-    fund1 << OP_DUP << OP_HASH160 << infiniteRecurseHash << OP_EQUALVERIFY << OP_EVAL;
-
-    CTransaction txFrom1;  // Funding transaction:
-    txFrom1.vout.resize(1);
-    txFrom1.vout[0].scriptPubKey = fund1;
-
-    BOOST_CHECK(txFrom1.IsStandard()); // Looks like a standard transaction until you try to spend it
-
-    std::vector<unsigned char> infiniteRecurseSerialized(infiniteRecurse);
-
-    CTransaction txTo1;
-    txTo1.vin.resize(1);
-    txTo1.vout.resize(1);
-    txTo1.vin[0].prevout.n = 0;
-    txTo1.vin[0].prevout.hash = txFrom1.GetHash();
-    txTo1.vin[0].scriptSig = CScript() << infiniteRecurseSerialized << infiniteRecurseSerialized;
-    txTo1.vout[0].nValue = 1;
-
-    int nUnused1 = 0;
-    BOOST_CHECK(!VerifyScript(txTo1.vin[0].scriptSig, txFrom1.vout[0].scriptPubKey, txTo1, 0, nUnused1, 0, true));
-    BOOST_CHECK(!VerifySignature(txFrom1, txTo1, 0, nUnused1, true));
-
-    // Make sure 3-level-deep recursion fails to validate:
-    CScript recurse3;
-    recurse3 << OP_EVAL;
-
-    uint160 recurse3Hash = Hash160(recurse3);
-
-    CScript fund2;
-    fund2 << OP_DUP << OP_HASH160 << recurse3Hash << OP_EQUALVERIFY << OP_EVAL;
-
-    CTransaction txFrom2;  // Funding transaction:
-    txFrom2.vout.resize(1);
-    txFrom2.vout[0].scriptPubKey = fund2;
-
-    BOOST_CHECK(txFrom2.IsStandard()); // Looks like a standard transaction until you try to spend it
-
-    std::vector<unsigned char> recurse3Serialized(recurse3);
-    CScript op1Script = CScript() << OP_1;
-    std::vector<unsigned char> op1Serialized(op1Script);
-
-    CTransaction txTo2;
-    txTo2.vin.resize(1);
-    txTo2.vout.resize(1);
-    txTo2.vin[0].prevout.n = 0;
-    txTo2.vin[0].prevout.hash = txFrom2.GetHash();
-    txTo2.vin[0].scriptSig = CScript() << op1Serialized << recurse3Serialized << recurse3Serialized;
-    txTo2.vout[0].nValue = 1;
-
-    int nUnused2 = 0;
-    BOOST_CHECK(!VerifyScript(txTo2.vin[0].scriptSig, txFrom2.vout[0].scriptPubKey, txTo2, 0, nUnused2, 0, true));
-    BOOST_CHECK(!VerifySignature(txFrom2, txTo2, 0, nUnused2, true));
-}
-
-BOOST_AUTO_TEST_CASE(script_op_eval3)
-{
-    // Test the CScript::Set* methods
-    CBasicKeyStore keystore;
-    CKey key[4];
-    std::vector<CKey> keys;
-    for (int i = 0; i < 4; i++)
-    {
-        key[i].MakeNewKey();
-        keystore.AddKey(key[i]);
-        keys.push_back(key[i]);
-    }
-
-    CScript inner[4];
-    inner[0].SetBitcoinAddress(key[0].GetPubKey());
-    inner[1].SetMultisig(2, std::vector<CKey>(keys.begin(), keys.begin()+2));
-    inner[2].SetMultisig(1, std::vector<CKey>(keys.begin(), keys.begin()+2));
-    inner[3].SetMultisig(2, std::vector<CKey>(keys.begin(), keys.begin()+3));
-
-    CScript outer[4];
-    for (int i = 0; i < 4; i++)
-    {
-        outer[i].SetEval(inner[i]);
-        keystore.AddCScript(Hash160(inner[i]), inner[i]);
-    }
-
-    CTransaction txFrom;  // Funding transaction:
-    txFrom.vout.resize(4);
-    for (int i = 0; i < 4; i++)
-    {
-        txFrom.vout[i].scriptPubKey = outer[i];
-    }
-    BOOST_CHECK(txFrom.IsStandard());
-
-    CTransaction txTo[4]; // Spending transactions
-    for (int i = 0; i < 4; i++)
-    {
-        txTo[i].vin.resize(1);
-        txTo[i].vout.resize(1);
-        txTo[i].vin[0].prevout.n = i;
-        txTo[i].vin[0].prevout.hash = txFrom.GetHash();
-        txTo[i].vout[0].nValue = 1;
-        txTo[i].vout[0].scriptPubKey = inner[i];
-        BOOST_CHECK_MESSAGE(IsMine(keystore, txFrom.vout[i].scriptPubKey), strprintf("IsMine %d", i));
-    }
-    for (int i = 0; i < 4; i++)
-    {
-        BOOST_CHECK_MESSAGE(SignSignature(keystore, txFrom, txTo[i], 0), strprintf("SignSignature %d", i));
-        BOOST_CHECK_MESSAGE(txTo[i].IsStandard(), strprintf("txTo[%d].IsStandard", i));
-    }
-}
-
-BOOST_AUTO_TEST_CASE(script_op_eval_backcompat1)
-{
-    // Check backwards-incompatibility-testing code
-    CScript returnsEleven;
-    returnsEleven << OP_11;
-
-    // This should validate on new clients, but will
-    // be invalid on old clients (that interpret OP_EVAL as a no-op)
-    //  ... except there's a special rule that makes new clients reject
-    // it.
-    CScript fund;
-    fund << OP_EVAL << OP_11 << OP_EQUAL;
-
-    CTransaction txFrom;  // Funding transaction:
-    txFrom.vout.resize(1);
-    txFrom.vout[0].scriptPubKey = fund;
-
-    CTransaction txTo;
-    txTo.vin.resize(1);
-    txTo.vout.resize(1);
-    txTo.vin[0].prevout.n = 0;
-    txTo.vin[0].prevout.hash = txFrom.GetHash();
-    txTo.vin[0].scriptSig = CScript() << static_cast<std::vector<unsigned char> >(returnsEleven);
-    txTo.vout[0].nValue = 1;
-
-    int nUnused = 0;
-    BOOST_CHECK(!VerifyScript(txTo.vin[0].scriptSig, txFrom.vout[0].scriptPubKey, txTo, 0, nUnused, 0, true));
-    BOOST_CHECK(!VerifySignature(txFrom, txTo, 0, nUnused, true));
-}
-
-BOOST_AUTO_TEST_CASE(script_op_eval_switchover)
-{
-    // Test OP_EVAL switchover code
-    CScript notValid;
-    notValid << OP_11 << OP_12 << OP_EQUALVERIFY;
-
-    // This will be valid under old rules, invalid under new:
-    CScript fund;
-    fund << OP_EVAL;
-
-    CTransaction txFrom;  // Funding transaction:
-    txFrom.vout.resize(1);
-    txFrom.vout[0].scriptPubKey = fund;
-
-    CTransaction txTo;
-    txTo.vin.resize(1);
-    txTo.vout.resize(1);
-    txTo.vin[0].prevout.n = 0;
-    txTo.vin[0].prevout.hash = txFrom.GetHash();
-    txTo.vin[0].scriptSig = CScript() << static_cast<std::vector<unsigned char> >(notValid);
-    txTo.vout[0].nValue = 1;
-
-    int nUnused = 0;
-    BOOST_CHECK(VerifyScript(txTo.vin[0].scriptSig, txFrom.vout[0].scriptPubKey, txTo, 0, nUnused, 0, false));
-
-    // Under strict op_eval switchover, it should be considered invalid:
-    BOOST_CHECK(!VerifyScript(txTo.vin[0].scriptSig, txFrom.vout[0].scriptPubKey, txTo, 0, nUnused, 0, true));
-}
-
-BOOST_AUTO_TEST_SUITE_END()
index 22885a6..79dd7f1 100644 (file)
@@ -7,8 +7,8 @@
 
 using namespace std;
 extern uint256 SignatureHash(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType);
-extern bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn, int& nSigOps,
-                         int nHashType, bool fStrictOpEval);
+extern bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
+                         bool fValidatePayToScriptHash, int nHashType);
 
 BOOST_AUTO_TEST_SUITE(script_tests)
 
@@ -21,21 +21,19 @@ BOOST_AUTO_TEST_CASE(script_PushData)
     static const unsigned char pushdata2[] = { OP_PUSHDATA2, 1, 0, 0x5a };
     static const unsigned char pushdata4[] = { OP_PUSHDATA4, 1, 0, 0, 0, 0x5a };
 
-    int nUnused = 0;
-
     vector<vector<unsigned char> > directStack;
-    BOOST_CHECK(EvalScript(directStack, CScript(&direct[0], &direct[sizeof(direct)]), CTransaction(), 0, 0, true, nUnused));
+    BOOST_CHECK(EvalScript(directStack, CScript(&direct[0], &direct[sizeof(direct)]), CTransaction(), 0, 0));
 
     vector<vector<unsigned char> > pushdata1Stack;
-    BOOST_CHECK(EvalScript(pushdata1Stack, CScript(&pushdata1[0], &pushdata1[sizeof(pushdata1)]), CTransaction(), 0, 0, true, nUnused));
+    BOOST_CHECK(EvalScript(pushdata1Stack, CScript(&pushdata1[0], &pushdata1[sizeof(pushdata1)]), CTransaction(), 0, 0));
     BOOST_CHECK(pushdata1Stack == directStack);
 
     vector<vector<unsigned char> > pushdata2Stack;
-    BOOST_CHECK(EvalScript(pushdata2Stack, CScript(&pushdata2[0], &pushdata2[sizeof(pushdata2)]), CTransaction(), 0, 0, true, nUnused));
+    BOOST_CHECK(EvalScript(pushdata2Stack, CScript(&pushdata2[0], &pushdata2[sizeof(pushdata2)]), CTransaction(), 0, 0));
     BOOST_CHECK(pushdata2Stack == directStack);
 
     vector<vector<unsigned char> > pushdata4Stack;
-    BOOST_CHECK(EvalScript(pushdata4Stack, CScript(&pushdata4[0], &pushdata4[sizeof(pushdata4)]), CTransaction(), 0, 0, true, nUnused));
+    BOOST_CHECK(EvalScript(pushdata4Stack, CScript(&pushdata4[0], &pushdata4[sizeof(pushdata4)]), CTransaction(), 0, 0));
     BOOST_CHECK(pushdata4Stack == directStack);
 }
 
@@ -73,7 +71,6 @@ sign_multisig(CScript scriptPubKey, CKey key, CTransaction transaction)
 
 BOOST_AUTO_TEST_CASE(script_CHECKMULTISIG12)
 {
-    int nUnused = 0;
     CKey key1, key2, key3;
     key1.MakeNewKey();
     key2.MakeNewKey();
@@ -94,20 +91,19 @@ BOOST_AUTO_TEST_CASE(script_CHECKMULTISIG12)
     txTo12.vout[0].nValue = 1;
 
     CScript goodsig1 = sign_multisig(scriptPubKey12, key1, txTo12);
-    BOOST_CHECK(VerifyScript(goodsig1, scriptPubKey12, txTo12, 0, nUnused, 0, true));
+    BOOST_CHECK(VerifyScript(goodsig1, scriptPubKey12, txTo12, 0, true, 0));
     txTo12.vout[0].nValue = 2;
-    BOOST_CHECK(!VerifyScript(goodsig1, scriptPubKey12, txTo12, 0, nUnused, 0, true));
+    BOOST_CHECK(!VerifyScript(goodsig1, scriptPubKey12, txTo12, 0, true, 0));
 
     CScript goodsig2 = sign_multisig(scriptPubKey12, key2, txTo12);
-    BOOST_CHECK(VerifyScript(goodsig2, scriptPubKey12, txTo12, 0, nUnused, 0, true));
+    BOOST_CHECK(VerifyScript(goodsig2, scriptPubKey12, txTo12, 0, true, 0));
 
     CScript badsig1 = sign_multisig(scriptPubKey12, key3, txTo12);
-    BOOST_CHECK(!VerifyScript(badsig1, scriptPubKey12, txTo12, 0, nUnused, 0, true));
+    BOOST_CHECK(!VerifyScript(badsig1, scriptPubKey12, txTo12, 0, true, 0));
 }
 
 BOOST_AUTO_TEST_CASE(script_CHECKMULTISIG23)
 {
-    int nUnused = 0;
     CKey key1, key2, key3, key4;
     key1.MakeNewKey();
     key2.MakeNewKey();
@@ -131,46 +127,46 @@ BOOST_AUTO_TEST_CASE(script_CHECKMULTISIG23)
     std::vector<CKey> keys;
     keys.push_back(key1); keys.push_back(key2);
     CScript goodsig1 = sign_multisig(scriptPubKey23, keys, txTo23);
-    BOOST_CHECK(VerifyScript(goodsig1, scriptPubKey23, txTo23, 0, nUnused, 0, true));
+    BOOST_CHECK(VerifyScript(goodsig1, scriptPubKey23, txTo23, 0, true, 0));
 
     keys.clear();
     keys.push_back(key1); keys.push_back(key3);
     CScript goodsig2 = sign_multisig(scriptPubKey23, keys, txTo23);
-    BOOST_CHECK(VerifyScript(goodsig2, scriptPubKey23, txTo23, 0, nUnused, 0, true));
+    BOOST_CHECK(VerifyScript(goodsig2, scriptPubKey23, txTo23, 0, true, 0));
 
     keys.clear();
     keys.push_back(key2); keys.push_back(key3);
     CScript goodsig3 = sign_multisig(scriptPubKey23, keys, txTo23);
-    BOOST_CHECK(VerifyScript(goodsig3, scriptPubKey23, txTo23, 0, nUnused, 0, true));
+    BOOST_CHECK(VerifyScript(goodsig3, scriptPubKey23, txTo23, 0, true, 0));
 
     keys.clear();
     keys.push_back(key2); keys.push_back(key2); // Can't re-use sig
     CScript badsig1 = sign_multisig(scriptPubKey23, keys, txTo23);
-    BOOST_CHECK(!VerifyScript(badsig1, scriptPubKey23, txTo23, 0, nUnused, 0, true));
+    BOOST_CHECK(!VerifyScript(badsig1, scriptPubKey23, txTo23, 0, true, 0));
 
     keys.clear();
     keys.push_back(key2); keys.push_back(key1); // sigs must be in correct order
     CScript badsig2 = sign_multisig(scriptPubKey23, keys, txTo23);
-    BOOST_CHECK(!VerifyScript(badsig2, scriptPubKey23, txTo23, 0, nUnused, 0, true));
+    BOOST_CHECK(!VerifyScript(badsig2, scriptPubKey23, txTo23, 0, true, 0));
 
     keys.clear();
     keys.push_back(key3); keys.push_back(key2); // sigs must be in correct order
     CScript badsig3 = sign_multisig(scriptPubKey23, keys, txTo23);
-    BOOST_CHECK(!VerifyScript(badsig3, scriptPubKey23, txTo23, 0, nUnused, 0, true));
+    BOOST_CHECK(!VerifyScript(badsig3, scriptPubKey23, txTo23, 0, true, 0));
 
     keys.clear();
     keys.push_back(key4); keys.push_back(key2); // sigs must match pubkeys
     CScript badsig4 = sign_multisig(scriptPubKey23, keys, txTo23);
-    BOOST_CHECK(!VerifyScript(badsig4, scriptPubKey23, txTo23, 0, nUnused, 0, true));
+    BOOST_CHECK(!VerifyScript(badsig4, scriptPubKey23, txTo23, 0, true, 0));
 
     keys.clear();
     keys.push_back(key1); keys.push_back(key4); // sigs must match pubkeys
     CScript badsig5 = sign_multisig(scriptPubKey23, keys, txTo23);
-    BOOST_CHECK(!VerifyScript(badsig5, scriptPubKey23, txTo23, 0, nUnused, 0, true));
+    BOOST_CHECK(!VerifyScript(badsig5, scriptPubKey23, txTo23, 0, true, 0));
 
     keys.clear(); // Must have signatures
     CScript badsig6 = sign_multisig(scriptPubKey23, keys, txTo23);
-    BOOST_CHECK(!VerifyScript(badsig6, scriptPubKey23, txTo23, 0, nUnused, 0, true));
+    BOOST_CHECK(!VerifyScript(badsig6, scriptPubKey23, txTo23, 0, true, 0));
 }    
 
 
diff --git a/src/test/sigopcount_tests.cpp b/src/test/sigopcount_tests.cpp
new file mode 100644 (file)
index 0000000..0b0a4a6
--- /dev/null
@@ -0,0 +1,60 @@
+#include <vector>
+#include <boost/test/unit_test.hpp>
+#include <boost/foreach.hpp>
+
+#include "script.h"
+#include "key.h"
+
+using namespace std;
+
+// Helpers:
+static std::vector<unsigned char>
+Serialize(const CScript& s)
+{
+    std::vector<unsigned char> sSerialized(s);
+    return sSerialized;
+}
+
+BOOST_AUTO_TEST_SUITE(sigopcount_tests)
+
+BOOST_AUTO_TEST_CASE(GetSigOpCount)
+{
+    // Test CScript::GetSigOpCount()
+    CScript s1;
+    BOOST_CHECK_EQUAL(s1.GetSigOpCount(false), 0);
+    BOOST_CHECK_EQUAL(s1.GetSigOpCount(true), 0);
+
+    uint160 dummy;
+    s1 << OP_1 << dummy << dummy << OP_2 << OP_CHECKMULTISIG;
+    BOOST_CHECK_EQUAL(s1.GetSigOpCount(true), 2);
+    s1 << OP_IF << OP_CHECKSIG << OP_ENDIF;
+    BOOST_CHECK_EQUAL(s1.GetSigOpCount(true), 3);
+    BOOST_CHECK_EQUAL(s1.GetSigOpCount(false), 21);
+
+    CScript p2sh;
+    p2sh.SetPayToScriptHash(s1);
+    CScript scriptSig;
+    scriptSig << OP_0 << Serialize(s1);
+    BOOST_CHECK_EQUAL(p2sh.GetSigOpCount(scriptSig), 3);
+
+    std::vector<CKey> keys;
+    for (int i = 0; i < 3; i++)
+    {
+        CKey k;
+        k.MakeNewKey();
+        keys.push_back(k);
+    }
+    CScript s2;
+    s2.SetMultisig(1, keys);
+    BOOST_CHECK_EQUAL(s2.GetSigOpCount(true), 3);
+    BOOST_CHECK_EQUAL(s2.GetSigOpCount(false), 20);
+
+    p2sh.SetPayToScriptHash(s2);
+    BOOST_CHECK_EQUAL(p2sh.GetSigOpCount(true), 0);
+    BOOST_CHECK_EQUAL(p2sh.GetSigOpCount(false), 0);
+    CScript scriptSig2;
+    scriptSig2 << OP_1 << dummy << dummy << Serialize(s2);
+    BOOST_CHECK_EQUAL(p2sh.GetSigOpCount(scriptSig2), 3);
+}
+
+BOOST_AUTO_TEST_SUITE_END()
index 4b52b74..7ff7545 100644 (file)
@@ -4,18 +4,24 @@
 #include "main.h"
 #include "wallet.h"
 
+CWallet* pwalletMain;
+
 extern bool fPrintToConsole;
 struct TestingSetup {
     TestingSetup() {
         fPrintToConsole = true; // don't want to write to debug.log file
+        pwalletMain = new CWallet();
+        RegisterWallet(pwalletMain);
+    }
+    ~TestingSetup()
+    {
+        delete pwalletMain;
+        pwalletMain = NULL;
     }
-    ~TestingSetup() { }
 };
 
 BOOST_GLOBAL_FIXTURE(TestingSetup);
 
-CWallet* pwalletMain;
-
 void Shutdown(void* parg)
 {
   exit(0);
index 3268343..592fe3f 100644 (file)
@@ -22,4 +22,87 @@ BOOST_AUTO_TEST_CASE(basic_transaction_tests)
     BOOST_CHECK_MESSAGE(!tx.CheckTransaction(), "Transaction with duplicate txins should be invalid.");
 }
 
+//
+// Helper: create two dummy transactions, each with
+// two outputs.  The first has 11 and 50 CENT outputs,
+// the second 21 and 22 CENT outputs.
+//
+static std::vector<CTransaction>
+SetupDummyInputs(CBasicKeyStore& keystoreRet, MapPrevTx& inputsRet)
+{
+    std::vector<CTransaction> dummyTransactions;
+    dummyTransactions.resize(2);
+
+    // Add some keys to the keystore:
+    CKey key[4];
+    for (int i = 0; i < 4; i++)
+    {
+        key[i].MakeNewKey();
+        keystoreRet.AddKey(key[i]);
+    }
+
+    // Create some dummy input transactions
+    dummyTransactions[0].vout.resize(2);
+    dummyTransactions[0].vout[0].nValue = 11*CENT;
+    dummyTransactions[0].vout[0].scriptPubKey.SetBitcoinAddress(key[0].GetPubKey());
+    dummyTransactions[0].vout[1].nValue = 50*CENT;
+    dummyTransactions[0].vout[1].scriptPubKey.SetBitcoinAddress(key[1].GetPubKey());
+    inputsRet[dummyTransactions[0].GetHash()] = make_pair(CTxIndex(), dummyTransactions[0]);
+
+    dummyTransactions[1].vout.resize(2);
+    dummyTransactions[1].vout[0].nValue = 21*CENT;
+    dummyTransactions[1].vout[0].scriptPubKey.SetBitcoinAddress(key[2].GetPubKey());
+    dummyTransactions[1].vout[1].nValue = 22*CENT;
+    dummyTransactions[1].vout[1].scriptPubKey.SetBitcoinAddress(key[3].GetPubKey());
+    inputsRet[dummyTransactions[1].GetHash()] = make_pair(CTxIndex(), dummyTransactions[1]);
+
+    return dummyTransactions;
+}
+
+BOOST_AUTO_TEST_CASE(test_Get)
+{
+    CBasicKeyStore keystore;
+    MapPrevTx dummyInputs;
+    std::vector<CTransaction> dummyTransactions = SetupDummyInputs(keystore, dummyInputs);
+
+    CTransaction t1;
+    t1.vin.resize(3);
+    t1.vin[0].prevout.hash = dummyTransactions[0].GetHash();
+    t1.vin[0].prevout.n = 1;
+    t1.vin[1].prevout.hash = dummyTransactions[1].GetHash();;
+    t1.vin[1].prevout.n = 0;
+    t1.vin[2].prevout.hash = dummyTransactions[1].GetHash();;
+    t1.vin[2].prevout.n = 1;
+    t1.vout.resize(2);
+    t1.vout[0].nValue = 90*CENT;
+    t1.vout[0].scriptPubKey << OP_1;
+
+    BOOST_CHECK(t1.AreInputsStandard(dummyInputs));
+    BOOST_CHECK_EQUAL(t1.GetValueIn(dummyInputs), (50+21+22)*CENT);
+}
+
+BOOST_AUTO_TEST_CASE(test_GetThrow)
+{
+    CBasicKeyStore keystore;
+    MapPrevTx dummyInputs;
+    std::vector<CTransaction> dummyTransactions = SetupDummyInputs(keystore, dummyInputs);
+
+    MapPrevTx missingInputs;
+
+    CTransaction t1;
+    t1.vin.resize(3);
+    t1.vin[0].prevout.hash = dummyTransactions[0].GetHash();
+    t1.vin[0].prevout.n = 0;
+    t1.vin[1].prevout.hash = dummyTransactions[1].GetHash();;
+    t1.vin[1].prevout.n = 0;
+    t1.vin[2].prevout.hash = dummyTransactions[1].GetHash();;
+    t1.vin[2].prevout.n = 1;
+    t1.vout.resize(2);
+    t1.vout[0].nValue = 90*CENT;
+    t1.vout[0].scriptPubKey << OP_1;
+
+    BOOST_CHECK_THROW(t1.AreInputsStandard(missingInputs), runtime_error);
+    BOOST_CHECK_THROW(t1.GetValueIn(missingInputs), runtime_error);
+}
+
 BOOST_AUTO_TEST_SUITE_END()
index 9571c47..94c0c77 100644 (file)
@@ -232,4 +232,19 @@ BOOST_AUTO_TEST_CASE(util_ParseMoney)
     BOOST_CHECK(!ParseMoney("92233720368.54775808", ret));
 }
 
+BOOST_AUTO_TEST_CASE(util_IsHex)
+{
+    BOOST_CHECK(IsHex("00"));
+    BOOST_CHECK(IsHex("00112233445566778899aabbccddeeffAABBCCDDEEFF"));
+    BOOST_CHECK(IsHex("ff"));
+    BOOST_CHECK(IsHex("FF"));
+
+    BOOST_CHECK(!IsHex(""));
+    BOOST_CHECK(!IsHex("0"));
+    BOOST_CHECK(!IsHex("a"));
+    BOOST_CHECK(!IsHex("eleven"));
+    BOOST_CHECK(!IsHex("00xx00"));
+    BOOST_CHECK(!IsHex("0x0000"));
+}
+
 BOOST_AUTO_TEST_SUITE_END()
index d3da1f2..0d27408 100644 (file)
@@ -623,7 +623,7 @@ inline const uint256 operator-(const uint256& a, const uint256& b)      { return
 
 
 
-
+#ifdef TEST_UINT256
 
 inline int Testuint256AdHoc(std::vector<std::string> vArg)
 {
@@ -756,3 +756,5 @@ inline int Testuint256AdHoc(std::vector<std::string> vArg)
 }
 
 #endif
+
+#endif
index 3805e07..6a4c2a2 100644 (file)
@@ -400,26 +400,36 @@ bool ParseMoney(const char* pszIn, int64& nRet)
 }
 
 
-vector<unsigned char> ParseHex(const char* psz)
+static char phexdigit[256] =
+{ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
+  -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
+  -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
+  0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
+  -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
+  -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
+  -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1
+  -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
+  -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
+  -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
+  -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
+  -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
+  -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
+  -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
+  -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
+  -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };
+
+bool IsHex(const string& str)
 {
-    static char phexdigit[256] =
-    { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-      -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-      -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-      0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
-      -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-      -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-      -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1
-      -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-      -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-      -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-      -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-      -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-      -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-      -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-      -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-      -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };
+    BOOST_FOREACH(unsigned char c, str)
+    {
+        if (phexdigit[c] < 0)
+            return false;
+    }
+    return (str.size() > 0) && (str.size()%2 == 0);
+}
 
+vector<unsigned char> ParseHex(const char* psz)
+{
     // convert hex dump to vector
     vector<unsigned char> vch;
     loop
@@ -948,12 +958,12 @@ int64 GetAdjustedTime()
     return GetTime() + nTimeOffset;
 }
 
-void AddTimeData(unsigned int ip, int64 nTime)
+void AddTimeData(const CNetAddr& ip, int64 nTime)
 {
     int64 nOffsetSample = nTime - GetTime();
 
     // Ignore duplicates
-    static set<unsigned int> setKnown;
+    static set<CNetAddr> setKnown;
     if (!setKnown.insert(ip).second)
         return;
 
@@ -1008,7 +1018,6 @@ void AddTimeData(unsigned int ip, int64 nTime)
 
 
 
-
 string FormatVersion(int nVersion)
 {
     if (nVersion%100 == 0)
@@ -1144,7 +1153,18 @@ static void pop_lock()
 void CCriticalSection::Enter(const char* pszName, const char* pszFile, int nLine)
 {
     push_lock(this, CLockLocation(pszName, pszFile, nLine));
+#ifdef DEBUG_LOCKCONTENTION
+    bool result = mutex.try_lock();
+    if (!result)
+    {
+        printf("LOCKCONTENTION: %s\n", pszName);
+        printf("Locker: %s:%d\n", pszFile, nLine);
+        mutex.lock();
+        printf("Locked\n");
+    }
+#else
     mutex.lock();
+#endif
 }
 void CCriticalSection::Leave()
 {
@@ -1161,9 +1181,19 @@ bool CCriticalSection::TryEnter(const char* pszName, const char* pszFile, int nL
 
 #else
 
-void CCriticalSection::Enter(const char*, const char*, int)
+void CCriticalSection::Enter(const char* pszName, const char* pszFile, int nLine)
 {
+#ifdef DEBUG_LOCKCONTENTION
+    bool result = mutex.try_lock();
+    if (!result)
+    {
+        printf("LOCKCONTENTION: %s\n", pszName);
+        printf("Locker: %s:%d\n", pszFile, nLine);
+        mutex.lock();
+    }
+#else
     mutex.lock();
+#endif
 }
 
 void CCriticalSection::Leave()
@@ -1178,3 +1208,4 @@ bool CCriticalSection::TryEnter(const char*, const char*, int)
 }
 
 #endif /* DEBUG_LOCKORDER */
+
index 48fea02..19f0652 100644 (file)
@@ -24,6 +24,7 @@
 #include <openssl/sha.h>
 #include <openssl/ripemd.h>
 
+#include "netbase.h"
 
 typedef long long  int64;
 typedef unsigned long long  uint64;
@@ -79,20 +80,7 @@ T* alignup(T* p)
 #define S_IWUSR             0200
 #endif
 #define unlink              _unlink
-typedef int socklen_t;
 #else
-#define WSAGetLastError()   errno
-#define WSAEINVAL           EINVAL
-#define WSAEALREADY         EALREADY
-#define WSAEWOULDBLOCK      EWOULDBLOCK
-#define WSAEMSGSIZE         EMSGSIZE
-#define WSAEINTR            EINTR
-#define WSAEINPROGRESS      EINPROGRESS
-#define WSAEADDRINUSE       EADDRINUSE
-#define WSAENOTSOCK         EBADF
-#define INVALID_SOCKET      (SOCKET)(~0)
-#define SOCKET_ERROR        -1
-typedef u_int SOCKET;
 #define _vsnprintf(a,b,c,d) vsnprintf(a,b,c,d)
 #define strlwr(psz)         to_lower(psz)
 #define _strlwr(psz)        to_lower(psz)
@@ -104,19 +92,6 @@ inline void Sleep(int64 n)
 }
 #endif
 
-inline int myclosesocket(SOCKET& hSocket)
-{
-    if (hSocket == INVALID_SOCKET)
-        return WSAENOTSOCK;
-#ifdef WIN32
-    int ret = closesocket(hSocket);
-#else
-    int ret = close(hSocket);
-#endif
-    hSocket = INVALID_SOCKET;
-    return ret;
-}
-#define closesocket(s)      myclosesocket(s)
 #if !defined(QT_GUI)
 inline const char* _(const char* psz)
 {
@@ -163,6 +138,7 @@ bool ParseMoney(const std::string& str, int64& nRet);
 bool ParseMoney(const char* pszIn, int64& nRet);
 std::vector<unsigned char> ParseHex(const char* psz);
 std::vector<unsigned char> ParseHex(const std::string& str);
+bool IsHex(const std::string& str);
 std::vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid = NULL);
 std::string DecodeBase64(const std::string& str);
 std::string EncodeBase64(const unsigned char* pch, size_t len);
@@ -187,9 +163,9 @@ uint64 GetRand(uint64 nMax);
 int64 GetTime();
 void SetMockTime(int64 nMockTimeIn);
 int64 GetAdjustedTime();
-void AddTimeData(unsigned int ip, int64 nTime);
 std::string FormatFullVersion();
 std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments);
+void AddTimeData(const CNetAddr& ip, int64 nTime);
 
 
 
@@ -740,8 +716,9 @@ inline bool AffinityBugWorkaround(void(*pfn)(void*))
 
 inline uint32_t ByteReverse(uint32_t value)
 {
-       value = ((value & 0xFF00FF00) >> 8) | ((value & 0x00FF00FF) << 8);
-       return (value<<16) | (value>>16);
+    value = ((value & 0xFF00FF00) >> 8) | ((value & 0x00FF00FF) << 8);
+    return (value<<16) | (value>>16);
 }
 
 #endif
+
index 28d15ef..a196044 100644 (file)
@@ -42,13 +42,13 @@ bool CWallet::AddCryptedKey(const vector<unsigned char> &vchPubKey, const vector
     return false;
 }
 
-bool CWallet::AddCScript(const uint160 &hash, const CScript& redeemScript)
+bool CWallet::AddCScript(const CScript& redeemScript)
 {
-    if (!CCryptoKeyStore::AddCScript(hash, redeemScript))
+    if (!CCryptoKeyStore::AddCScript(redeemScript))
         return false;
     if (!fFileBacked)
         return true;
-    return CWalletDB(strWalletFile).WriteCScript(hash, redeemScript);
+    return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
 }
 
 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
index a7d07c9..1132104 100644 (file)
@@ -70,8 +70,8 @@ public:
     bool AddCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
     // Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
     bool LoadCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret); }
-    bool AddCScript(const uint160& hash, const CScript& redeemScript);
-    bool LoadCScript(const uint160& hash, const CScript& redeemScript) { return CCryptoKeyStore::AddCScript(hash, redeemScript); }
+    bool AddCScript(const CScript& redeemScript);
+    bool LoadCScript(const CScript& redeemScript) { return CCryptoKeyStore::AddCScript(redeemScript); }
 
     bool Unlock(const SecureString& strWalletPassphrase);
     bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
@@ -91,7 +91,6 @@ public:
     bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
     bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
     bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
-    bool BroadcastTransaction(CWalletTx& wtxNew);
     std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
     std::string SendMoneyToBitcoinAddress(const CBitcoinAddress& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);