diff options
Diffstat (limited to 'src')
75 files changed, 1460 insertions, 1299 deletions
diff --git a/src/Makefile.am b/src/Makefile.am index 1f8f9aabdc..8253c4ab14 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -80,7 +80,9 @@ BITCOIN_CORE_H = \ coincontrol.h \ coins.h \ compat.h \ - core.h \ + compressor.h \ + core/block.h \ + core/transaction.h \ core_io.h \ crypter.h \ db.h \ @@ -103,7 +105,6 @@ BITCOIN_CORE_H = \ rpcclient.h \ rpcprotocol.h \ rpcserver.h \ - script/compressor.h \ script/interpreter.h \ script/script.h \ script/sigcache.h \ @@ -119,6 +120,7 @@ BITCOIN_CORE_H = \ txmempool.h \ ui_interface.h \ uint256.h \ + undo.h \ util.h \ utilstrencodings.h \ utilmoneystr.h \ @@ -144,7 +146,7 @@ obj/build.h: FORCE @$(MKDIR_P) $(builddir)/obj @$(top_srcdir)/share/genbuild.sh $(abs_top_builddir)/src/obj/build.h \ $(abs_top_srcdir) -libbitcoin_util_a-version.$(OBJEXT): obj/build.h +libbitcoin_util_a-clientversion.$(OBJEXT): obj/build.h # server: shared between bitcoind and bitcoin-qt libbitcoin_server_a_CPPFLAGS = $(BITCOIN_INCLUDES) $(MINIUPNPC_CPPFLAGS) @@ -209,10 +211,13 @@ univalue_libbitcoin_univalue_a_SOURCES = \ libbitcoin_common_a_CPPFLAGS = $(BITCOIN_INCLUDES) libbitcoin_common_a_SOURCES = \ allocators.cpp \ + amount.cpp \ base58.cpp \ chainparams.cpp \ coins.cpp \ - core.cpp \ + compressor.cpp \ + core/block.cpp \ + core/transaction.cpp \ core_read.cpp \ core_write.cpp \ ecwrapper.cpp \ @@ -221,7 +226,6 @@ libbitcoin_common_a_SOURCES = \ keystore.cpp \ netbase.cpp \ protocol.cpp \ - script/compressor.cpp \ script/interpreter.cpp \ script/script.cpp \ script/sigcache.cpp \ @@ -237,6 +241,7 @@ libbitcoin_util_a_SOURCES = \ compat/glibc_sanity.cpp \ compat/glibcxx_sanity.cpp \ chainparamsbase.cpp \ + clientversion.cpp \ random.cpp \ rpcprotocol.cpp \ sync.cpp \ @@ -245,7 +250,6 @@ libbitcoin_util_a_SOURCES = \ utilstrencodings.cpp \ utilmoneystr.cpp \ utiltime.cpp \ - version.cpp \ $(BITCOIN_CORE_H) if GLIBC_BACK_COMPAT @@ -350,7 +354,7 @@ clean-local: .rc.o: @test -f $(WINDRES) - $(AM_V_GEN) $(WINDRES) -i $< -o $@ + $(AM_V_GEN) $(WINDRES) -DWINDRES_PREPROC -i $< -o $@ .mm.o: $(AM_V_CXX) $(OBJCXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ diff --git a/src/alert.cpp b/src/alert.cpp index d495849206..f16898dc38 100644 --- a/src/alert.cpp +++ b/src/alert.cpp @@ -6,6 +6,7 @@ #include "alert.h" #include "chainparams.h" +#include "clientversion.h" #include "key.h" #include "net.h" #include "timedata.h" diff --git a/src/amount.cpp b/src/amount.cpp new file mode 100644 index 0000000000..e6f5b7d440 --- /dev/null +++ b/src/amount.cpp @@ -0,0 +1,31 @@ +// Copyright (c) 2009-2010 Satoshi Nakamoto +// Copyright (c) 2009-2014 The Bitcoin developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include "amount.h" + +#include "tinyformat.h" + +CFeeRate::CFeeRate(const CAmount& nFeePaid, size_t nSize) +{ + if (nSize > 0) + nSatoshisPerK = nFeePaid*1000/nSize; + else + nSatoshisPerK = 0; +} + +CAmount CFeeRate::GetFee(size_t nSize) const +{ + CAmount nFee = nSatoshisPerK*nSize / 1000; + + if (nFee == 0 && nSatoshisPerK > 0) + nFee = nSatoshisPerK; + + return nFee; +} + +std::string CFeeRate::ToString() const +{ + return strprintf("%d.%08d BTC/kB", nSatoshisPerK / COIN, nSatoshisPerK % COIN); +} diff --git a/src/amount.h b/src/amount.h index 831fa1f6ca..c0d37954cb 100644 --- a/src/amount.h +++ b/src/amount.h @@ -6,8 +6,49 @@ #ifndef BITCOIN_AMOUNT_H #define BITCOIN_AMOUNT_H -#include <stdint.h> +#include "serialize.h" + +#include <stdlib.h> +#include <string> typedef int64_t CAmount; +static const CAmount COIN = 100000000; +static const CAmount CENT = 1000000; + +/** No amount larger than this (in satoshi) is valid */ +static const CAmount MAX_MONEY = 21000000 * COIN; +inline bool MoneyRange(const CAmount& nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); } + +/** Type-safe wrapper class to for fee rates + * (how much to pay based on transaction size) + */ +class CFeeRate +{ +private: + CAmount nSatoshisPerK; // unit is satoshis-per-1,000-bytes +public: + CFeeRate() : nSatoshisPerK(0) { } + explicit CFeeRate(const CAmount& _nSatoshisPerK): nSatoshisPerK(_nSatoshisPerK) { } + CFeeRate(const CAmount& nFeePaid, size_t nSize); + CFeeRate(const CFeeRate& other) { nSatoshisPerK = other.nSatoshisPerK; } + + CAmount GetFee(size_t size) const; // unit returned is satoshis + CAmount GetFeePerK() const { return GetFee(1000); } // satoshis-per-1000-bytes + + friend bool operator<(const CFeeRate& a, const CFeeRate& b) { return a.nSatoshisPerK < b.nSatoshisPerK; } + friend bool operator>(const CFeeRate& a, const CFeeRate& b) { return a.nSatoshisPerK > b.nSatoshisPerK; } + friend bool operator==(const CFeeRate& a, const CFeeRate& b) { return a.nSatoshisPerK == b.nSatoshisPerK; } + friend bool operator<=(const CFeeRate& a, const CFeeRate& b) { return a.nSatoshisPerK <= b.nSatoshisPerK; } + friend bool operator>=(const CFeeRate& a, const CFeeRate& b) { return a.nSatoshisPerK >= b.nSatoshisPerK; } + std::string ToString() const; + + ADD_SERIALIZE_METHODS; + + template <typename Stream, typename Operation> + inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { + READWRITE(nSatoshisPerK); + } +}; + #endif // BITCOIN_AMOUNT_H diff --git a/src/bitcoin-cli.cpp b/src/bitcoin-cli.cpp index aa5e285b10..38fbc29faf 100644 --- a/src/bitcoin-cli.cpp +++ b/src/bitcoin-cli.cpp @@ -4,12 +4,12 @@ // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "chainparamsbase.h" +#include "clientversion.h" #include "init.h" #include "rpcclient.h" #include "rpcprotocol.h" #include "util.h" #include "utilstrencodings.h" -#include "version.h" #include <boost/filesystem/operations.hpp> diff --git a/src/bitcoin-tx.cpp b/src/bitcoin-tx.cpp index da37e60c7f..c0d21ed36f 100644 --- a/src/bitcoin-tx.cpp +++ b/src/bitcoin-tx.cpp @@ -3,7 +3,8 @@ // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "base58.h" -#include "core.h" +#include "clientversion.h" +#include "core/transaction.h" #include "core_io.h" #include "keystore.h" #include "main.h" // for MAX_BLOCK_SIZE diff --git a/src/bitcoind.cpp b/src/bitcoind.cpp index 0737b5a83d..a79e581a80 100644 --- a/src/bitcoind.cpp +++ b/src/bitcoind.cpp @@ -3,6 +3,7 @@ // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. +#include "clientversion.h" #include "rpcserver.h" #include "init.h" #include "main.h" diff --git a/src/bloom.cpp b/src/bloom.cpp index cac71fdbbf..c1e7aeb3bf 100644 --- a/src/bloom.cpp +++ b/src/bloom.cpp @@ -4,7 +4,7 @@ #include "bloom.h" -#include "core.h" +#include "core/transaction.h" #include "script/script.h" #include "script/standard.h" #include "streams.h" diff --git a/src/chain.cpp b/src/chain.cpp index 56ed22ce71..e13c047861 100644 --- a/src/chain.cpp +++ b/src/chain.cpp @@ -7,8 +7,9 @@ using namespace std; -// CChain implementation - +/** + * CChain implementation + */ void CChain::SetTip(CBlockIndex *pindex) { if (pindex == NULL) { vChain.clear(); diff --git a/src/chain.h b/src/chain.h index 290150476e..7c5603dafc 100644 --- a/src/chain.h +++ b/src/chain.h @@ -6,7 +6,7 @@ #ifndef H_BITCOIN_CHAIN #define H_BITCOIN_CHAIN -#include "core.h" +#include "core/block.h" #include "pow.h" #include "tinyformat.h" #include "uint256.h" @@ -50,38 +50,40 @@ struct CDiskBlockPos }; enum BlockStatus { - // Unused. + //! Unused. BLOCK_VALID_UNKNOWN = 0, - // Parsed, version ok, hash satisfies claimed PoW, 1 <= vtx count <= max, timestamp not in future + //! Parsed, version ok, hash satisfies claimed PoW, 1 <= vtx count <= max, timestamp not in future BLOCK_VALID_HEADER = 1, - // All parent headers found, difficulty matches, timestamp >= median previous, checkpoint. Implies all parents - // are also at least TREE. + //! All parent headers found, difficulty matches, timestamp >= median previous, checkpoint. Implies all parents + //! are also at least TREE. BLOCK_VALID_TREE = 2, - // Only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid, no duplicate txids, - // sigops, size, merkle root. Implies all parents are at least TREE but not necessarily TRANSACTIONS. When all - // parent blocks also have TRANSACTIONS, CBlockIndex::nChainTx will be set. + /** + * Only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid, no duplicate txids, + * sigops, size, merkle root. Implies all parents are at least TREE but not necessarily TRANSACTIONS. When all + * parent blocks also have TRANSACTIONS, CBlockIndex::nChainTx will be set. + */ BLOCK_VALID_TRANSACTIONS = 3, - // Outputs do not overspend inputs, no double spends, coinbase output ok, immature coinbase spends, BIP30. - // Implies all parents are also at least CHAIN. + //! Outputs do not overspend inputs, no double spends, coinbase output ok, immature coinbase spends, BIP30. + //! Implies all parents are also at least CHAIN. BLOCK_VALID_CHAIN = 4, - // Scripts & signatures ok. Implies all parents are also at least SCRIPTS. + //! Scripts & signatures ok. Implies all parents are also at least SCRIPTS. BLOCK_VALID_SCRIPTS = 5, - // All validity bits. + //! All validity bits. BLOCK_VALID_MASK = BLOCK_VALID_HEADER | BLOCK_VALID_TREE | BLOCK_VALID_TRANSACTIONS | BLOCK_VALID_CHAIN | BLOCK_VALID_SCRIPTS, - BLOCK_HAVE_DATA = 8, // full block available in blk*.dat - BLOCK_HAVE_UNDO = 16, // undo data available in rev*.dat + BLOCK_HAVE_DATA = 8, //! full block available in blk*.dat + BLOCK_HAVE_UNDO = 16, //! undo data available in rev*.dat BLOCK_HAVE_MASK = BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO, - BLOCK_FAILED_VALID = 32, // stage after last reached validness failed - BLOCK_FAILED_CHILD = 64, // descends from failed block + BLOCK_FAILED_VALID = 32, //! stage after last reached validness failed + BLOCK_FAILED_CHILD = 64, //! descends from failed block BLOCK_FAILED_MASK = BLOCK_FAILED_VALID | BLOCK_FAILED_CHILD, }; @@ -93,49 +95,50 @@ enum BlockStatus { class CBlockIndex { public: - // pointer to the hash of the block, if any. memory is owned by this CBlockIndex + //! pointer to the hash of the block, if any. memory is owned by this CBlockIndex const uint256* phashBlock; - // pointer to the index of the predecessor of this block + //! pointer to the index of the predecessor of this block CBlockIndex* pprev; - // pointer to the index of some further predecessor of this block + //! pointer to the index of some further predecessor of this block CBlockIndex* pskip; - // height of the entry in the chain. The genesis block has height 0 + //! height of the entry in the chain. The genesis block has height 0 int nHeight; - // Which # file this block is stored in (blk?????.dat) + //! Which # file this block is stored in (blk?????.dat) int nFile; - // Byte offset within blk?????.dat where this block's data is stored + //! Byte offset within blk?????.dat where this block's data is stored unsigned int nDataPos; - // Byte offset within rev?????.dat where this block's undo data is stored + //! Byte offset within rev?????.dat where this block's undo data is stored unsigned int nUndoPos; - // (memory only) Total amount of work (expected number of hashes) in the chain up to and including this block + //! (memory only) Total amount of work (expected number of hashes) in the chain up to and including this block uint256 nChainWork; - // Number of transactions in this block. - // Note: in a potential headers-first mode, this number cannot be relied upon + //! Number of transactions in this block. + //! Note: in a potential headers-first mode, this number cannot be relied upon unsigned int nTx; - // (memory only) Number of transactions in the chain up to and including this block. - // This value will be non-zero only if and only if transactions for this block and all its parents are available. - unsigned int nChainTx; // change to 64-bit type when necessary; won't happen before 2030 + //! (memory only) Number of transactions in the chain up to and including this block. + //! This value will be non-zero only if and only if transactions for this block and all its parents are available. + //! Change to 64-bit type when necessary; won't happen before 2030 + unsigned int nChainTx; - // Verification status of this block. See enum BlockStatus + //! Verification status of this block. See enum BlockStatus unsigned int nStatus; - // block header + //! block header int nVersion; uint256 hashMerkleRoot; unsigned int nTime; unsigned int nBits; unsigned int nNonce; - // (memory only) Sequencial id assigned to distinguish order in which blocks are received. + //! (memory only) Sequential id assigned to distinguish order in which blocks are received. uint32_t nSequenceId; void SetNull() @@ -254,7 +257,7 @@ public: GetBlockHash().ToString()); } - // Check whether this block index entry is valid up to the passed validity level. + //! Check whether this block index entry is valid up to the passed validity level. bool IsValid(enum BlockStatus nUpTo = BLOCK_VALID_TRANSACTIONS) const { assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed. @@ -263,8 +266,8 @@ public: return ((nStatus & BLOCK_VALID_MASK) >= nUpTo); } - // Raise the validity level of this block index entry. - // Returns true if the validity was changed. + //! Raise the validity level of this block index entry. + //! Returns true if the validity was changed. bool RaiseValidity(enum BlockStatus nUpTo) { assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed. @@ -277,10 +280,10 @@ public: return false; } - // Build the skiplist pointer for this entry. + //! Build the skiplist pointer for this entry. void BuildSkip(); - // Efficiently find an ancestor of this block. + //! Efficiently find an ancestor of this block. CBlockIndex* GetAncestor(int height); const CBlockIndex* GetAncestor(int height) const; }; diff --git a/src/chainparams.cpp b/src/chainparams.cpp index 1ab292517a..9ffc369b40 100644 --- a/src/chainparams.cpp +++ b/src/chainparams.cpp @@ -1,6 +1,6 @@ // Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers -// Distributed under the MIT/X11 software license, see the accompanying +// Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "chainparams.h" @@ -23,11 +23,11 @@ struct SeedSpec6 { #include "chainparamsseeds.h" -// -// Main network -// +/** + * Main network + */ -// Convert the pnSeeds6 array into usable address objects. +//! Convert the pnSeeds6 array into usable address objects. static void convertSeed6(std::vector<CAddress> &vSeedsOut, const SeedSpec6 *data, unsigned int count) { // It'll only connect to one or two seed nodes because once it connects, @@ -45,11 +45,13 @@ static void convertSeed6(std::vector<CAddress> &vSeedsOut, const SeedSpec6 *data } } - // What makes a good checkpoint block? - // + Is surrounded by blocks with reasonable timestamps - // (no blocks before with a timestamp after, none after with - // timestamp before) - // + Contains no strange transactions +/** + * What makes a good checkpoint block? + * + Is surrounded by blocks with reasonable timestamps + * (no blocks before with a timestamp after, none after with + * timestamp before) + * + Contains no strange transactions + */ static Checkpoints::MapCheckpoints mapCheckpoints = boost::assign::map_list_of ( 11111, uint256("0x0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d")) @@ -101,9 +103,11 @@ public: CMainParams() { networkID = CBaseChainParams::MAIN; strNetworkID = "main"; - // The message start string is designed to be unlikely to occur in normal data. - // The characters are rarely used upper ASCII, not valid as UTF-8, and produce - // a large 4-byte int at any alignment. + /** + * The message start string is designed to be unlikely to occur in normal data. + * The characters are rarely used upper ASCII, not valid as UTF-8, and produce + * a large 4-byte int at any alignment. + */ pchMessageStart[0] = 0xf9; pchMessageStart[1] = 0xbe; pchMessageStart[2] = 0xb4; @@ -119,14 +123,16 @@ public: nTargetTimespan = 14 * 24 * 60 * 60; // two weeks nTargetSpacing = 10 * 60; - // Build the genesis block. Note that the output of the genesis coinbase cannot - // be spent as it did not originally exist in the database. - // - // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1) - // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0) - // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73) - // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B) - // vMerkleTree: 4a5e1e + /** + * Build the genesis block. Note that the output of the genesis coinbase cannot + * be spent as it did not originally exist in the database. + * + * CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1) + * CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0) + * CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73) + * CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B) + * vMerkleTree: 4a5e1e + */ const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks"; CMutableTransaction txNew; txNew.vin.resize(1); @@ -178,18 +184,19 @@ public: }; static CMainParams mainParams; -// -// Testnet (v3) -// - +/** + * Testnet (v3) + */ class CTestNetParams : public CMainParams { public: CTestNetParams() { networkID = CBaseChainParams::TESTNET; strNetworkID = "test"; - // The message start string is designed to be unlikely to occur in normal data. - // The characters are rarely used upper ASCII, not valid as UTF-8, and produce - // a large 4-byte int at any alignment. + /** + * The message start string is designed to be unlikely to occur in normal data. + * The characters are rarely used upper ASCII, not valid as UTF-8, and produce + * a large 4-byte int at any alignment. + */ pchMessageStart[0] = 0x0b; pchMessageStart[1] = 0x11; pchMessageStart[2] = 0x09; @@ -200,10 +207,10 @@ public: nRejectBlockOutdatedMajority = 75; nToCheckBlockUpgradeMajority = 100; nMinerThreads = 0; - nTargetTimespan = 14 * 24 * 60 * 60; // two weeks + nTargetTimespan = 14 * 24 * 60 * 60; //! two weeks nTargetSpacing = 10 * 60; - // Modify the testnet genesis block so the timestamp is valid for a later start. + //! Modify the testnet genesis block so the timestamp is valid for a later start. genesis.nTime = 1296688602; genesis.nNonce = 414098458; hashGenesisBlock = genesis.GetHash(); @@ -239,9 +246,9 @@ public: }; static CTestNetParams testNetParams; -// -// Regression test -// +/** + * Regression test + */ class CRegTestParams : public CTestNetParams { public: CRegTestParams() { @@ -256,7 +263,7 @@ public: nRejectBlockOutdatedMajority = 950; nToCheckBlockUpgradeMajority = 1000; nMinerThreads = 1; - nTargetTimespan = 14 * 24 * 60 * 60; // two weeks + nTargetTimespan = 14 * 24 * 60 * 60; //! two weeks nTargetSpacing = 10 * 60; bnProofOfWorkLimit = ~uint256(0) >> 1; genesis.nTime = 1296688602; @@ -266,8 +273,8 @@ public: nDefaultPort = 18444; assert(hashGenesisBlock == uint256("0x0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206")); - vFixedSeeds.clear(); // Regtest mode doesn't have any fixed seeds. - vSeeds.clear(); // Regtest mode doesn't have any DNS seeds. + vFixedSeeds.clear(); //! Regtest mode doesn't have any fixed seeds. + vSeeds.clear(); //! Regtest mode doesn't have any DNS seeds. fRequireRPCPassword = false; fMiningRequiresPeers = false; @@ -284,17 +291,17 @@ public: }; static CRegTestParams regTestParams; -// -// Unit test -// +/** + * Unit test + */ class CUnitTestParams : public CMainParams, public CModifiableParams { public: CUnitTestParams() { networkID = CBaseChainParams::UNITTEST; strNetworkID = "unittest"; nDefaultPort = 18445; - vFixedSeeds.clear(); - vSeeds.clear(); // Regtest mode doesn't have any DNS seeds. + vFixedSeeds.clear(); //! Unit test mode doesn't have any fixed seeds. + vSeeds.clear(); //! Unit test mode doesn't have any DNS seeds. fRequireRPCPassword = false; fMiningRequiresPeers = false; @@ -309,7 +316,7 @@ public: return data; } - // Published setters to allow changing values in unit test cases + //! Published setters to allow changing values in unit test cases virtual void setSubsidyHalvingInterval(int anSubsidyHalvingInterval) { nSubsidyHalvingInterval=anSubsidyHalvingInterval; } virtual void setEnforceBlockUpgradeMajority(int anEnforceBlockUpgradeMajority) { nEnforceBlockUpgradeMajority=anEnforceBlockUpgradeMajority; } virtual void setRejectBlockOutdatedMajority(int anRejectBlockOutdatedMajority) { nRejectBlockOutdatedMajority=anRejectBlockOutdatedMajority; } diff --git a/src/chainparams.h b/src/chainparams.h index f157419bb2..9279edd6c0 100644 --- a/src/chainparams.h +++ b/src/chainparams.h @@ -1,14 +1,14 @@ // Copyright (c) 2009-2010 Satoshi Nakamoto -// Copyright (c) 2009-2013 The Bitcoin developers -// Distributed under the MIT/X11 software license, see the accompanying +// Copyright (c) 2009-2014 The Bitcoin developers +// Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_CHAIN_PARAMS_H #define BITCOIN_CHAIN_PARAMS_H -#include "core.h" #include "chainparamsbase.h" #include "checkpoints.h" +#include "core/block.h" #include "protocol.h" #include "uint256.h" @@ -47,34 +47,33 @@ public: int GetDefaultPort() const { return nDefaultPort; } const uint256& ProofOfWorkLimit() const { return bnProofOfWorkLimit; } int SubsidyHalvingInterval() const { return nSubsidyHalvingInterval; } - /* Used to check majorities for block version upgrade */ + /** Used to check majorities for block version upgrade */ int EnforceBlockUpgradeMajority() const { return nEnforceBlockUpgradeMajority; } int RejectBlockOutdatedMajority() const { return nRejectBlockOutdatedMajority; } int ToCheckBlockUpgradeMajority() const { return nToCheckBlockUpgradeMajority; } - /* Used if GenerateBitcoins is called with a negative number of threads */ + /** Used if GenerateBitcoins is called with a negative number of threads */ int DefaultMinerThreads() const { return nMinerThreads; } const CBlock& GenesisBlock() const { return genesis; } bool RequireRPCPassword() const { return fRequireRPCPassword; } - /* Make miner wait to have peers to avoid wasting work */ + /** Make miner wait to have peers to avoid wasting work */ bool MiningRequiresPeers() const { return fMiningRequiresPeers; } - /* Default value for -checkmempool argument */ + /** Default value for -checkmempool argument */ bool DefaultCheckMemPool() const { return fDefaultCheckMemPool; } - /* Allow mining of a min-difficulty block */ + /** Allow mining of a min-difficulty block */ bool AllowMinDifficultyBlocks() const { return fAllowMinDifficultyBlocks; } - /* Skip proof-of-work check: allow mining of any difficulty block */ + /** Skip proof-of-work check: allow mining of any difficulty block */ bool SkipProofOfWorkCheck() const { return fSkipProofOfWorkCheck; } - /* Make standard checks */ + /** Make standard checks */ bool RequireStandard() const { return fRequireStandard; } int64_t TargetTimespan() const { return nTargetTimespan; } int64_t TargetSpacing() const { return nTargetSpacing; } int64_t Interval() const { return nTargetTimespan / nTargetSpacing; } - /* Make miner stop after a block is found. In RPC, don't return - * until nGenProcLimit blocks are generated */ + /** Make miner stop after a block is found. In RPC, don't return until nGenProcLimit blocks are generated */ bool MineBlocksOnDemand() const { return fMineBlocksOnDemand; } - /* In the future use NetworkIDString() for RPC fields */ + /** In the future use NetworkIDString() for RPC fields */ bool TestnetToBeDeprecatedFieldRPC() const { return fTestnetToBeDeprecatedFieldRPC; } - /* Return the BIP70 network string (main, test or regtest) */ + /** Return the BIP70 network string (main, test or regtest) */ std::string NetworkIDString() const { return strNetworkID; } const std::vector<CDNSSeedData>& DNSSeeds() const { return vSeeds; } const std::vector<unsigned char>& Base58Prefix(Base58Type type) const { return base58Prefixes[type]; } @@ -85,7 +84,7 @@ protected: uint256 hashGenesisBlock; MessageStartChars pchMessageStart; - // Raw pub key bytes for the broadcast alert signing key. + //! Raw pub key bytes for the broadcast alert signing key. std::vector<unsigned char> vAlertPubKey; int nDefaultPort; uint256 bnProofOfWorkLimit; @@ -112,14 +111,15 @@ protected: bool fTestnetToBeDeprecatedFieldRPC; }; -/** Modifiable parameters interface is used by test cases to adapt the parameters in order -*** to test specific features more easily. Test cases should always restore the previous -*** values after finalization. -**/ +/** + * Modifiable parameters interface is used by test cases to adapt the parameters in order + * to test specific features more easily. Test cases should always restore the previous + * values after finalization. + */ class CModifiableParams { public: - // Published setters to allow changing values in unit test cases + //! Published setters to allow changing values in unit test cases virtual void setSubsidyHalvingInterval(int anSubsidyHalvingInterval) =0; virtual void setEnforceBlockUpgradeMajority(int anEnforceBlockUpgradeMajority)=0; virtual void setRejectBlockOutdatedMajority(int anRejectBlockOutdatedMajority)=0; @@ -139,7 +139,7 @@ const CChainParams &Params(); /** Return parameters for the given network. */ CChainParams &Params(CBaseChainParams::Network network); -/** Get modifyable network parameters (UNITTEST only) */ +/** Get modifiable network parameters (UNITTEST only) */ CModifiableParams *ModifiableParams(); /** Sets the params returned by Params() to those for the given network. */ diff --git a/src/chainparamsbase.cpp b/src/chainparamsbase.cpp index 5d9ec7927b..8646a31603 100644 --- a/src/chainparamsbase.cpp +++ b/src/chainparamsbase.cpp @@ -1,6 +1,6 @@ // Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers -// Distributed under the MIT/X11 software license, see the accompanying +// Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "chainparamsbase.h" @@ -13,10 +13,9 @@ using namespace boost::assign; -// -// Main network -// - +/** + * Main network + */ class CBaseMainParams : public CBaseChainParams { public: @@ -28,9 +27,9 @@ public: }; static CBaseMainParams mainParams; -// -// Testnet (v3) -// +/** + * Testnet (v3) + */ class CBaseTestNetParams : public CBaseMainParams { public: @@ -43,9 +42,9 @@ public: }; static CBaseTestNetParams testNetParams; -// -// Regression test -// +/* + * Regression test + */ class CBaseRegTestParams : public CBaseTestNetParams { public: @@ -57,9 +56,9 @@ public: }; static CBaseRegTestParams regTestParams; -// -// Unit test -// +/* + * Unit test + */ class CBaseUnitTestParams : public CBaseMainParams { public: diff --git a/src/chainparamsbase.h b/src/chainparamsbase.h index 911d1181ac..4042b8c879 100644 --- a/src/chainparamsbase.h +++ b/src/chainparamsbase.h @@ -1,5 +1,5 @@ // Copyright (c) 2014 The Bitcoin developers -// Distributed under the MIT/X11 software license, see the accompanying +// Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_CHAIN_PARAMS_BASE_H diff --git a/src/chainparamsseeds.h b/src/chainparamsseeds.h index 3f3278361e..c3323c48bd 100644 --- a/src/chainparamsseeds.h +++ b/src/chainparamsseeds.h @@ -1,10 +1,13 @@ #ifndef H_CHAINPARAMSSEEDS #define H_CHAINPARAMSSEEDS -// List of fixed seed nodes for the bitcoin network -// AUTOGENERATED by contrib/devtools/generate-seeds.py -// Each line contains a 16-byte IPv6 address and a port. -// IPv4 as well as onion addresses are wrapped inside a IPv6 address accordingly. +/** + * List of fixed seed nodes for the bitcoin network + * AUTOGENERATED by contrib/devtools/generate-seeds.py + * + * Each line contains a 16-byte IPv6 address and a port. + * IPv4 as well as onion addresses are wrapped inside a IPv6 address accordingly. + */ static SeedSpec6 pnSeed6_main[] = { {{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x2e,0x69,0x6a,0x7e}, 8333}, {{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0xa2,0xd1,0x04,0x7d}, 8333}, diff --git a/src/version.cpp b/src/clientversion.cpp index d12b681e5c..4987c3ed38 100644 --- a/src/version.cpp +++ b/src/clientversion.cpp @@ -2,7 +2,7 @@ // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. -#include "version.h" +#include "clientversion.h" #include "tinyformat.h" diff --git a/src/clientversion.h b/src/clientversion.h index cd7ceb78f0..acaf54c6af 100644 --- a/src/clientversion.h +++ b/src/clientversion.h @@ -35,4 +35,31 @@ // Copyright string used in Windows .rc files #define COPYRIGHT_STR "2009-" STRINGIZE(COPYRIGHT_YEAR) " The Bitcoin Core Developers" +/* + bitcoind-res.rc includes this file, but it cannot cope with real c++ code. + WINDRES_PREPROC is defined to indicate that its pre-processor is running. + Anything other than a define should be guarded below. +*/ + +#if !defined(WINDRES_PREPROC) + +#include <string> +#include <vector> + +static const int CLIENT_VERSION = + 1000000 * CLIENT_VERSION_MAJOR + + 10000 * CLIENT_VERSION_MINOR + + 100 * CLIENT_VERSION_REVISION + + 1 * CLIENT_VERSION_BUILD; + +extern const std::string CLIENT_NAME; +extern const std::string CLIENT_BUILD; +extern const std::string CLIENT_DATE; + + +std::string FormatFullVersion(); +std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments); + +#endif // WINDRES_PREPROC + #endif // CLIENTVERSION_H diff --git a/src/coincontrol.h b/src/coincontrol.h index 033092c019..c8f12d92de 100644 --- a/src/coincontrol.h +++ b/src/coincontrol.h @@ -5,7 +5,7 @@ #ifndef COINCONTROL_H #define COINCONTROL_H -#include "core.h" +#include "core/transaction.h" /** Coin Control Features. */ class CCoinControl diff --git a/src/coins.h b/src/coins.h index b8f1e5bcc5..ee9051562b 100644 --- a/src/coins.h +++ b/src/coins.h @@ -6,9 +6,10 @@ #ifndef BITCOIN_COINS_H #define BITCOIN_COINS_H -#include "core.h" +#include "compressor.h" #include "serialize.h" #include "uint256.h" +#include "undo.h" #include <assert.h> #include <stdint.h> diff --git a/src/script/compressor.cpp b/src/compressor.cpp index af1acf48db..806175dd3e 100644 --- a/src/script/compressor.cpp +++ b/src/compressor.cpp @@ -5,6 +5,7 @@ #include "compressor.h" +#include "hash.h" #include "key.h" #include "script/standard.h" @@ -128,3 +129,57 @@ bool CScriptCompressor::Decompress(unsigned int nSize, const std::vector<unsigne } return false; } + +// Amount compression: +// * If the amount is 0, output 0 +// * first, divide the amount (in base units) by the largest power of 10 possible; call the exponent e (e is max 9) +// * if e<9, the last digit of the resulting number cannot be 0; store it as d, and drop it (divide by 10) +// * call the result n +// * output 1 + 10*(9*n + d - 1) + e +// * if e==9, we only know the resulting number is not zero, so output 1 + 10*(n - 1) + 9 +// (this is decodable, as d is in [1-9] and e is in [0-9]) + +uint64_t CTxOutCompressor::CompressAmount(uint64_t n) +{ + if (n == 0) + return 0; + int e = 0; + while (((n % 10) == 0) && e < 9) { + n /= 10; + e++; + } + if (e < 9) { + int d = (n % 10); + assert(d >= 1 && d <= 9); + n /= 10; + return 1 + (n*9 + d - 1)*10 + e; + } else { + return 1 + (n - 1)*10 + 9; + } +} + +uint64_t CTxOutCompressor::DecompressAmount(uint64_t x) +{ + // x = 0 OR x = 1+10*(9*n + d - 1) + e OR x = 1+10*(n - 1) + 9 + if (x == 0) + return 0; + x--; + // x = 10*(9*n + d - 1) + e + int e = x % 10; + x /= 10; + uint64_t n = 0; + if (e < 9) { + // x = 9*n + d - 1 + int d = (x % 9) + 1; + x /= 9; + // x = n + n = x*10 + d; + } else { + n = x+1; + } + while (e) { + n *= 10; + e--; + } + return n; +} diff --git a/src/script/compressor.h b/src/compressor.h index 154e0b2662..a612c3a883 100644 --- a/src/script/compressor.h +++ b/src/compressor.h @@ -3,9 +3,10 @@ // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. -#ifndef H_BITCOIN_SCRIPT_COMPRESSOR -#define H_BITCOIN_SCRIPT_COMPRESSOR +#ifndef H_BITCOIN_COMPRESSOR +#define H_BITCOIN_COMPRESSOR +#include "core/transaction.h" #include "script/script.h" #include "serialize.h" @@ -86,4 +87,33 @@ public: } }; -#endif // H_BITCOIN_SCRIPT_COMPRESSOR +/** wrapper for CTxOut that provides a more compact serialization */ +class CTxOutCompressor +{ +private: + CTxOut &txout; + +public: + static uint64_t CompressAmount(uint64_t nAmount); + static uint64_t DecompressAmount(uint64_t nAmount); + + CTxOutCompressor(CTxOut &txoutIn) : txout(txoutIn) { } + + ADD_SERIALIZE_METHODS; + + template <typename Stream, typename Operation> + inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { + if (!ser_action.ForRead()) { + uint64_t nVal = CompressAmount(txout.nValue); + READWRITE(VARINT(nVal)); + } else { + uint64_t nVal = 0; + READWRITE(VARINT(nVal)); + txout.nValue = DecompressAmount(nVal); + } + CScriptCompressor cscript(REF(txout.scriptPubKey)); + READWRITE(cscript); + } +}; + +#endif // H_BITCOIN_COMPRESSOR diff --git a/src/core.cpp b/src/core.cpp deleted file mode 100644 index 73e6de88e1..0000000000 --- a/src/core.cpp +++ /dev/null @@ -1,339 +0,0 @@ -// Copyright (c) 2009-2010 Satoshi Nakamoto -// Copyright (c) 2009-2014 The Bitcoin developers -// Distributed under the MIT/X11 software license, see the accompanying -// file COPYING or http://www.opensource.org/licenses/mit-license.php. - -#include "core.h" - -#include "hash.h" -#include "tinyformat.h" -#include "utilstrencodings.h" - -std::string COutPoint::ToString() const -{ - return strprintf("COutPoint(%s, %u)", hash.ToString().substr(0,10), n); -} - -CTxIn::CTxIn(COutPoint prevoutIn, CScript scriptSigIn, uint32_t nSequenceIn) -{ - prevout = prevoutIn; - scriptSig = scriptSigIn; - nSequence = nSequenceIn; -} - -CTxIn::CTxIn(uint256 hashPrevTx, uint32_t nOut, CScript scriptSigIn, uint32_t nSequenceIn) -{ - prevout = COutPoint(hashPrevTx, nOut); - scriptSig = scriptSigIn; - nSequence = nSequenceIn; -} - -std::string CTxIn::ToString() const -{ - std::string str; - str += "CTxIn("; - str += prevout.ToString(); - if (prevout.IsNull()) - str += strprintf(", coinbase %s", HexStr(scriptSig)); - else - str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24)); - if (nSequence != std::numeric_limits<unsigned int>::max()) - str += strprintf(", nSequence=%u", nSequence); - str += ")"; - return str; -} - -CTxOut::CTxOut(const CAmount& nValueIn, CScript scriptPubKeyIn) -{ - nValue = nValueIn; - scriptPubKey = scriptPubKeyIn; -} - -uint256 CTxOut::GetHash() const -{ - return SerializeHash(*this); -} - -std::string CTxOut::ToString() const -{ - return strprintf("CTxOut(nValue=%d.%08d, scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30)); -} - -CFeeRate::CFeeRate(const CAmount& nFeePaid, size_t nSize) -{ - if (nSize > 0) - nSatoshisPerK = nFeePaid*1000/nSize; - else - nSatoshisPerK = 0; -} - -CAmount CFeeRate::GetFee(size_t nSize) const -{ - CAmount nFee = nSatoshisPerK*nSize / 1000; - - if (nFee == 0 && nSatoshisPerK > 0) - nFee = nSatoshisPerK; - - return nFee; -} - -std::string CFeeRate::ToString() const -{ - return strprintf("%d.%08d BTC/kB", nSatoshisPerK / COIN, nSatoshisPerK % COIN); -} - -CMutableTransaction::CMutableTransaction() : nVersion(CTransaction::CURRENT_VERSION), nLockTime(0) {} -CMutableTransaction::CMutableTransaction(const CTransaction& tx) : nVersion(tx.nVersion), vin(tx.vin), vout(tx.vout), nLockTime(tx.nLockTime) {} - -uint256 CMutableTransaction::GetHash() const -{ - return SerializeHash(*this); -} - -void CTransaction::UpdateHash() const -{ - *const_cast<uint256*>(&hash) = SerializeHash(*this); -} - -CTransaction::CTransaction() : hash(0), nVersion(CTransaction::CURRENT_VERSION), vin(), vout(), nLockTime(0) { } - -CTransaction::CTransaction(const CMutableTransaction &tx) : nVersion(tx.nVersion), vin(tx.vin), vout(tx.vout), nLockTime(tx.nLockTime) { - UpdateHash(); -} - -CTransaction& CTransaction::operator=(const CTransaction &tx) { - *const_cast<int*>(&nVersion) = tx.nVersion; - *const_cast<std::vector<CTxIn>*>(&vin) = tx.vin; - *const_cast<std::vector<CTxOut>*>(&vout) = tx.vout; - *const_cast<unsigned int*>(&nLockTime) = tx.nLockTime; - *const_cast<uint256*>(&hash) = tx.hash; - return *this; -} - -CAmount CTransaction::GetValueOut() const -{ - CAmount nValueOut = 0; - for (std::vector<CTxOut>::const_iterator it(vout.begin()); it != vout.end(); ++it) - { - nValueOut += it->nValue; - if (!MoneyRange(it->nValue) || !MoneyRange(nValueOut)) - throw std::runtime_error("CTransaction::GetValueOut() : value out of range"); - } - return nValueOut; -} - -double CTransaction::ComputePriority(double dPriorityInputs, unsigned int nTxSize) const -{ - nTxSize = CalculateModifiedSize(nTxSize); - if (nTxSize == 0) return 0.0; - - return dPriorityInputs / nTxSize; -} - -unsigned int CTransaction::CalculateModifiedSize(unsigned int nTxSize) const -{ - // In order to avoid disincentivizing cleaning up the UTXO set we don't count - // the constant overhead for each txin and up to 110 bytes of scriptSig (which - // is enough to cover a compressed pubkey p2sh redemption) for priority. - // Providing any more cleanup incentive than making additional inputs free would - // risk encouraging people to create junk outputs to redeem later. - if (nTxSize == 0) - nTxSize = ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION); - for (std::vector<CTxIn>::const_iterator it(vin.begin()); it != vin.end(); ++it) - { - unsigned int offset = 41U + std::min(110U, (unsigned int)it->scriptSig.size()); - if (nTxSize > offset) - nTxSize -= offset; - } - return nTxSize; -} - -std::string CTransaction::ToString() const -{ - std::string str; - str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%u, vout.size=%u, nLockTime=%u)\n", - GetHash().ToString().substr(0,10), - nVersion, - vin.size(), - vout.size(), - nLockTime); - for (unsigned int i = 0; i < vin.size(); i++) - str += " " + vin[i].ToString() + "\n"; - for (unsigned int i = 0; i < vout.size(); i++) - str += " " + vout[i].ToString() + "\n"; - return str; -} - -// Amount compression: -// * If the amount is 0, output 0 -// * first, divide the amount (in base units) by the largest power of 10 possible; call the exponent e (e is max 9) -// * if e<9, the last digit of the resulting number cannot be 0; store it as d, and drop it (divide by 10) -// * call the result n -// * output 1 + 10*(9*n + d - 1) + e -// * if e==9, we only know the resulting number is not zero, so output 1 + 10*(n - 1) + 9 -// (this is decodable, as d is in [1-9] and e is in [0-9]) - -uint64_t CTxOutCompressor::CompressAmount(uint64_t n) -{ - if (n == 0) - return 0; - int e = 0; - while (((n % 10) == 0) && e < 9) { - n /= 10; - e++; - } - if (e < 9) { - int d = (n % 10); - assert(d >= 1 && d <= 9); - n /= 10; - return 1 + (n*9 + d - 1)*10 + e; - } else { - return 1 + (n - 1)*10 + 9; - } -} - -uint64_t CTxOutCompressor::DecompressAmount(uint64_t x) -{ - // x = 0 OR x = 1+10*(9*n + d - 1) + e OR x = 1+10*(n - 1) + 9 - if (x == 0) - return 0; - x--; - // x = 10*(9*n + d - 1) + e - int e = x % 10; - x /= 10; - uint64_t n = 0; - if (e < 9) { - // x = 9*n + d - 1 - int d = (x % 9) + 1; - x /= 9; - // x = n - n = x*10 + d; - } else { - n = x+1; - } - while (e) { - n *= 10; - e--; - } - return n; -} - -uint256 CBlockHeader::GetHash() const -{ - return Hash(BEGIN(nVersion), END(nNonce)); -} - -uint256 CBlock::BuildMerkleTree(bool* fMutated) const -{ - /* WARNING! If you're reading this because you're learning about crypto - and/or designing a new system that will use merkle trees, keep in mind - that the following merkle tree algorithm has a serious flaw related to - duplicate txids, resulting in a vulnerability (CVE-2012-2459). - - The reason is that if the number of hashes in the list at a given time - is odd, the last one is duplicated before computing the next level (which - is unusual in Merkle trees). This results in certain sequences of - transactions leading to the same merkle root. For example, these two - trees: - - A A - / \ / \ - B C B C - / \ | / \ / \ - D E F D E F F - / \ / \ / \ / \ / \ / \ / \ - 1 2 3 4 5 6 1 2 3 4 5 6 5 6 - - for transaction lists [1,2,3,4,5,6] and [1,2,3,4,5,6,5,6] (where 5 and - 6 are repeated) result in the same root hash A (because the hash of both - of (F) and (F,F) is C). - - The vulnerability results from being able to send a block with such a - transaction list, with the same merkle root, and the same block hash as - the original without duplication, resulting in failed validation. If the - receiving node proceeds to mark that block as permanently invalid - however, it will fail to accept further unmodified (and thus potentially - valid) versions of the same block. We defend against this by detecting - the case where we would hash two identical hashes at the end of the list - together, and treating that identically to the block having an invalid - merkle root. Assuming no double-SHA256 collisions, this will detect all - known ways of changing the transactions without affecting the merkle - root. - */ - vMerkleTree.clear(); - vMerkleTree.reserve(vtx.size() * 2 + 16); // Safe upper bound for the number of total nodes. - for (std::vector<CTransaction>::const_iterator it(vtx.begin()); it != vtx.end(); ++it) - vMerkleTree.push_back(it->GetHash()); - int j = 0; - bool mutated = false; - for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2) - { - for (int i = 0; i < nSize; i += 2) - { - int i2 = std::min(i+1, nSize-1); - if (i2 == i + 1 && i2 + 1 == nSize && vMerkleTree[j+i] == vMerkleTree[j+i2]) { - // Two identical hashes at the end of the list at a particular level. - mutated = true; - } - vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]), - BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2]))); - } - j += nSize; - } - if (fMutated) { - *fMutated = mutated; - } - return (vMerkleTree.empty() ? 0 : vMerkleTree.back()); -} - -std::vector<uint256> CBlock::GetMerkleBranch(int nIndex) const -{ - if (vMerkleTree.empty()) - BuildMerkleTree(); - std::vector<uint256> vMerkleBranch; - int j = 0; - for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2) - { - int i = std::min(nIndex^1, nSize-1); - vMerkleBranch.push_back(vMerkleTree[j+i]); - nIndex >>= 1; - j += nSize; - } - return vMerkleBranch; -} - -uint256 CBlock::CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex) -{ - if (nIndex == -1) - return 0; - for (std::vector<uint256>::const_iterator it(vMerkleBranch.begin()); it != vMerkleBranch.end(); ++it) - { - if (nIndex & 1) - hash = Hash(BEGIN(*it), END(*it), BEGIN(hash), END(hash)); - else - hash = Hash(BEGIN(hash), END(hash), BEGIN(*it), END(*it)); - nIndex >>= 1; - } - return hash; -} - -std::string CBlock::ToString() const -{ - std::stringstream s; - s << strprintf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%u)\n", - GetHash().ToString(), - nVersion, - hashPrevBlock.ToString(), - hashMerkleRoot.ToString(), - nTime, nBits, nNonce, - vtx.size()); - for (unsigned int i = 0; i < vtx.size(); i++) - { - s << " " << vtx[i].ToString() << "\n"; - } - s << " vMerkleTree: "; - for (unsigned int i = 0; i < vMerkleTree.size(); i++) - s << " " << vMerkleTree[i].ToString(); - s << "\n"; - return s.str(); -} diff --git a/src/core.h b/src/core.h deleted file mode 100644 index a024dad740..0000000000 --- a/src/core.h +++ /dev/null @@ -1,566 +0,0 @@ -// Copyright (c) 2009-2010 Satoshi Nakamoto -// Copyright (c) 2009-2013 The Bitcoin developers -// Distributed under the MIT/X11 software license, see the accompanying -// file COPYING or http://www.opensource.org/licenses/mit-license.php. - -#ifndef BITCOIN_CORE_H -#define BITCOIN_CORE_H - -#include "amount.h" -#include "script/compressor.h" -#include "script/script.h" -#include "serialize.h" -#include "uint256.h" - -#include <stdint.h> - -class CTransaction; - -static const int64_t COIN = 100000000; -static const int64_t CENT = 1000000; - -/** No amount larger than this (in satoshi) is valid */ -static const CAmount MAX_MONEY = 21000000 * COIN; -inline bool MoneyRange(const CAmount& nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); } - -/** An outpoint - a combination of a transaction hash and an index n into its vout */ -class COutPoint -{ -public: - uint256 hash; - uint32_t n; - - COutPoint() { SetNull(); } - COutPoint(uint256 hashIn, uint32_t nIn) { hash = hashIn; n = nIn; } - - ADD_SERIALIZE_METHODS; - - template <typename Stream, typename Operation> - inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { - READWRITE(FLATDATA(*this)); - } - - void SetNull() { hash = 0; n = (uint32_t) -1; } - bool IsNull() const { return (hash == 0 && n == (uint32_t) -1); } - - friend bool operator<(const COutPoint& a, const COutPoint& b) - { - return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n)); - } - - friend bool operator==(const COutPoint& a, const COutPoint& b) - { - return (a.hash == b.hash && a.n == b.n); - } - - friend bool operator!=(const COutPoint& a, const COutPoint& b) - { - return !(a == b); - } - - std::string ToString() const; -}; - -/** An input of a transaction. It contains the location of the previous - * transaction's output that it claims and a signature that matches the - * output's public key. - */ -class CTxIn -{ -public: - COutPoint prevout; - CScript scriptSig; - uint32_t nSequence; - - CTxIn() - { - nSequence = std::numeric_limits<unsigned int>::max(); - } - - explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), uint32_t nSequenceIn=std::numeric_limits<unsigned int>::max()); - CTxIn(uint256 hashPrevTx, uint32_t nOut, CScript scriptSigIn=CScript(), uint32_t nSequenceIn=std::numeric_limits<uint32_t>::max()); - - ADD_SERIALIZE_METHODS; - - template <typename Stream, typename Operation> - inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { - READWRITE(prevout); - READWRITE(scriptSig); - READWRITE(nSequence); - } - - bool IsFinal() const - { - return (nSequence == std::numeric_limits<uint32_t>::max()); - } - - friend bool operator==(const CTxIn& a, const CTxIn& b) - { - return (a.prevout == b.prevout && - a.scriptSig == b.scriptSig && - a.nSequence == b.nSequence); - } - - friend bool operator!=(const CTxIn& a, const CTxIn& b) - { - return !(a == b); - } - - std::string ToString() const; -}; - - - -/** Type-safe wrapper class to for fee rates - * (how much to pay based on transaction size) - */ -class CFeeRate -{ -private: - CAmount nSatoshisPerK; // unit is satoshis-per-1,000-bytes -public: - CFeeRate() : nSatoshisPerK(0) { } - explicit CFeeRate(const CAmount& _nSatoshisPerK): nSatoshisPerK(_nSatoshisPerK) { } - CFeeRate(const CAmount& nFeePaid, size_t nSize); - CFeeRate(const CFeeRate& other) { nSatoshisPerK = other.nSatoshisPerK; } - - CAmount GetFee(size_t size) const; // unit returned is satoshis - CAmount GetFeePerK() const { return GetFee(1000); } // satoshis-per-1000-bytes - - friend bool operator<(const CFeeRate& a, const CFeeRate& b) { return a.nSatoshisPerK < b.nSatoshisPerK; } - friend bool operator>(const CFeeRate& a, const CFeeRate& b) { return a.nSatoshisPerK > b.nSatoshisPerK; } - friend bool operator==(const CFeeRate& a, const CFeeRate& b) { return a.nSatoshisPerK == b.nSatoshisPerK; } - friend bool operator<=(const CFeeRate& a, const CFeeRate& b) { return a.nSatoshisPerK <= b.nSatoshisPerK; } - friend bool operator>=(const CFeeRate& a, const CFeeRate& b) { return a.nSatoshisPerK >= b.nSatoshisPerK; } - std::string ToString() const; - - ADD_SERIALIZE_METHODS; - - template <typename Stream, typename Operation> - inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { - READWRITE(nSatoshisPerK); - } -}; - - -/** An output of a transaction. It contains the public key that the next input - * must be able to sign with to claim it. - */ -class CTxOut -{ -public: - CAmount nValue; - CScript scriptPubKey; - - CTxOut() - { - SetNull(); - } - - CTxOut(const CAmount& nValueIn, CScript scriptPubKeyIn); - - ADD_SERIALIZE_METHODS; - - template <typename Stream, typename Operation> - inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { - READWRITE(nValue); - READWRITE(scriptPubKey); - } - - void SetNull() - { - nValue = -1; - scriptPubKey.clear(); - } - - bool IsNull() const - { - return (nValue == -1); - } - - uint256 GetHash() const; - - bool IsDust(CFeeRate minRelayTxFee) const - { - // "Dust" is defined in terms of CTransaction::minRelayTxFee, - // which has units satoshis-per-kilobyte. - // If you'd pay more than 1/3 in fees - // to spend something, then we consider it dust. - // A typical txout is 34 bytes big, and will - // need a CTxIn of at least 148 bytes to spend: - // so dust is a txout less than 546 satoshis - // with default minRelayTxFee. - size_t nSize = GetSerializeSize(SER_DISK,0)+148u; - return (nValue < 3*minRelayTxFee.GetFee(nSize)); - } - - friend bool operator==(const CTxOut& a, const CTxOut& b) - { - return (a.nValue == b.nValue && - a.scriptPubKey == b.scriptPubKey); - } - - friend bool operator!=(const CTxOut& a, const CTxOut& b) - { - return !(a == b); - } - - std::string ToString() const; -}; - - -struct CMutableTransaction; - -/** The basic transaction that is broadcasted on the network and contained in - * blocks. A transaction can contain multiple inputs and outputs. - */ -class CTransaction -{ -private: - /** Memory only. */ - const uint256 hash; - void UpdateHash() const; - -public: - static const int32_t CURRENT_VERSION=1; - - // The local variables are made const to prevent unintended modification - // without updating the cached hash value. However, CTransaction is not - // actually immutable; deserialization and assignment are implemented, - // and bypass the constness. This is safe, as they update the entire - // structure, including the hash. - const int32_t nVersion; - const std::vector<CTxIn> vin; - const std::vector<CTxOut> vout; - const uint32_t nLockTime; - - /** Construct a CTransaction that qualifies as IsNull() */ - CTransaction(); - - /** Convert a CMutableTransaction into a CTransaction. */ - CTransaction(const CMutableTransaction &tx); - - CTransaction& operator=(const CTransaction& tx); - - ADD_SERIALIZE_METHODS; - - template <typename Stream, typename Operation> - inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { - READWRITE(*const_cast<int32_t*>(&this->nVersion)); - nVersion = this->nVersion; - READWRITE(*const_cast<std::vector<CTxIn>*>(&vin)); - READWRITE(*const_cast<std::vector<CTxOut>*>(&vout)); - READWRITE(*const_cast<uint32_t*>(&nLockTime)); - if (ser_action.ForRead()) - UpdateHash(); - } - - bool IsNull() const { - return vin.empty() && vout.empty(); - } - - const uint256& GetHash() const { - return hash; - } - - // Return sum of txouts. - CAmount GetValueOut() const; - // GetValueIn() is a method on CCoinsViewCache, because - // inputs must be known to compute value in. - - // Compute priority, given priority of inputs and (optionally) tx size - double ComputePriority(double dPriorityInputs, unsigned int nTxSize=0) const; - - // Compute modified tx size for priority calculation (optionally given tx size) - unsigned int CalculateModifiedSize(unsigned int nTxSize=0) const; - - bool IsCoinBase() const - { - return (vin.size() == 1 && vin[0].prevout.IsNull()); - } - - friend bool operator==(const CTransaction& a, const CTransaction& b) - { - return a.hash == b.hash; - } - - friend bool operator!=(const CTransaction& a, const CTransaction& b) - { - return a.hash != b.hash; - } - - std::string ToString() const; -}; - -/** A mutable version of CTransaction. */ -struct CMutableTransaction -{ - int32_t nVersion; - std::vector<CTxIn> vin; - std::vector<CTxOut> vout; - uint32_t nLockTime; - - CMutableTransaction(); - CMutableTransaction(const CTransaction& tx); - - ADD_SERIALIZE_METHODS; - - template <typename Stream, typename Operation> - inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { - READWRITE(this->nVersion); - nVersion = this->nVersion; - READWRITE(vin); - READWRITE(vout); - READWRITE(nLockTime); - } - - /** Compute the hash of this CMutableTransaction. This is computed on the - * fly, as opposed to GetHash() in CTransaction, which uses a cached result. - */ - uint256 GetHash() const; -}; - -/** wrapper for CTxOut that provides a more compact serialization */ -class CTxOutCompressor -{ -private: - CTxOut &txout; - -public: - static uint64_t CompressAmount(uint64_t nAmount); - static uint64_t DecompressAmount(uint64_t nAmount); - - CTxOutCompressor(CTxOut &txoutIn) : txout(txoutIn) { } - - ADD_SERIALIZE_METHODS; - - template <typename Stream, typename Operation> - inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { - if (!ser_action.ForRead()) { - uint64_t nVal = CompressAmount(txout.nValue); - READWRITE(VARINT(nVal)); - } else { - uint64_t nVal = 0; - READWRITE(VARINT(nVal)); - txout.nValue = DecompressAmount(nVal); - } - CScriptCompressor cscript(REF(txout.scriptPubKey)); - READWRITE(cscript); - } -}; - -/** Undo information for a CTxIn - * - * Contains the prevout's CTxOut being spent, and if this was the - * last output of the affected transaction, its metadata as well - * (coinbase or not, height, transaction version) - */ -class CTxInUndo -{ -public: - CTxOut txout; // the txout data before being spent - bool fCoinBase; // if the outpoint was the last unspent: whether it belonged to a coinbase - unsigned int nHeight; // if the outpoint was the last unspent: its height - int nVersion; // if the outpoint was the last unspent: its version - - CTxInUndo() : txout(), fCoinBase(false), nHeight(0), nVersion(0) {} - CTxInUndo(const CTxOut &txoutIn, bool fCoinBaseIn = false, unsigned int nHeightIn = 0, int nVersionIn = 0) : txout(txoutIn), fCoinBase(fCoinBaseIn), nHeight(nHeightIn), nVersion(nVersionIn) { } - - unsigned int GetSerializeSize(int nType, int nVersion) const { - return ::GetSerializeSize(VARINT(nHeight*2+(fCoinBase ? 1 : 0)), nType, nVersion) + - (nHeight > 0 ? ::GetSerializeSize(VARINT(this->nVersion), nType, nVersion) : 0) + - ::GetSerializeSize(CTxOutCompressor(REF(txout)), nType, nVersion); - } - - template<typename Stream> - void Serialize(Stream &s, int nType, int nVersion) const { - ::Serialize(s, VARINT(nHeight*2+(fCoinBase ? 1 : 0)), nType, nVersion); - if (nHeight > 0) - ::Serialize(s, VARINT(this->nVersion), nType, nVersion); - ::Serialize(s, CTxOutCompressor(REF(txout)), nType, nVersion); - } - - template<typename Stream> - void Unserialize(Stream &s, int nType, int nVersion) { - unsigned int nCode = 0; - ::Unserialize(s, VARINT(nCode), nType, nVersion); - nHeight = nCode / 2; - fCoinBase = nCode & 1; - if (nHeight > 0) - ::Unserialize(s, VARINT(this->nVersion), nType, nVersion); - ::Unserialize(s, REF(CTxOutCompressor(REF(txout))), nType, nVersion); - } -}; - -/** Undo information for a CTransaction */ -class CTxUndo -{ -public: - // undo information for all txins - std::vector<CTxInUndo> vprevout; - - ADD_SERIALIZE_METHODS; - - template <typename Stream, typename Operation> - inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { - READWRITE(vprevout); - } -}; - - -/** Nodes collect new transactions into a block, hash them into a hash tree, - * and scan through nonce values to make the block's hash satisfy proof-of-work - * requirements. When they solve the proof-of-work, they broadcast the block - * to everyone and the block is added to the block chain. The first transaction - * in the block is a special one that creates a new coin owned by the creator - * of the block. - */ -class CBlockHeader -{ -public: - // header - static const int32_t CURRENT_VERSION=2; - int32_t nVersion; - uint256 hashPrevBlock; - uint256 hashMerkleRoot; - uint32_t nTime; - uint32_t nBits; - uint32_t nNonce; - - CBlockHeader() - { - SetNull(); - } - - ADD_SERIALIZE_METHODS; - - template <typename Stream, typename Operation> - inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { - READWRITE(this->nVersion); - nVersion = this->nVersion; - READWRITE(hashPrevBlock); - READWRITE(hashMerkleRoot); - READWRITE(nTime); - READWRITE(nBits); - READWRITE(nNonce); - } - - void SetNull() - { - nVersion = CBlockHeader::CURRENT_VERSION; - hashPrevBlock = 0; - hashMerkleRoot = 0; - nTime = 0; - nBits = 0; - nNonce = 0; - } - - bool IsNull() const - { - return (nBits == 0); - } - - uint256 GetHash() const; - - int64_t GetBlockTime() const - { - return (int64_t)nTime; - } -}; - - -class CBlock : public CBlockHeader -{ -public: - // network and disk - std::vector<CTransaction> vtx; - - // memory only - mutable std::vector<uint256> vMerkleTree; - - CBlock() - { - SetNull(); - } - - CBlock(const CBlockHeader &header) - { - SetNull(); - *((CBlockHeader*)this) = header; - } - - ADD_SERIALIZE_METHODS; - - template <typename Stream, typename Operation> - inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { - READWRITE(*(CBlockHeader*)this); - READWRITE(vtx); - } - - void SetNull() - { - CBlockHeader::SetNull(); - vtx.clear(); - vMerkleTree.clear(); - } - - CBlockHeader GetBlockHeader() const - { - CBlockHeader block; - block.nVersion = nVersion; - block.hashPrevBlock = hashPrevBlock; - block.hashMerkleRoot = hashMerkleRoot; - block.nTime = nTime; - block.nBits = nBits; - block.nNonce = nNonce; - return block; - } - - // Build the in-memory merkle tree for this block and return the merkle root. - // If non-NULL, *mutated is set to whether mutation was detected in the merkle - // tree (a duplication of transactions in the block leading to an identical - // merkle root). - uint256 BuildMerkleTree(bool* mutated = NULL) const; - - std::vector<uint256> GetMerkleBranch(int nIndex) const; - static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex); - std::string ToString() const; -}; - - -/** Describes a place in the block chain to another node such that if the - * other node doesn't have the same branch, it can find a recent common trunk. - * The further back it is, the further before the fork it may be. - */ -struct CBlockLocator -{ - std::vector<uint256> vHave; - - CBlockLocator() {} - - CBlockLocator(const std::vector<uint256>& vHaveIn) - { - vHave = vHaveIn; - } - - ADD_SERIALIZE_METHODS; - - template <typename Stream, typename Operation> - inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { - if (!(nType & SER_GETHASH)) - READWRITE(nVersion); - READWRITE(vHave); - } - - void SetNull() - { - vHave.clear(); - } - - bool IsNull() - { - return vHave.empty(); - } -}; - -#endif // BITCOIN_CORE_H diff --git a/src/core/block.cpp b/src/core/block.cpp new file mode 100644 index 0000000000..2010d44dac --- /dev/null +++ b/src/core/block.cpp @@ -0,0 +1,130 @@ +// Copyright (c) 2009-2010 Satoshi Nakamoto +// Copyright (c) 2009-2014 The Bitcoin developers +// Distributed under the MIT/X11 software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include "core/block.h" + +#include "hash.h" +#include "tinyformat.h" +#include "utilstrencodings.h" + +uint256 CBlockHeader::GetHash() const +{ + return Hash(BEGIN(nVersion), END(nNonce)); +} + +uint256 CBlock::BuildMerkleTree(bool* fMutated) const +{ + /* WARNING! If you're reading this because you're learning about crypto + and/or designing a new system that will use merkle trees, keep in mind + that the following merkle tree algorithm has a serious flaw related to + duplicate txids, resulting in a vulnerability (CVE-2012-2459). + + The reason is that if the number of hashes in the list at a given time + is odd, the last one is duplicated before computing the next level (which + is unusual in Merkle trees). This results in certain sequences of + transactions leading to the same merkle root. For example, these two + trees: + + A A + / \ / \ + B C B C + / \ | / \ / \ + D E F D E F F + / \ / \ / \ / \ / \ / \ / \ + 1 2 3 4 5 6 1 2 3 4 5 6 5 6 + + for transaction lists [1,2,3,4,5,6] and [1,2,3,4,5,6,5,6] (where 5 and + 6 are repeated) result in the same root hash A (because the hash of both + of (F) and (F,F) is C). + + The vulnerability results from being able to send a block with such a + transaction list, with the same merkle root, and the same block hash as + the original without duplication, resulting in failed validation. If the + receiving node proceeds to mark that block as permanently invalid + however, it will fail to accept further unmodified (and thus potentially + valid) versions of the same block. We defend against this by detecting + the case where we would hash two identical hashes at the end of the list + together, and treating that identically to the block having an invalid + merkle root. Assuming no double-SHA256 collisions, this will detect all + known ways of changing the transactions without affecting the merkle + root. + */ + vMerkleTree.clear(); + vMerkleTree.reserve(vtx.size() * 2 + 16); // Safe upper bound for the number of total nodes. + for (std::vector<CTransaction>::const_iterator it(vtx.begin()); it != vtx.end(); ++it) + vMerkleTree.push_back(it->GetHash()); + int j = 0; + bool mutated = false; + for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2) + { + for (int i = 0; i < nSize; i += 2) + { + int i2 = std::min(i+1, nSize-1); + if (i2 == i + 1 && i2 + 1 == nSize && vMerkleTree[j+i] == vMerkleTree[j+i2]) { + // Two identical hashes at the end of the list at a particular level. + mutated = true; + } + vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]), + BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2]))); + } + j += nSize; + } + if (fMutated) { + *fMutated = mutated; + } + return (vMerkleTree.empty() ? 0 : vMerkleTree.back()); +} + +std::vector<uint256> CBlock::GetMerkleBranch(int nIndex) const +{ + if (vMerkleTree.empty()) + BuildMerkleTree(); + std::vector<uint256> vMerkleBranch; + int j = 0; + for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2) + { + int i = std::min(nIndex^1, nSize-1); + vMerkleBranch.push_back(vMerkleTree[j+i]); + nIndex >>= 1; + j += nSize; + } + return vMerkleBranch; +} + +uint256 CBlock::CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex) +{ + if (nIndex == -1) + return 0; + for (std::vector<uint256>::const_iterator it(vMerkleBranch.begin()); it != vMerkleBranch.end(); ++it) + { + if (nIndex & 1) + hash = Hash(BEGIN(*it), END(*it), BEGIN(hash), END(hash)); + else + hash = Hash(BEGIN(hash), END(hash), BEGIN(*it), END(*it)); + nIndex >>= 1; + } + return hash; +} + +std::string CBlock::ToString() const +{ + std::stringstream s; + s << strprintf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%u)\n", + GetHash().ToString(), + nVersion, + hashPrevBlock.ToString(), + hashMerkleRoot.ToString(), + nTime, nBits, nNonce, + vtx.size()); + for (unsigned int i = 0; i < vtx.size(); i++) + { + s << " " << vtx[i].ToString() << "\n"; + } + s << " vMerkleTree: "; + for (unsigned int i = 0; i < vMerkleTree.size(); i++) + s << " " << vMerkleTree[i].ToString(); + s << "\n"; + return s.str(); +} diff --git a/src/core/block.h b/src/core/block.h new file mode 100644 index 0000000000..f1eb7a844f --- /dev/null +++ b/src/core/block.h @@ -0,0 +1,168 @@ +// Copyright (c) 2009-2010 Satoshi Nakamoto +// Copyright (c) 2009-2013 The Bitcoin developers +// Distributed under the MIT/X11 software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#ifndef H_BITCOIN_CORE_BLOCK +#define H_BITCOIN_CORE_BLOCK + +#include "core/transaction.h" +#include "serialize.h" +#include "uint256.h" + +/** Nodes collect new transactions into a block, hash them into a hash tree, + * and scan through nonce values to make the block's hash satisfy proof-of-work + * requirements. When they solve the proof-of-work, they broadcast the block + * to everyone and the block is added to the block chain. The first transaction + * in the block is a special one that creates a new coin owned by the creator + * of the block. + */ +class CBlockHeader +{ +public: + // header + static const int32_t CURRENT_VERSION=2; + int32_t nVersion; + uint256 hashPrevBlock; + uint256 hashMerkleRoot; + uint32_t nTime; + uint32_t nBits; + uint32_t nNonce; + + CBlockHeader() + { + SetNull(); + } + + ADD_SERIALIZE_METHODS; + + template <typename Stream, typename Operation> + inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { + READWRITE(this->nVersion); + nVersion = this->nVersion; + READWRITE(hashPrevBlock); + READWRITE(hashMerkleRoot); + READWRITE(nTime); + READWRITE(nBits); + READWRITE(nNonce); + } + + void SetNull() + { + nVersion = CBlockHeader::CURRENT_VERSION; + hashPrevBlock = 0; + hashMerkleRoot = 0; + nTime = 0; + nBits = 0; + nNonce = 0; + } + + bool IsNull() const + { + return (nBits == 0); + } + + uint256 GetHash() const; + + int64_t GetBlockTime() const + { + return (int64_t)nTime; + } +}; + + +class CBlock : public CBlockHeader +{ +public: + // network and disk + std::vector<CTransaction> vtx; + + // memory only + mutable std::vector<uint256> vMerkleTree; + + CBlock() + { + SetNull(); + } + + CBlock(const CBlockHeader &header) + { + SetNull(); + *((CBlockHeader*)this) = header; + } + + ADD_SERIALIZE_METHODS; + + template <typename Stream, typename Operation> + inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { + READWRITE(*(CBlockHeader*)this); + READWRITE(vtx); + } + + void SetNull() + { + CBlockHeader::SetNull(); + vtx.clear(); + vMerkleTree.clear(); + } + + CBlockHeader GetBlockHeader() const + { + CBlockHeader block; + block.nVersion = nVersion; + block.hashPrevBlock = hashPrevBlock; + block.hashMerkleRoot = hashMerkleRoot; + block.nTime = nTime; + block.nBits = nBits; + block.nNonce = nNonce; + return block; + } + + // Build the in-memory merkle tree for this block and return the merkle root. + // If non-NULL, *mutated is set to whether mutation was detected in the merkle + // tree (a duplication of transactions in the block leading to an identical + // merkle root). + uint256 BuildMerkleTree(bool* mutated = NULL) const; + + std::vector<uint256> GetMerkleBranch(int nIndex) const; + static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex); + std::string ToString() const; +}; + + +/** Describes a place in the block chain to another node such that if the + * other node doesn't have the same branch, it can find a recent common trunk. + * The further back it is, the further before the fork it may be. + */ +struct CBlockLocator +{ + std::vector<uint256> vHave; + + CBlockLocator() {} + + CBlockLocator(const std::vector<uint256>& vHaveIn) + { + vHave = vHaveIn; + } + + ADD_SERIALIZE_METHODS; + + template <typename Stream, typename Operation> + inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { + if (!(nType & SER_GETHASH)) + READWRITE(nVersion); + READWRITE(vHave); + } + + void SetNull() + { + vHave.clear(); + } + + bool IsNull() + { + return vHave.empty(); + } +}; + +#endif // H_BITCOIN_CORE_BLOCK diff --git a/src/core/transaction.cpp b/src/core/transaction.cpp new file mode 100644 index 0000000000..f835bafb9f --- /dev/null +++ b/src/core/transaction.cpp @@ -0,0 +1,142 @@ +// Copyright (c) 2009-2010 Satoshi Nakamoto +// Copyright (c) 2009-2014 The Bitcoin developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include "core/transaction.h" + +#include "hash.h" +#include "tinyformat.h" +#include "utilstrencodings.h" + +std::string COutPoint::ToString() const +{ + return strprintf("COutPoint(%s, %u)", hash.ToString().substr(0,10), n); +} + +CTxIn::CTxIn(COutPoint prevoutIn, CScript scriptSigIn, uint32_t nSequenceIn) +{ + prevout = prevoutIn; + scriptSig = scriptSigIn; + nSequence = nSequenceIn; +} + +CTxIn::CTxIn(uint256 hashPrevTx, uint32_t nOut, CScript scriptSigIn, uint32_t nSequenceIn) +{ + prevout = COutPoint(hashPrevTx, nOut); + scriptSig = scriptSigIn; + nSequence = nSequenceIn; +} + +std::string CTxIn::ToString() const +{ + std::string str; + str += "CTxIn("; + str += prevout.ToString(); + if (prevout.IsNull()) + str += strprintf(", coinbase %s", HexStr(scriptSig)); + else + str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24)); + if (nSequence != std::numeric_limits<unsigned int>::max()) + str += strprintf(", nSequence=%u", nSequence); + str += ")"; + return str; +} + +CTxOut::CTxOut(const CAmount& nValueIn, CScript scriptPubKeyIn) +{ + nValue = nValueIn; + scriptPubKey = scriptPubKeyIn; +} + +uint256 CTxOut::GetHash() const +{ + return SerializeHash(*this); +} + +std::string CTxOut::ToString() const +{ + return strprintf("CTxOut(nValue=%d.%08d, scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30)); +} + +CMutableTransaction::CMutableTransaction() : nVersion(CTransaction::CURRENT_VERSION), nLockTime(0) {} +CMutableTransaction::CMutableTransaction(const CTransaction& tx) : nVersion(tx.nVersion), vin(tx.vin), vout(tx.vout), nLockTime(tx.nLockTime) {} + +uint256 CMutableTransaction::GetHash() const +{ + return SerializeHash(*this); +} + +void CTransaction::UpdateHash() const +{ + *const_cast<uint256*>(&hash) = SerializeHash(*this); +} + +CTransaction::CTransaction() : hash(0), nVersion(CTransaction::CURRENT_VERSION), vin(), vout(), nLockTime(0) { } + +CTransaction::CTransaction(const CMutableTransaction &tx) : nVersion(tx.nVersion), vin(tx.vin), vout(tx.vout), nLockTime(tx.nLockTime) { + UpdateHash(); +} + +CTransaction& CTransaction::operator=(const CTransaction &tx) { + *const_cast<int*>(&nVersion) = tx.nVersion; + *const_cast<std::vector<CTxIn>*>(&vin) = tx.vin; + *const_cast<std::vector<CTxOut>*>(&vout) = tx.vout; + *const_cast<unsigned int*>(&nLockTime) = tx.nLockTime; + *const_cast<uint256*>(&hash) = tx.hash; + return *this; +} + +CAmount CTransaction::GetValueOut() const +{ + CAmount nValueOut = 0; + for (std::vector<CTxOut>::const_iterator it(vout.begin()); it != vout.end(); ++it) + { + nValueOut += it->nValue; + if (!MoneyRange(it->nValue) || !MoneyRange(nValueOut)) + throw std::runtime_error("CTransaction::GetValueOut() : value out of range"); + } + return nValueOut; +} + +double CTransaction::ComputePriority(double dPriorityInputs, unsigned int nTxSize) const +{ + nTxSize = CalculateModifiedSize(nTxSize); + if (nTxSize == 0) return 0.0; + + return dPriorityInputs / nTxSize; +} + +unsigned int CTransaction::CalculateModifiedSize(unsigned int nTxSize) const +{ + // In order to avoid disincentivizing cleaning up the UTXO set we don't count + // the constant overhead for each txin and up to 110 bytes of scriptSig (which + // is enough to cover a compressed pubkey p2sh redemption) for priority. + // Providing any more cleanup incentive than making additional inputs free would + // risk encouraging people to create junk outputs to redeem later. + if (nTxSize == 0) + nTxSize = ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION); + for (std::vector<CTxIn>::const_iterator it(vin.begin()); it != vin.end(); ++it) + { + unsigned int offset = 41U + std::min(110U, (unsigned int)it->scriptSig.size()); + if (nTxSize > offset) + nTxSize -= offset; + } + return nTxSize; +} + +std::string CTransaction::ToString() const +{ + std::string str; + str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%u, vout.size=%u, nLockTime=%u)\n", + GetHash().ToString().substr(0,10), + nVersion, + vin.size(), + vout.size(), + nLockTime); + for (unsigned int i = 0; i < vin.size(); i++) + str += " " + vin[i].ToString() + "\n"; + for (unsigned int i = 0; i < vout.size(); i++) + str += " " + vout[i].ToString() + "\n"; + return str; +} diff --git a/src/core/transaction.h b/src/core/transaction.h new file mode 100644 index 0000000000..c21558cfeb --- /dev/null +++ b/src/core/transaction.h @@ -0,0 +1,276 @@ +// Copyright (c) 2009-2010 Satoshi Nakamoto +// Copyright (c) 2009-2014 The Bitcoin developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#ifndef H_BITCOIN_CORE_TRANSACTION +#define H_BITCOIN_CORE_TRANSACTION + +#include "amount.h" +#include "script/script.h" +#include "serialize.h" +#include "uint256.h" + +/** An outpoint - a combination of a transaction hash and an index n into its vout */ +class COutPoint +{ +public: + uint256 hash; + uint32_t n; + + COutPoint() { SetNull(); } + COutPoint(uint256 hashIn, uint32_t nIn) { hash = hashIn; n = nIn; } + + ADD_SERIALIZE_METHODS; + + template <typename Stream, typename Operation> + inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { + READWRITE(FLATDATA(*this)); + } + + void SetNull() { hash = 0; n = (uint32_t) -1; } + bool IsNull() const { return (hash == 0 && n == (uint32_t) -1); } + + friend bool operator<(const COutPoint& a, const COutPoint& b) + { + return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n)); + } + + friend bool operator==(const COutPoint& a, const COutPoint& b) + { + return (a.hash == b.hash && a.n == b.n); + } + + friend bool operator!=(const COutPoint& a, const COutPoint& b) + { + return !(a == b); + } + + std::string ToString() const; +}; + +/** An input of a transaction. It contains the location of the previous + * transaction's output that it claims and a signature that matches the + * output's public key. + */ +class CTxIn +{ +public: + COutPoint prevout; + CScript scriptSig; + uint32_t nSequence; + + CTxIn() + { + nSequence = std::numeric_limits<unsigned int>::max(); + } + + explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), uint32_t nSequenceIn=std::numeric_limits<unsigned int>::max()); + CTxIn(uint256 hashPrevTx, uint32_t nOut, CScript scriptSigIn=CScript(), uint32_t nSequenceIn=std::numeric_limits<uint32_t>::max()); + + ADD_SERIALIZE_METHODS; + + template <typename Stream, typename Operation> + inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { + READWRITE(prevout); + READWRITE(scriptSig); + READWRITE(nSequence); + } + + bool IsFinal() const + { + return (nSequence == std::numeric_limits<uint32_t>::max()); + } + + friend bool operator==(const CTxIn& a, const CTxIn& b) + { + return (a.prevout == b.prevout && + a.scriptSig == b.scriptSig && + a.nSequence == b.nSequence); + } + + friend bool operator!=(const CTxIn& a, const CTxIn& b) + { + return !(a == b); + } + + std::string ToString() const; +}; + +/** An output of a transaction. It contains the public key that the next input + * must be able to sign with to claim it. + */ +class CTxOut +{ +public: + CAmount nValue; + CScript scriptPubKey; + + CTxOut() + { + SetNull(); + } + + CTxOut(const CAmount& nValueIn, CScript scriptPubKeyIn); + + ADD_SERIALIZE_METHODS; + + template <typename Stream, typename Operation> + inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { + READWRITE(nValue); + READWRITE(scriptPubKey); + } + + void SetNull() + { + nValue = -1; + scriptPubKey.clear(); + } + + bool IsNull() const + { + return (nValue == -1); + } + + uint256 GetHash() const; + + bool IsDust(CFeeRate minRelayTxFee) const + { + // "Dust" is defined in terms of CTransaction::minRelayTxFee, + // which has units satoshis-per-kilobyte. + // If you'd pay more than 1/3 in fees + // to spend something, then we consider it dust. + // A typical txout is 34 bytes big, and will + // need a CTxIn of at least 148 bytes to spend: + // so dust is a txout less than 546 satoshis + // with default minRelayTxFee. + size_t nSize = GetSerializeSize(SER_DISK,0)+148u; + return (nValue < 3*minRelayTxFee.GetFee(nSize)); + } + + friend bool operator==(const CTxOut& a, const CTxOut& b) + { + return (a.nValue == b.nValue && + a.scriptPubKey == b.scriptPubKey); + } + + friend bool operator!=(const CTxOut& a, const CTxOut& b) + { + return !(a == b); + } + + std::string ToString() const; +}; + +struct CMutableTransaction; + +/** The basic transaction that is broadcasted on the network and contained in + * blocks. A transaction can contain multiple inputs and outputs. + */ +class CTransaction +{ +private: + /** Memory only. */ + const uint256 hash; + void UpdateHash() const; + +public: + static const int32_t CURRENT_VERSION=1; + + // The local variables are made const to prevent unintended modification + // without updating the cached hash value. However, CTransaction is not + // actually immutable; deserialization and assignment are implemented, + // and bypass the constness. This is safe, as they update the entire + // structure, including the hash. + const int32_t nVersion; + const std::vector<CTxIn> vin; + const std::vector<CTxOut> vout; + const uint32_t nLockTime; + + /** Construct a CTransaction that qualifies as IsNull() */ + CTransaction(); + + /** Convert a CMutableTransaction into a CTransaction. */ + CTransaction(const CMutableTransaction &tx); + + CTransaction& operator=(const CTransaction& tx); + + ADD_SERIALIZE_METHODS; + + template <typename Stream, typename Operation> + inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { + READWRITE(*const_cast<int32_t*>(&this->nVersion)); + nVersion = this->nVersion; + READWRITE(*const_cast<std::vector<CTxIn>*>(&vin)); + READWRITE(*const_cast<std::vector<CTxOut>*>(&vout)); + READWRITE(*const_cast<uint32_t*>(&nLockTime)); + if (ser_action.ForRead()) + UpdateHash(); + } + + bool IsNull() const { + return vin.empty() && vout.empty(); + } + + const uint256& GetHash() const { + return hash; + } + + // Return sum of txouts. + CAmount GetValueOut() const; + // GetValueIn() is a method on CCoinsViewCache, because + // inputs must be known to compute value in. + + // Compute priority, given priority of inputs and (optionally) tx size + double ComputePriority(double dPriorityInputs, unsigned int nTxSize=0) const; + + // Compute modified tx size for priority calculation (optionally given tx size) + unsigned int CalculateModifiedSize(unsigned int nTxSize=0) const; + + bool IsCoinBase() const + { + return (vin.size() == 1 && vin[0].prevout.IsNull()); + } + + friend bool operator==(const CTransaction& a, const CTransaction& b) + { + return a.hash == b.hash; + } + + friend bool operator!=(const CTransaction& a, const CTransaction& b) + { + return a.hash != b.hash; + } + + std::string ToString() const; +}; + +/** A mutable version of CTransaction. */ +struct CMutableTransaction +{ + int32_t nVersion; + std::vector<CTxIn> vin; + std::vector<CTxOut> vout; + uint32_t nLockTime; + + CMutableTransaction(); + CMutableTransaction(const CTransaction& tx); + + ADD_SERIALIZE_METHODS; + + template <typename Stream, typename Operation> + inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { + READWRITE(this->nVersion); + nVersion = this->nVersion; + READWRITE(vin); + READWRITE(vout); + READWRITE(nLockTime); + } + + /** Compute the hash of this CMutableTransaction. This is computed on the + * fly, as opposed to GetHash() in CTransaction, which uses a cached result. + */ + uint256 GetHash() const; +}; + +#endif // H_BITCOIN_CORE_TRANSACTION diff --git a/src/core_read.cpp b/src/core_read.cpp index dcbcf4b4f7..d39bc9a780 100644 --- a/src/core_read.cpp +++ b/src/core_read.cpp @@ -4,7 +4,7 @@ #include "core_io.h" -#include "core.h" +#include "core/transaction.h" #include "script/script.h" #include "serialize.h" #include "streams.h" diff --git a/src/core_write.cpp b/src/core_write.cpp index b2b29fb367..a3ae8eec07 100644 --- a/src/core_write.cpp +++ b/src/core_write.cpp @@ -5,7 +5,7 @@ #include "core_io.h" #include "base58.h" -#include "core.h" +#include "core/transaction.h" #include "script/script.h" #include "script/standard.h" #include "serialize.h" @@ -6,6 +6,7 @@ #ifndef BITCOIN_DB_H #define BITCOIN_DB_H +#include "clientversion.h" #include "serialize.h" #include "streams.h" #include "sync.h" diff --git a/src/init.cpp b/src/init.cpp index 70ac5190d3..3fd08ce006 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -10,6 +10,7 @@ #include "init.h" #include "addrman.h" +#include "amount.h" #include "checkpoints.h" #include "compat/sanity.h" #include "key.h" @@ -547,6 +548,10 @@ bool AppInit2(boost::thread_group& threadGroup) #endif // ********************************************************* Step 2: parameter interactions + // Set this early so that parameter interactions go to console + fPrintToConsole = GetBoolArg("-printtoconsole", false); + fLogTimestamps = GetBoolArg("-logtimestamps", true); + fLogIPs = GetBoolArg("-logips", false); if (mapArgs.count("-bind") || mapArgs.count("-whitebind")) { // when specifying an explicit binding address, you want to listen on it @@ -640,9 +645,6 @@ bool AppInit2(boost::thread_group& threadGroup) nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS; fServer = GetBoolArg("-server", false); - fPrintToConsole = GetBoolArg("-printtoconsole", false); - fLogTimestamps = GetBoolArg("-logtimestamps", true); - fLogIPs = GetBoolArg("-logips", false); #ifdef ENABLE_WALLET bool fDisableWallet = GetBoolArg("-disablewallet", false); #endif diff --git a/src/key.cpp b/src/key.cpp index 0f4bc6652c..c466e84f26 100644 --- a/src/key.cpp +++ b/src/key.cpp @@ -1,5 +1,5 @@ // Copyright (c) 2009-2014 The Bitcoin developers -// Distributed under the MIT/X11 software license, see the accompanying +// Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "key.h" @@ -13,7 +13,7 @@ #include "ecwrapper.h" #endif -// anonymous namespace +//! anonymous namespace namespace { #ifdef USE_SECP256K1 @@ -56,7 +56,7 @@ int CompareBigEndian(const unsigned char *c1, size_t c1len, const unsigned char return 0; } -// Order of secp256k1's generator minus 1. +/** Order of secp256k1's generator minus 1. */ const unsigned char vchMaxModOrder[32] = { 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFE, @@ -64,7 +64,7 @@ const unsigned char vchMaxModOrder[32] = { 0xBF,0xD2,0x5E,0x8C,0xD0,0x36,0x41,0x40 }; -// Half of the order of secp256k1's generator minus 1. +/** Half of the order of secp256k1's generator minus 1. */ const unsigned char vchMaxModHalfOrder[32] = { 0x7F,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, @@ -1,6 +1,6 @@ // Copyright (c) 2009-2010 Satoshi Nakamoto -// Copyright (c) 2009-2013 The Bitcoin developers -// Distributed under the MIT/X11 software license, see the accompanying +// Copyright (c) 2009-2014 The Bitcoin developers +// Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_KEY_H @@ -14,13 +14,15 @@ #include <stdexcept> #include <vector> -// secp256k1: -// const unsigned int PRIVATE_KEY_SIZE = 279; -// const unsigned int PUBLIC_KEY_SIZE = 65; -// const unsigned int SIGNATURE_SIZE = 72; -// -// see www.keylength.com -// script supports up to 75 for single byte push +/** + * secp256k1: + * const unsigned int PRIVATE_KEY_SIZE = 279; + * const unsigned int PUBLIC_KEY_SIZE = 65; + * const unsigned int SIGNATURE_SIZE = 72; + * + * see www.keylength.com + * script supports up to 75 for single byte push + */ /** A reference to a CKey: the Hash160 of its serialized public key */ class CKeyID : public uint160 @@ -34,11 +36,14 @@ public: class CPubKey { private: - // Just store the serialized data. - // Its length can very cheaply be computed from the first byte. + + /** + * Just store the serialized data. + * Its length can very cheaply be computed from the first byte. + */ unsigned char vch[65]; - // Compute the length of a pubkey with a given first byte. + //! Compute the length of a pubkey with a given first byte. unsigned int static GetLen(unsigned char chHeader) { if (chHeader == 2 || chHeader == 3) @@ -48,20 +53,20 @@ private: return 0; } - // Set this key data to be invalid + //! Set this key data to be invalid void Invalidate() { vch[0] = 0xFF; } public: - // Construct an invalid public key. + //! Construct an invalid public key. CPubKey() { Invalidate(); } - // Initialize a public key using begin/end iterators to byte data. + //! Initialize a public key using begin/end iterators to byte data. template <typename T> void Set(const T pbegin, const T pend) { @@ -72,26 +77,26 @@ public: Invalidate(); } - // Construct a public key using begin/end iterators to byte data. + //! Construct a public key using begin/end iterators to byte data. template <typename T> CPubKey(const T pbegin, const T pend) { Set(pbegin, pend); } - // Construct a public key from a byte vector. + //! Construct a public key from a byte vector. CPubKey(const std::vector<unsigned char>& vch) { Set(vch.begin(), vch.end()); } - // Simple read-only vector-like interface to the pubkey data. + //! Simple read-only vector-like interface to the pubkey data. unsigned int size() const { return GetLen(vch[0]); } const unsigned char* begin() const { return vch; } const unsigned char* end() const { return vch + size(); } const unsigned char& operator[](unsigned int pos) const { return vch[pos]; } - // Comparator implementation. + //! Comparator implementation. friend bool operator==(const CPubKey& a, const CPubKey& b) { return a.vch[0] == b.vch[0] && @@ -107,7 +112,7 @@ public: (a.vch[0] == b.vch[0] && memcmp(a.vch, b.vch, a.size()) < 0); } - // Implement serialization, as if this was a byte vector. + //! Implement serialization, as if this was a byte vector. unsigned int GetSerializeSize(int nType, int nVersion) const { return size() + 1; @@ -134,86 +139,92 @@ public: } } - // Get the KeyID of this public key (hash of its serialization) + //! Get the KeyID of this public key (hash of its serialization) CKeyID GetID() const { return CKeyID(Hash160(vch, vch + size())); } - // Get the 256-bit hash of this public key. + //! Get the 256-bit hash of this public key. uint256 GetHash() const { return Hash(vch, vch + size()); } - // Check syntactic correctness. - // - // Note that this is consensus critical as CheckSig() calls it! + /* + * Check syntactic correctness. + * + * Note that this is consensus critical as CheckSig() calls it! + */ bool IsValid() const { return size() > 0; } - // fully validate whether this is a valid public key (more expensive than IsValid()) + //! fully validate whether this is a valid public key (more expensive than IsValid()) bool IsFullyValid() const; - // Check whether this is a compressed public key. + //! Check whether this is a compressed public key. bool IsCompressed() const { return size() == 33; } - // Verify a DER signature (~72 bytes). - // If this public key is not fully valid, the return value will be false. + /** + * Verify a DER signature (~72 bytes). + * If this public key is not fully valid, the return value will be false. + */ bool Verify(const uint256& hash, const std::vector<unsigned char>& vchSig) const; - // Recover a public key from a compact signature. + //! Recover a public key from a compact signature. bool RecoverCompact(const uint256& hash, const std::vector<unsigned char>& vchSig); - // Turn this public key into an uncompressed public key. + //! Turn this public key into an uncompressed public key. bool Decompress(); - // Derive BIP32 child pubkey. + //! Derive BIP32 child pubkey. bool Derive(CPubKey& pubkeyChild, unsigned char ccChild[32], unsigned int nChild, const unsigned char cc[32]) const; }; -// secure_allocator is defined in allocators.h -// CPrivKey is a serialized private key, with all parameters included (279 bytes) +/** + * secure_allocator is defined in allocators.h + * CPrivKey is a serialized private key, with all parameters included (279 bytes) + */ typedef std::vector<unsigned char, secure_allocator<unsigned char> > CPrivKey; /** An encapsulated private key. */ class CKey { private: - // Whether this private key is valid. We check for correctness when modifying the key - // data, so fValid should always correspond to the actual state. + //! Whether this private key is valid. We check for correctness when modifying the key + //! data, so fValid should always correspond to the actual state. bool fValid; - // Whether the public key corresponding to this private key is (to be) compressed. + //! Whether the public key corresponding to this private key is (to be) compressed. bool fCompressed; - // The actual byte data + //! The actual byte data unsigned char vch[32]; - // Check whether the 32-byte array pointed to be vch is valid keydata. + //! Check whether the 32-byte array pointed to be vch is valid keydata. bool static Check(const unsigned char* vch); public: - // Construct an invalid private key. + //! Construct an invalid private key. CKey() : fValid(false), fCompressed(false) { LockObject(vch); } - // Copy constructor. This is necessary because of memlocking. + //! Copy constructor. This is necessary because of memlocking. CKey(const CKey& secret) : fValid(secret.fValid), fCompressed(secret.fCompressed) { LockObject(vch); memcpy(vch, secret.vch, sizeof(vch)); } - // Destructor (again necessary because of memlocking). + //! Destructor (again necessary because of memlocking). ~CKey() { UnlockObject(vch); @@ -225,7 +236,7 @@ public: memcmp(&a.vch[0], &b.vch[0], a.size()) == 0; } - // Initialize using begin and end iterators to byte data. + //! Initialize using begin and end iterators to byte data. template <typename T> void Set(const T pbegin, const T pend, bool fCompressedIn) { @@ -242,48 +253,54 @@ public: } } - // Simple read-only vector-like interface. + //! Simple read-only vector-like interface. unsigned int size() const { return (fValid ? 32 : 0); } const unsigned char* begin() const { return vch; } const unsigned char* end() const { return vch + size(); } - // Check whether this private key is valid. + //! Check whether this private key is valid. bool IsValid() const { return fValid; } - // Check whether the public key corresponding to this private key is (to be) compressed. + //! Check whether the public key corresponding to this private key is (to be) compressed. bool IsCompressed() const { return fCompressed; } - // Initialize from a CPrivKey (serialized OpenSSL private key data). + //! Initialize from a CPrivKey (serialized OpenSSL private key data). bool SetPrivKey(const CPrivKey& vchPrivKey, bool fCompressed); - // Generate a new private key using a cryptographic PRNG. + //! Generate a new private key using a cryptographic PRNG. void MakeNewKey(bool fCompressed); - // Convert the private key to a CPrivKey (serialized OpenSSL private key data). - // This is expensive. + /** + * Convert the private key to a CPrivKey (serialized OpenSSL private key data). + * This is expensive. + */ CPrivKey GetPrivKey() const; - // Compute the public key from a private key. - // This is expensive. + /** + * Compute the public key from a private key. + * This is expensive. + */ CPubKey GetPubKey() const; - // Create a DER-serialized signature. + //! Create a DER-serialized signature. bool Sign(const uint256& hash, std::vector<unsigned char>& vchSig, bool lowS = true) const; - // Create a compact signature (65 bytes), which allows reconstructing the used public key. - // The format is one header byte, followed by two times 32 bytes for the serialized r and s values. - // The header byte: 0x1B = first key with even y, 0x1C = first key with odd y, - // 0x1D = second key with even y, 0x1E = second key with odd y, - // add 0x04 for compressed keys. + /** + * Create a compact signature (65 bytes), which allows reconstructing the used public key. + * The format is one header byte, followed by two times 32 bytes for the serialized r and s values. + * The header byte: 0x1B = first key with even y, 0x1C = first key with odd y, + * 0x1D = second key with even y, 0x1E = second key with odd y, + * add 0x04 for compressed keys. + */ bool SignCompact(const uint256& hash, std::vector<unsigned char>& vchSig) const; - // Derive BIP32 child key. + //! Derive BIP32 child key. bool Derive(CKey& keyChild, unsigned char ccChild[32], unsigned int nChild, const unsigned char cc[32]) const; - // Load private key and check that public key matches. + //! Load private key and check that public key matches. bool Load(CPrivKey& privkey, CPubKey& vchPubKey, bool fSkipCheck); - // Check whether an element of a signature (r or s) is valid. + //! Check whether an element of a signature (r or s) is valid. static bool CheckSignatureElement(const unsigned char* vch, int len, bool half); }; diff --git a/src/keystore.cpp b/src/keystore.cpp index 039c690625..879f099720 100644 --- a/src/keystore.cpp +++ b/src/keystore.cpp @@ -1,6 +1,6 @@ // Copyright (c) 2009-2010 Satoshi Nakamoto -// Copyright (c) 2009-2013 The Bitcoin developers -// Distributed under the MIT/X11 software license, see the accompanying +// Copyright (c) 2009-2014 The Bitcoin developers +// Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "keystore.h" diff --git a/src/keystore.h b/src/keystore.h index 4f8189c8f5..66f8771d4a 100644 --- a/src/keystore.h +++ b/src/keystore.h @@ -1,6 +1,6 @@ // Copyright (c) 2009-2010 Satoshi Nakamoto -// Copyright (c) 2009-2013 The Bitcoin developers -// Distributed under the MIT/X11 software license, see the accompanying +// Copyright (c) 2009-2014 The Bitcoin developers +// Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_KEYSTORE_H @@ -24,22 +24,22 @@ protected: public: virtual ~CKeyStore() {} - // Add a key to the store. + //! Add a key to the store. virtual bool AddKeyPubKey(const CKey &key, const CPubKey &pubkey) =0; virtual bool AddKey(const CKey &key); - // Check whether a key corresponding to a given address is present in the store. + //! Check whether a key corresponding to a given address is present in the store. virtual bool HaveKey(const CKeyID &address) const =0; virtual bool GetKey(const CKeyID &address, CKey& keyOut) const =0; virtual void GetKeys(std::set<CKeyID> &setAddress) const =0; virtual bool GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const; - // Support for BIP 0013 : see https://github.com/bitcoin/bips/blob/master/bip-0013.mediawiki + //! Support for BIP 0013 : see https://github.com/bitcoin/bips/blob/master/bip-0013.mediawiki virtual bool AddCScript(const CScript& redeemScript) =0; virtual bool HaveCScript(const CScriptID &hash) const =0; virtual bool GetCScript(const CScriptID &hash, CScript& redeemScriptOut) const =0; - // Support for Watch-only addresses + //! Support for Watch-only addresses virtual bool AddWatchOnly(const CScript &dest) =0; virtual bool RemoveWatchOnly(const CScript &dest) =0; virtual bool HaveWatchOnly(const CScript &dest) const =0; diff --git a/src/leveldbwrapper.h b/src/leveldbwrapper.h index d997d56e00..10b7a2427c 100644 --- a/src/leveldbwrapper.h +++ b/src/leveldbwrapper.h @@ -5,6 +5,7 @@ #ifndef BITCOIN_LEVELDBWRAPPER_H #define BITCOIN_LEVELDBWRAPPER_H +#include "clientversion.h" #include "serialize.h" #include "streams.h" #include "util.h" diff --git a/src/main.h b/src/main.h index 1ef51918c5..1941ca7059 100644 --- a/src/main.h +++ b/src/main.h @@ -10,10 +10,12 @@ #include "config/bitcoin-config.h" #endif +#include "amount.h" #include "chain.h" #include "chainparams.h" #include "coins.h" -#include "core.h" +#include "core/block.h" +#include "core/transaction.h" #include "net.h" #include "pow.h" #include "script/script.h" @@ -23,6 +25,7 @@ #include "tinyformat.h" #include "txmempool.h" #include "uint256.h" +#include "undo.h" #include <algorithm> #include <exception> @@ -127,7 +130,6 @@ static const uint64_t nMinDiskSpace = 52428800; class CBlockTreeDB; -class CTxUndo; class CScriptCheck; class CValidationState; class CValidationInterface; diff --git a/src/miner.cpp b/src/miner.cpp index eefccfd641..0235de3ab3 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -5,7 +5,9 @@ #include "miner.h" -#include "core.h" +#include "amount.h" +#include "core/block.h" +#include "core/transaction.h" #include "hash.h" #include "main.h" #include "net.h" diff --git a/src/net.cpp b/src/net.cpp index 6cf64f51c3..5ceb82cf8b 100644 --- a/src/net.cpp +++ b/src/net.cpp @@ -11,7 +11,8 @@ #include "addrman.h" #include "chainparams.h" -#include "core.h" +#include "clientversion.h" +#include "core/transaction.h" #include "ui_interface.h" #ifdef WIN32 diff --git a/src/netbase.cpp b/src/netbase.cpp index b3d1001547..ea05b8766f 100644 --- a/src/netbase.cpp +++ b/src/netbase.cpp @@ -667,11 +667,28 @@ bool CNetAddr::IsRFC1918() const (GetByte(3) == 172 && (GetByte(2) >= 16 && GetByte(2) <= 31))); } +bool CNetAddr::IsRFC2544() const +{ + return IsIPv4() && GetByte(3) == 198 && (GetByte(2) == 18 || GetByte(2) == 19); +} + bool CNetAddr::IsRFC3927() const { return IsIPv4() && (GetByte(3) == 169 && GetByte(2) == 254); } +bool CNetAddr::IsRFC6598() const +{ + return IsIPv4() && GetByte(3) == 100 && GetByte(2) >= 64 && GetByte(2) <= 127; +} + +bool CNetAddr::IsRFC5737() const +{ + return IsIPv4() && ((GetByte(3) == 192 && GetByte(2) == 0 && GetByte(1) == 2) || + (GetByte(3) == 198 && GetByte(2) == 51 && GetByte(1) == 100) || + (GetByte(3) == 203 && GetByte(2) == 0 && GetByte(1) == 113)); +} + bool CNetAddr::IsRFC3849() const { return GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x0D && GetByte(12) == 0xB8; @@ -778,7 +795,7 @@ bool CNetAddr::IsValid() const bool CNetAddr::IsRoutable() const { - return IsValid() && !(IsRFC1918() || IsRFC3927() || IsRFC4862() || (IsRFC4193() && !IsTor()) || IsRFC4843() || IsLocal()); + return IsValid() && !(IsRFC1918() || IsRFC2544() || IsRFC3927() || IsRFC4862() || IsRFC6598() || IsRFC5737() || (IsRFC4193() && !IsTor()) || IsRFC4843() || IsLocal()); } enum Network CNetAddr::GetNetwork() const diff --git a/src/netbase.h b/src/netbase.h index 1455cd8c33..9d8697dcc6 100644 --- a/src/netbase.h +++ b/src/netbase.h @@ -61,6 +61,9 @@ class CNetAddr bool IsIPv4() const; // IPv4 mapped address (::FFFF:0:0/96, 0.0.0.0/0) bool IsIPv6() const; // IPv6 address (not mapped IPv4, not Tor) bool IsRFC1918() const; // IPv4 private networks (10.0.0.0/8, 192.168.0.0/16, 172.16.0.0/12) + bool IsRFC2544() const; // IPv4 inter-network communcations (192.18.0.0/15) + bool IsRFC6598() const; // IPv4 ISP-level NAT (100.64.0.0/10) + bool IsRFC5737() const; // IPv4 documentation addresses (192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24) bool IsRFC3849() const; // IPv6 documentation address (2001:0DB8::/32) bool IsRFC3927() const; // IPv4 autoconfig (169.254.0.0/16) bool IsRFC3964() const; // IPv6 6to4 tunnelling (2002::/16) diff --git a/src/pow.cpp b/src/pow.cpp index 75fbfc6a6d..af7fc488ef 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -6,7 +6,7 @@ #include "pow.h" #include "chainparams.h" -#include "core.h" +#include "core/block.h" #include "main.h" #include "timedata.h" #include "uint256.h" diff --git a/src/qt/bitcoingui.cpp b/src/qt/bitcoingui.cpp index f0471c32f9..77cfdceef0 100644 --- a/src/qt/bitcoingui.cpp +++ b/src/qt/bitcoingui.cpp @@ -19,7 +19,7 @@ #ifdef ENABLE_WALLET #include "walletframe.h" #include "walletmodel.h" -#endif +#endif // ENABLE_WALLET #ifdef Q_OS_MAC #include "macdockiconhandler.h" @@ -106,7 +106,7 @@ BitcoinGUI::BitcoinGUI(const NetworkStyle *networkStyle, QWidget *parent) : bool enableWallet = !GetBoolArg("-disablewallet", false); #else bool enableWallet = false; -#endif +#endif // ENABLE_WALLET if(enableWallet) { windowTitle += tr("Wallet"); @@ -136,7 +136,7 @@ BitcoinGUI::BitcoinGUI(const NetworkStyle *networkStyle, QWidget *parent) : walletFrame = new WalletFrame(this); setCentralWidget(walletFrame); } else -#endif +#endif // ENABLE_WALLET { /* When compiled without wallet or -disablewallet is provided, * the central widget is the rpc console. @@ -268,6 +268,7 @@ void BitcoinGUI::createActions(const NetworkStyle *networkStyle) historyAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_4)); tabGroup->addAction(historyAction); +#ifdef ENABLE_WALLET // These showNormalIfMinimized are needed because Send Coins and Receive Coins // can be triggered from the tray menu, and need to show the GUI to be useful. connect(overviewAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized())); @@ -278,6 +279,7 @@ void BitcoinGUI::createActions(const NetworkStyle *networkStyle) connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(gotoReceiveCoinsPage())); connect(historyAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized())); connect(historyAction, SIGNAL(triggered()), this, SLOT(gotoHistoryPage())); +#endif // ENABLE_WALLET quitAction = new QAction(QIcon(":/icons/quit"), tr("E&xit"), this); quitAction->setStatusTip(tr("Quit application")); @@ -343,7 +345,7 @@ void BitcoinGUI::createActions(const NetworkStyle *networkStyle) connect(usedReceivingAddressesAction, SIGNAL(triggered()), walletFrame, SLOT(usedReceivingAddresses())); connect(openAction, SIGNAL(triggered()), this, SLOT(openClicked())); } -#endif +#endif // ENABLE_WALLET } void BitcoinGUI::createMenuBar() @@ -433,7 +435,7 @@ void BitcoinGUI::setClientModel(ClientModel *clientModel) { walletFrame->setClientModel(clientModel); } -#endif +#endif // ENABLE_WALLET unitDisplayControl->setOptionsModel(clientModel->getOptionsModel()); } else { // Disable possibility to show main window via action @@ -469,7 +471,7 @@ void BitcoinGUI::removeAllWallets() setWalletActionsEnabled(false); walletFrame->removeAllWallets(); } -#endif +#endif // ENABLE_WALLET void BitcoinGUI::setWalletActionsEnabled(bool enabled) { @@ -616,7 +618,7 @@ void BitcoinGUI::gotoVerifyMessageTab(QString addr) { if (walletFrame) walletFrame->gotoVerifyMessageTab(addr); } -#endif +#endif // ENABLE_WALLET void BitcoinGUI::setNumConnections(int count) { @@ -676,7 +678,7 @@ void BitcoinGUI::setNumBlocks(int count) #ifdef ENABLE_WALLET if(walletFrame) walletFrame->showOutOfSyncWarning(false); -#endif +#endif // ENABLE_WALLET progressBarLabel->setVisible(false); progressBar->setVisible(false); @@ -727,7 +729,7 @@ void BitcoinGUI::setNumBlocks(int count) #ifdef ENABLE_WALLET if(walletFrame) walletFrame->showOutOfSyncWarning(true); -#endif +#endif // ENABLE_WALLET tooltip += QString("<br>"); tooltip += tr("Last received block was generated %1 ago.").arg(timeBehindText); @@ -850,7 +852,7 @@ void BitcoinGUI::incomingTransaction(const QString& date, int unit, const CAmoun .arg(type) .arg(address), CClientUIInterface::MSG_INFORMATION); } -#endif +#endif // ENABLE_WALLET void BitcoinGUI::dragEnterEvent(QDragEnterEvent *event) { @@ -924,7 +926,7 @@ void BitcoinGUI::setEncryptionStatus(int status) break; } } -#endif +#endif // ENABLE_WALLET void BitcoinGUI::showNormalIfMinimized(bool fToggleHidden) { diff --git a/src/qt/bitcoingui.h b/src/qt/bitcoingui.h index f65f0e9137..0ef4101127 100644 --- a/src/qt/bitcoingui.h +++ b/src/qt/bitcoingui.h @@ -63,7 +63,7 @@ public: bool addWallet(const QString& name, WalletModel *walletModel); bool setCurrentWallet(const QString& name); void removeAllWallets(); -#endif +#endif // ENABLE_WALLET protected: void changeEvent(QEvent *e); @@ -163,7 +163,7 @@ public slots: /** Show incoming transaction notification for new transactions. */ void incomingTransaction(const QString& date, int unit, const CAmount& amount, const QString& type, const QString& address); -#endif +#endif // ENABLE_WALLET private slots: #ifdef ENABLE_WALLET @@ -183,7 +183,7 @@ private slots: /** Show open dialog */ void openClicked(); -#endif +#endif // ENABLE_WALLET /** Show configuration dialog */ void optionsClicked(); /** Show about dialog */ diff --git a/src/qt/bitcoinunits.cpp b/src/qt/bitcoinunits.cpp index 423b559bf7..c85f569fd3 100644 --- a/src/qt/bitcoinunits.cpp +++ b/src/qt/bitcoinunits.cpp @@ -4,7 +4,7 @@ #include "bitcoinunits.h" -#include "core.h" +#include "core/transaction.h" #include <QStringList> diff --git a/src/qt/clientmodel.cpp b/src/qt/clientmodel.cpp index 738fb48ef8..aedda49071 100644 --- a/src/qt/clientmodel.cpp +++ b/src/qt/clientmodel.cpp @@ -10,6 +10,7 @@ #include "alert.h" #include "chainparams.h" #include "checkpoints.h" +#include "clientversion.h" #include "main.h" #include "net.h" #include "ui_interface.h" diff --git a/src/qt/guiutil.cpp b/src/qt/guiutil.cpp index 91bb10755a..22a1f019e9 100644 --- a/src/qt/guiutil.cpp +++ b/src/qt/guiutil.cpp @@ -9,7 +9,7 @@ #include "qvalidatedlineedit.h" #include "walletmodel.h" -#include "core.h" +#include "core/transaction.h" #include "init.h" #include "main.h" #include "protocol.h" diff --git a/src/qt/optionsmodel.cpp b/src/qt/optionsmodel.cpp index 6db654dff7..c941ebd4ca 100644 --- a/src/qt/optionsmodel.cpp +++ b/src/qt/optionsmodel.cpp @@ -11,6 +11,7 @@ #include "bitcoinunits.h" #include "guiutil.h" +#include "amount.h" #include "init.h" #include "main.h" #include "net.h" diff --git a/src/qt/recentrequeststablemodel.cpp b/src/qt/recentrequeststablemodel.cpp index 5deac8007c..5533adab8b 100644 --- a/src/qt/recentrequeststablemodel.cpp +++ b/src/qt/recentrequeststablemodel.cpp @@ -5,6 +5,7 @@ #include "recentrequeststablemodel.h" #include "bitcoinunits.h" +#include "clientversion.h" #include "guiutil.h" #include "optionsmodel.h" #include "streams.h" diff --git a/src/qt/utilitydialog.cpp b/src/qt/utilitydialog.cpp index 84f88dff5a..58bf040624 100644 --- a/src/qt/utilitydialog.cpp +++ b/src/qt/utilitydialog.cpp @@ -10,8 +10,8 @@ #include "clientmodel.h" #include "guiutil.h" +#include "clientversion.h" #include "init.h" -#include "version.h" #include <stdio.h> diff --git a/src/rpcmining.cpp b/src/rpcmining.cpp index c767835a27..8af3c46348 100644 --- a/src/rpcmining.cpp +++ b/src/rpcmining.cpp @@ -3,6 +3,7 @@ // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. +#include "amount.h" #include "chainparams.h" #include "core_io.h" #include "init.h" diff --git a/src/rpcmisc.cpp b/src/rpcmisc.cpp index 92ed1c3e2b..08e956c961 100644 --- a/src/rpcmisc.cpp +++ b/src/rpcmisc.cpp @@ -4,6 +4,7 @@ // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "base58.h" +#include "clientversion.h" #include "init.h" #include "main.h" #include "net.h" diff --git a/src/rpcnet.cpp b/src/rpcnet.cpp index 12dcd5b540..46b5f3d7ad 100644 --- a/src/rpcnet.cpp +++ b/src/rpcnet.cpp @@ -4,6 +4,7 @@ #include "rpcserver.h" +#include "clientversion.h" #include "main.h" #include "net.h" #include "netbase.h" diff --git a/src/rpcprotocol.cpp b/src/rpcprotocol.cpp index c99d113bc3..c2ce73106f 100644 --- a/src/rpcprotocol.cpp +++ b/src/rpcprotocol.cpp @@ -5,6 +5,7 @@ #include "rpcprotocol.h" +#include "clientversion.h" #include "tinyformat.h" #include "util.h" #include "utilstrencodings.h" diff --git a/src/rpcrawtransaction.cpp b/src/rpcrawtransaction.cpp index fdfcb59eeb..d3ce3b3191 100644 --- a/src/rpcrawtransaction.cpp +++ b/src/rpcrawtransaction.cpp @@ -4,7 +4,7 @@ // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "base58.h" -#include "core.h" +#include "core/transaction.h" #include "core_io.h" #include "init.h" #include "keystore.h" diff --git a/src/rpcserver.cpp b/src/rpcserver.cpp index 9668c78831..08ed73f6de 100644 --- a/src/rpcserver.cpp +++ b/src/rpcserver.cpp @@ -1,6 +1,6 @@ // Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers -// Distributed under the MIT/X11 software license, see the accompanying +// Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "rpcserver.h" @@ -34,7 +34,7 @@ using namespace std; static std::string strRPCUserColonPass; static bool fRPCRunning = false; -// These are created by StartRPCThreads, destroyed in StopRPCThreads +//! These are created by StartRPCThreads, destroyed in StopRPCThreads static asio::io_service* rpc_io_service = NULL; static map<string, boost::shared_ptr<deadline_timer> > deadlineTimers; static ssl::context* rpc_ssl_context = NULL; @@ -134,9 +134,9 @@ vector<unsigned char> ParseHexO(const Object& o, string strKey) } -/// -/// Note: This interface may still be subject to change. -/// +/** + * Note: This interface may still be subject to change. + */ string CRPCTable::help(string strCommand) const { @@ -232,11 +232,9 @@ Value stop(const Array& params, bool fHelp) -// -// Call Table -// - - +/** + * Call Table + */ static const CRPCCommand vRPCCommands[] = { // category name actor (function) okSafeMode threadSafe reqWallet // --------------------- ------------------------ ----------------------- ---------- ---------- --------- @@ -453,7 +451,7 @@ private: void ServiceConnection(AcceptedConnection *conn); -// Forward declaration required for RPCListen +//! Forward declaration required for RPCListen template <typename Protocol, typename SocketAcceptorService> static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, ssl::context& context, @@ -669,7 +667,7 @@ void StartRPCThreads() fListening = true; rpc_acceptors.push_back(acceptor); - // If dual IPv6/IPv4 bind succesful, skip binding to IPv4 separately + // If dual IPv6/IPv4 bind successful, skip binding to IPv4 separately if(bBindAny && bindAddress == asio::ip::address_v6::any() && !v6_only_error) break; } diff --git a/src/rpcserver.h b/src/rpcserver.h index d440035f15..cc444cef1f 100644 --- a/src/rpcserver.h +++ b/src/rpcserver.h @@ -1,6 +1,6 @@ // Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers -// Distributed under the MIT/X11 software license, see the accompanying +// Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef _BITCOINRPC_SERVER_H_ @@ -32,9 +32,10 @@ public: virtual void close() = 0; }; -/* Start RPC threads */ +/** Start RPC threads */ void StartRPCThreads(); -/* Alternative to StartRPCThreads for the GUI, when no server is +/** + * Alternative to StartRPCThreads for the GUI, when no server is * used. The RPC thread in this case is only used to handle timeouts. * If real RPC threads have already been started this is a no-op. */ @@ -44,23 +45,23 @@ void StopRPCThreads(); /* Query whether RPC is running */ bool IsRPCRunning(); -/* - Type-check arguments; throws JSONRPCError if wrong type given. Does not check that - the right number of arguments are passed, just that any passed are the correct type. - Use like: RPCTypeCheck(params, boost::assign::list_of(str_type)(int_type)(obj_type)); -*/ +/** + * Type-check arguments; throws JSONRPCError if wrong type given. Does not check that + * the right number of arguments are passed, just that any passed are the correct type. + * Use like: RPCTypeCheck(params, boost::assign::list_of(str_type)(int_type)(obj_type)); + */ void RPCTypeCheck(const json_spirit::Array& params, const std::list<json_spirit::Value_type>& typesExpected, bool fAllowNull=false); -/* - Check for expected keys/value types in an Object. - Use like: RPCTypeCheck(object, boost::assign::map_list_of("name", str_type)("value", int_type)); -*/ +/** + * Check for expected keys/value types in an Object. + * Use like: RPCTypeCheck(object, boost::assign::map_list_of("name", str_type)("value", int_type)); + */ void RPCTypeCheck(const json_spirit::Object& o, const std::map<std::string, json_spirit::Value_type>& typesExpected, bool fAllowNull=false); -/* - Run func nSeconds from now. Uses boost deadline timers. - Overrides previous timer <name> (if any). +/** + * Run func nSeconds from now. Uses boost deadline timers. + * Overrides previous timer <name> (if any). */ void RPCRunLater(const std::string& name, boost::function<void(void)> func, int64_t nSeconds); @@ -104,10 +105,10 @@ public: extern const CRPCTable tableRPC; -// -// Utilities: convert hex-encoded Values -// (throws error if not hex). -// +/** + * Utilities: convert hex-encoded Values + * (throws error if not hex). + */ extern uint256 ParseHashV(const json_spirit::Value& v, std::string strName); extern uint256 ParseHashO(const json_spirit::Object& o, std::string strKey); extern std::vector<unsigned char> ParseHexV(const json_spirit::Value& v, std::string strName); diff --git a/src/rpcwallet.cpp b/src/rpcwallet.cpp index 68bb4068b8..2728fb4fb3 100644 --- a/src/rpcwallet.cpp +++ b/src/rpcwallet.cpp @@ -3,6 +3,7 @@ // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. +#include "amount.h" #include "base58.h" #include "core_io.h" #include "rpcserver.h" diff --git a/src/script/interpreter.cpp b/src/script/interpreter.cpp index 11c909472a..3625972ebf 100644 --- a/src/script/interpreter.cpp +++ b/src/script/interpreter.cpp @@ -5,7 +5,7 @@ #include "interpreter.h" -#include "core.h" +#include "core/transaction.h" #include "crypto/ripemd160.h" #include "crypto/sha1.h" #include "crypto/sha2.h" diff --git a/src/script/sign.cpp b/src/script/sign.cpp index bf98c40394..0eab0626e5 100644 --- a/src/script/sign.cpp +++ b/src/script/sign.cpp @@ -5,7 +5,7 @@ #include "script/sign.h" -#include "core.h" +#include "core/transaction.h" #include "key.h" #include "keystore.h" #include "script/standard.h" diff --git a/src/test/alert_tests.cpp b/src/test/alert_tests.cpp index 28610f0d2e..9cf7a98f46 100644 --- a/src/test/alert_tests.cpp +++ b/src/test/alert_tests.cpp @@ -7,13 +7,13 @@ // #include "alert.h" +#include "clientversion.h" #include "data/alertTests.raw.h" #include "serialize.h" #include "streams.h" #include "util.h" #include "utilstrencodings.h" -#include "version.h" #include <fstream> diff --git a/src/test/bloom_tests.cpp b/src/test/bloom_tests.cpp index 99b21a23a0..783e284af5 100644 --- a/src/test/bloom_tests.cpp +++ b/src/test/bloom_tests.cpp @@ -5,6 +5,7 @@ #include "bloom.h" #include "base58.h" +#include "clientversion.h" #include "key.h" #include "main.h" #include "serialize.h" diff --git a/src/test/checkblock_tests.cpp b/src/test/checkblock_tests.cpp index 9151fdc0c8..fc36b43e16 100644 --- a/src/test/checkblock_tests.cpp +++ b/src/test/checkblock_tests.cpp @@ -8,6 +8,7 @@ +#include "clientversion.h" #include "main.h" #include "utiltime.h" diff --git a/src/test/compress_tests.cpp b/src/test/compress_tests.cpp index 719955ba85..bf404cf0cf 100644 --- a/src/test/compress_tests.cpp +++ b/src/test/compress_tests.cpp @@ -2,7 +2,7 @@ // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. -#include "main.h" +#include "compressor.h" #include "util.h" #include <stdint.h> diff --git a/src/test/main_tests.cpp b/src/test/main_tests.cpp index 70a800af51..78c4181409 100644 --- a/src/test/main_tests.cpp +++ b/src/test/main_tests.cpp @@ -2,7 +2,7 @@ // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. -#include "core.h" +#include "core/transaction.h" #include "main.h" #include <boost/test/unit_test.hpp> diff --git a/src/test/transaction_tests.cpp b/src/test/transaction_tests.cpp index c46c31e99f..d4c9b1a0ea 100644 --- a/src/test/transaction_tests.cpp +++ b/src/test/transaction_tests.cpp @@ -5,6 +5,7 @@ #include "data/tx_invalid.json.h" #include "data/tx_valid.json.h" +#include "clientversion.h" #include "key.h" #include "keystore.h" #include "main.h" diff --git a/src/test/util_tests.cpp b/src/test/util_tests.cpp index 61daa0a3fe..67d50fccf4 100644 --- a/src/test/util_tests.cpp +++ b/src/test/util_tests.cpp @@ -4,12 +4,12 @@ #include "util.h" -#include "core.h" +#include "clientversion.h" +#include "core/transaction.h" #include "random.h" #include "sync.h" #include "utilstrencodings.h" #include "utilmoneystr.h" -#include "version.h" #include <stdint.h> #include <vector> diff --git a/src/txdb.cpp b/src/txdb.cpp index 8a73ce961c..0731d843f3 100644 --- a/src/txdb.cpp +++ b/src/txdb.cpp @@ -5,7 +5,6 @@ #include "txdb.h" -#include "core.h" #include "pow.h" #include "uint256.h" diff --git a/src/txmempool.cpp b/src/txmempool.cpp index b0d6b4aefa..d3d9cb8a01 100644 --- a/src/txmempool.cpp +++ b/src/txmempool.cpp @@ -5,7 +5,7 @@ #include "txmempool.h" -#include "core.h" +#include "clientversion.h" #include "streams.h" #include "util.h" #include "utilmoneystr.h" diff --git a/src/txmempool.h b/src/txmempool.h index 85cf5310ff..2ec80cb860 100644 --- a/src/txmempool.h +++ b/src/txmempool.h @@ -8,8 +8,9 @@ #include <list> +#include "amount.h" #include "coins.h" -#include "core.h" +#include "core/transaction.h" #include "sync.h" class CAutoFile; diff --git a/src/undo.h b/src/undo.h new file mode 100644 index 0000000000..232c193429 --- /dev/null +++ b/src/undo.h @@ -0,0 +1,71 @@ +// Copyright (c) 2009-2010 Satoshi Nakamoto +// Copyright (c) 2009-2013 The Bitcoin developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#ifndef H_BITCOIN_TXUNDO +#define H_BITCOIN_TXUNDO + +#include "compressor.h" +#include "core/transaction.h" +#include "serialize.h" + +/** Undo information for a CTxIn + * + * Contains the prevout's CTxOut being spent, and if this was the + * last output of the affected transaction, its metadata as well + * (coinbase or not, height, transaction version) + */ +class CTxInUndo +{ +public: + CTxOut txout; // the txout data before being spent + bool fCoinBase; // if the outpoint was the last unspent: whether it belonged to a coinbase + unsigned int nHeight; // if the outpoint was the last unspent: its height + int nVersion; // if the outpoint was the last unspent: its version + + CTxInUndo() : txout(), fCoinBase(false), nHeight(0), nVersion(0) {} + CTxInUndo(const CTxOut &txoutIn, bool fCoinBaseIn = false, unsigned int nHeightIn = 0, int nVersionIn = 0) : txout(txoutIn), fCoinBase(fCoinBaseIn), nHeight(nHeightIn), nVersion(nVersionIn) { } + + unsigned int GetSerializeSize(int nType, int nVersion) const { + return ::GetSerializeSize(VARINT(nHeight*2+(fCoinBase ? 1 : 0)), nType, nVersion) + + (nHeight > 0 ? ::GetSerializeSize(VARINT(this->nVersion), nType, nVersion) : 0) + + ::GetSerializeSize(CTxOutCompressor(REF(txout)), nType, nVersion); + } + + template<typename Stream> + void Serialize(Stream &s, int nType, int nVersion) const { + ::Serialize(s, VARINT(nHeight*2+(fCoinBase ? 1 : 0)), nType, nVersion); + if (nHeight > 0) + ::Serialize(s, VARINT(this->nVersion), nType, nVersion); + ::Serialize(s, CTxOutCompressor(REF(txout)), nType, nVersion); + } + + template<typename Stream> + void Unserialize(Stream &s, int nType, int nVersion) { + unsigned int nCode = 0; + ::Unserialize(s, VARINT(nCode), nType, nVersion); + nHeight = nCode / 2; + fCoinBase = nCode & 1; + if (nHeight > 0) + ::Unserialize(s, VARINT(this->nVersion), nType, nVersion); + ::Unserialize(s, REF(CTxOutCompressor(REF(txout))), nType, nVersion); + } +}; + +/** Undo information for a CTransaction */ +class CTxUndo +{ +public: + // undo information for all txins + std::vector<CTxInUndo> vprevout; + + ADD_SERIALIZE_METHODS; + + template <typename Stream, typename Operation> + inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { + READWRITE(vprevout); + } +}; + +#endif // H_BITCOIN_TXUNDO diff --git a/src/utilmoneystr.cpp b/src/utilmoneystr.cpp index 95be06aa18..267a5b845c 100644 --- a/src/utilmoneystr.cpp +++ b/src/utilmoneystr.cpp @@ -5,7 +5,7 @@ #include "utilmoneystr.h" -#include "core.h" +#include "core/transaction.h" #include "tinyformat.h" #include "utilstrencodings.h" diff --git a/src/version.h b/src/version.h index a1e440de24..6ee08c205b 100644 --- a/src/version.h +++ b/src/version.h @@ -5,25 +5,6 @@ #ifndef BITCOIN_VERSION_H #define BITCOIN_VERSION_H -#include "clientversion.h" - -#include <string> -#include <vector> - -// -// client versioning -// - -static const int CLIENT_VERSION = - 1000000 * CLIENT_VERSION_MAJOR - + 10000 * CLIENT_VERSION_MINOR - + 100 * CLIENT_VERSION_REVISION - + 1 * CLIENT_VERSION_BUILD; - -extern const std::string CLIENT_NAME; -extern const std::string CLIENT_BUILD; -extern const std::string CLIENT_DATE; - // // network protocol versioning // @@ -53,7 +34,4 @@ static const int BIP0031_VERSION = 60000; // "mempool" command, enhanced "getdata" behavior starts with this version static const int MEMPOOL_GD_VERSION = 60002; -std::string FormatFullVersion(); -std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments); - #endif // BITCOIN_VERSION_H diff --git a/src/wallet.cpp b/src/wallet.cpp index 3812c22fe2..d392149dbb 100644 --- a/src/wallet.cpp +++ b/src/wallet.cpp @@ -1,6 +1,6 @@ // Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers -// Distributed under the MIT/X11 software license, see the accompanying +// Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "wallet.h" @@ -22,18 +22,23 @@ using namespace std; -// Settings +/** + * Settings + */ CFeeRate payTxFee(DEFAULT_TRANSACTION_FEE); unsigned int nTxConfirmTarget = 1; bool bSpendZeroConfChange = true; -/** Fees smaller than this (in satoshi) are considered zero fee (for transaction creation) */ -CFeeRate CWallet::minTxFee = CFeeRate(10000); // Override with -mintxfee +/** + * Fees smaller than this (in satoshi) are considered zero fee (for transaction creation) + * Override with -mintxfee + */ +CFeeRate CWallet::minTxFee = CFeeRate(10000); -////////////////////////////////////////////////////////////////////////////// -// -// mapWallet -// +/** @defgroup mapWallet + * + * @{ + */ struct CompareValueOnly { @@ -367,8 +372,10 @@ void CWallet::SyncMetaData(pair<TxSpends::iterator, TxSpends::iterator> range) } } -// Outpoint is spent if any non-conflicted transaction -// spends it: +/** + * Outpoint is spent if any non-conflicted transaction + * spends it: + */ bool CWallet::IsSpent(const uint256& hash, unsigned int n) const { const COutPoint outpoint(hash, n); @@ -477,7 +484,7 @@ bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase) { if (!pwalletdbEncryption->TxnCommit()) { delete pwalletdbEncryption; - // We now have keys encrypted in memory, but no on disk... + // We now have keys encrypted in memory, but not on disk... // die to avoid confusion and let the user reload their unencrypted wallet. assert(false); } @@ -667,9 +674,11 @@ bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFromLoadWallet) return true; } -// Add a transaction to the wallet, or update it. -// pblock is optional, but should be provided if the transaction is known to be in a block. -// If fUpdate is true, existing transactions will be updated. +/** + * Add a transaction to the wallet, or update it. + * pblock is optional, but should be provided if the transaction is known to be in a block. + * If fUpdate is true, existing transactions will be updated. + */ bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate) { { @@ -911,9 +920,11 @@ bool CWalletTx::WriteToDisk() return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this); } -// Scan the block chain (starting in pindexStart) for transactions -// from or to us. If fUpdate is true, found transactions that already -// exist in the wallet will be updated. +/** + * Scan the block chain (starting in pindexStart) for transactions + * from or to us. If fUpdate is true, found transactions that already + * exist in the wallet will be updated. + */ int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate) { int ret = 0; @@ -1035,15 +1046,15 @@ void CWallet::ResendWalletTransactions() } } +/** @} */ // end of mapWallet - -////////////////////////////////////////////////////////////////////////////// -// -// Actions -// +/** @defgroup Actions + * + * @{ + */ CAmount CWallet::GetBalance() const @@ -1136,7 +1147,9 @@ CAmount CWallet::GetImmatureWatchOnlyBalance() const return nTotal; } -// populate vCoins with vector of available COutputs. +/** + * populate vCoins with vector of available COutputs. + */ void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl) const { vCoins.clear(); @@ -1194,7 +1207,7 @@ static void ApproximateBestSubset(vector<pair<CAmount, pair<const CWalletTx*,uns //The solver here uses a randomized algorithm, //the randomness serves no real security purpose but is just //needed to prevent degenerate behavior and it is important - //that the rng fast. We do not use a constant random sequence, + //that the rng is fast. We do not use a constant random sequence, //because there may be some privacy improvement by making //the selection random. if (nPass == 0 ? insecure_rand()&1 : !vfIncluded[i]) @@ -1524,7 +1537,9 @@ bool CWallet::CreateTransaction(CScript scriptPubKey, const CAmount& nValue, return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, strFailReason, coinControl); } -// Call after CreateTransaction unless you want to abort +/** + * Call after CreateTransaction unless you want to abort + */ bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey) { { @@ -1669,7 +1684,7 @@ DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx) setKeyPool.clear(); // Note: can't top-up keypool here, because wallet is locked. // User will be prompted to unlock wallet the next operation - // the requires a new key. + // that requires a new key. } } @@ -1736,10 +1751,10 @@ bool CWallet::SetDefaultKey(const CPubKey &vchPubKey) return true; } -// -// Mark old keypool keys as used, -// and generate all new keys -// +/** + * Mark old keypool keys as used, + * and generate all new keys + */ bool CWallet::NewKeyPool() { { @@ -2120,6 +2135,7 @@ void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts) } } +/** @} */ // end of Actions class CAffectedKeysVisitor : public boost::static_visitor<void> { private: diff --git a/src/wallet.h b/src/wallet.h index 9b6895090c..b692ad056b 100644 --- a/src/wallet.h +++ b/src/wallet.h @@ -1,12 +1,14 @@ // Copyright (c) 2009-2010 Satoshi Nakamoto -// Copyright (c) 2009-2013 The Bitcoin developers -// Distributed under the MIT/X11 software license, see the accompanying +// Copyright (c) 2009-2014 The Bitcoin developers +// Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_WALLET_H #define BITCOIN_WALLET_H -#include "core.h" +#include "amount.h" +#include "core/block.h" +#include "core/transaction.h" #include "crypter.h" #include "key.h" #include "keystore.h" @@ -24,16 +26,18 @@ #include <utility> #include <vector> -// Settings +/** + * Settings + */ extern CFeeRate payTxFee; extern unsigned int nTxConfirmTarget; extern bool bSpendZeroConfChange; -// -paytxfee default +//! -paytxfee default static const CAmount DEFAULT_TRANSACTION_FEE = 0; -// -paytxfee will warn if called with a higher fee than this amount (in satoshis) per KB +//! -paytxfee will warn if called with a higher fee than this amount (in satoshis) per KB static const CAmount nHighTransactionFeeWarning = 0.01 * COIN; -// Largest (in bytes) free transaction we're willing to create +//! Largest (in bytes) free transaction we're willing to create static const unsigned int MAX_FREE_TRANSACTION_CREATE_SIZE = 1000; class CAccountingEntry; @@ -92,7 +96,8 @@ public: StringMap destdata; }; -/** A CWallet is an extension of a keystore, which also maintains a set of transactions and balances, +/** + * A CWallet is an extension of a keystore, which also maintains a set of transactions and balances, * and provides the ability to create new transactions. */ class CWallet : public CCryptoKeyStore, public CValidationInterface @@ -102,18 +107,20 @@ private: CWalletDB *pwalletdbEncryption; - // the current wallet version: clients below this version are not able to load the wallet + //! the current wallet version: clients below this version are not able to load the wallet int nWalletVersion; - // the maximum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded + //! the maximum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded int nWalletMaxVersion; int64_t nNextResend; int64_t nLastResend; - // Used to keep track of spent outpoints, and - // detect and report conflicts (double-spends or - // mutated transactions where the mutant gets mined). + /** + * Used to keep track of spent outpoints, and + * detect and report conflicts (double-spends or + * mutated transactions where the mutant gets mined). + */ typedef std::multimap<COutPoint, uint256> TxSpends; TxSpends mapTxSpends; void AddToSpends(const COutPoint& outpoint, const uint256& wtxid); @@ -122,11 +129,13 @@ private: void SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator>); public: - /// Main wallet lock. - /// This lock protects all the fields added by CWallet - /// except for: - /// fFileBacked (immutable after instantiation) - /// strWalletFile (immutable after instantiation) + /* + * Main wallet lock. + * This lock protects all the fields added by CWallet + * except for: + * fFileBacked (immutable after instantiation) + * strWalletFile (immutable after instantiation) + */ mutable CCriticalSection cs_wallet; bool fFileBacked; @@ -186,7 +195,7 @@ public: const CWalletTx* GetWalletTx(const uint256& hash) const; - // check whether we are allowed to upgrade (or already support) to the named feature + //! check whether we are allowed to upgrade (or already support) to the named feature bool CanSupportFeature(enum WalletFeature wf) { AssertLockHeld(cs_wallet); return nWalletMaxVersion >= wf; } void AvailableCoins(std::vector<COutput>& vCoins, bool fOnlyConfirmed=true, const CCoinControl *coinControl = NULL) const; @@ -200,38 +209,40 @@ public: void UnlockAllCoins(); void ListLockedCoins(std::vector<COutPoint>& vOutpts); - // keystore implementation - // Generate a new key + /** + * keystore implementation + * Generate a new key + */ CPubKey GenerateNewKey(); - // Adds a key to the store, and saves it to disk. + //! Adds a key to the store, and saves it to disk. bool AddKeyPubKey(const CKey& key, const CPubKey &pubkey); - // Adds a key to the store, without saving it to disk (used by LoadWallet) + //! Adds a key to the store, without saving it to disk (used by LoadWallet) bool LoadKey(const CKey& key, const CPubKey &pubkey) { return CCryptoKeyStore::AddKeyPubKey(key, pubkey); } - // Load metadata (used by LoadWallet) + //! Load metadata (used by LoadWallet) bool LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &metadata); bool LoadMinVersion(int nVersion) { AssertLockHeld(cs_wallet); nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; } - // Adds an encrypted key to the store, and saves it to disk. + //! Adds an encrypted key to the store, and saves it to disk. bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret); - // Adds an encrypted key to the store, without saving it to disk (used by LoadWallet) + //! Adds an encrypted key to the store, without saving it to disk (used by LoadWallet) bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret); bool AddCScript(const CScript& redeemScript); bool LoadCScript(const CScript& redeemScript); - /// Adds a destination data tuple to the store, and saves it to disk + //! Adds a destination data tuple to the store, and saves it to disk bool AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value); - /// Erases a destination data tuple in the store and on disk + //! Erases a destination data tuple in the store and on disk bool EraseDestData(const CTxDestination &dest, const std::string &key); - /// Adds a destination data tuple to the store, without saving it to disk + //! Adds a destination data tuple to the store, without saving it to disk bool LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value); - /// Look up a destination data tuple in the store, return true if found false otherwise + //! Look up a destination data tuple in the store, return true if found false otherwise bool GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const; - // Adds a watch-only address to the store, and saves it to disk. + //! Adds a watch-only address to the store, and saves it to disk. bool AddWatchOnly(const CScript &dest); bool RemoveWatchOnly(const CScript &dest); - // Adds a watch-only address to the store, without saving it to disk (used by LoadWallet) + //! Adds a watch-only address to the store, without saving it to disk (used by LoadWallet) bool LoadWatchOnly(const CScript &dest); bool Unlock(const SecureString& strWalletPassphrase); @@ -240,17 +251,19 @@ public: void GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const; - /** Increment the next transaction order id - @return next transaction order id + /** + * Increment the next transaction order id + * @return next transaction order id */ int64_t IncOrderPosNext(CWalletDB *pwalletdb = NULL); typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair; typedef std::multimap<int64_t, TxPair > TxItems; - /** Get the wallet's activity log - @return multimap of ordered transactions and accounting entries - @warning Returned pointers are *only* valid within the scope of passed acentries + /** + * Get the wallet's activity log + * @return multimap of ordered transactions and accounting entries + * @warning Returned pointers are *only* valid within the scope of passed acentries */ TxItems OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount = ""); @@ -318,7 +331,8 @@ public: return true; return false; } - bool IsFromMe(const CTransaction& tx) const // should probably be renamed to IsRelevantToMe + /** should probably be renamed to IsRelevantToMe */ + bool IsFromMe(const CTransaction& tx) const { return (GetDebit(tx, ISMINE_ALL) > 0); } @@ -384,19 +398,20 @@ public: bool SetDefaultKey(const CPubKey &vchPubKey); - // signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower + //! signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false); - // change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format) + //! change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format) bool SetMaxVersion(int nVersion); - // get the current wallet format (the oldest client version guaranteed to understand this wallet) + //! get the current wallet format (the oldest client version guaranteed to understand this wallet) int GetVersion() { LOCK(cs_wallet); return nWalletVersion; } - // Get wallet transactions that conflict with given transaction (spend same outputs) + //! Get wallet transactions that conflict with given transaction (spend same outputs) std::set<uint256> GetConflicts(const uint256& txid) const; - /** Address book entry changed. + /** + * Address book entry changed. * @note called with lock cs_wallet held. */ boost::signals2::signal<void (CWallet *wallet, const CTxDestination @@ -404,7 +419,8 @@ public: const std::string &purpose, ChangeType status)> NotifyAddressBookChanged; - /** Wallet transaction added, removed or updated. + /** + * Wallet transaction added, removed or updated. * @note called with lock cs_wallet held. */ boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx, @@ -515,10 +531,13 @@ public: int SetMerkleBranch(const CBlock& block); - // Return depth of transaction in blockchain: - // -1 : not in blockchain, and not in memory pool (conflicted transaction) - // 0 : in memory pool, waiting to be included in a block - // >=1 : this many blocks deep in the main chain + + /** + * Return depth of transaction in blockchain: + * -1 : not in blockchain, and not in memory pool (conflicted transaction) + * 0 : in memory pool, waiting to be included in a block + * >=1 : this many blocks deep in the main chain + */ int GetDepthInMainChain(const CBlockIndex* &pindexRet) const; int GetDepthInMainChain() const { const CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); } bool IsInMainChain() const { const CBlockIndex *pindexRet; return GetDepthInMainChainINTERNAL(pindexRet) > 0; } @@ -526,7 +545,8 @@ public: bool AcceptToMemoryPool(bool fLimitFree=true, bool fRejectInsaneFee=true); }; -/** A transaction with a bunch of additional info that only the owner cares about. +/** + * A transaction with a bunch of additional info that only the owner cares about. * It includes any unrecorded transactions needed to link it back to the block chain. */ class CWalletTx : public CMerkleTx @@ -538,11 +558,11 @@ public: mapValue_t mapValue; std::vector<std::pair<std::string, std::string> > vOrderForm; unsigned int fTimeReceivedIsTxTime; - unsigned int nTimeReceived; // time received by this node + unsigned int nTimeReceived; //! time received by this node unsigned int nTimeSmart; char fFromMe; std::string strFromAccount; - int64_t nOrderPos; // position in ordered transaction list + int64_t nOrderPos; //! position in ordered transaction list // memory only mutable bool fDebitCached; @@ -634,7 +654,7 @@ public: } READWRITE(*(CMerkleTx*)this); - std::vector<CMerkleTx> vUnused; // Used to be vtxPrev + std::vector<CMerkleTx> vUnused; //! Used to be vtxPrev READWRITE(vUnused); READWRITE(mapValue); READWRITE(vOrderForm); @@ -659,7 +679,7 @@ public: mapValue.erase("timesmart"); } - // make sure balances are recalculated + //! make sure balances are recalculated void MarkDirty() { fCreditCached = false; @@ -678,7 +698,7 @@ public: MarkDirty(); } - // filter decides which addresses will count towards the debit + //! filter decides which addresses will count towards the debit CAmount GetDebit(const isminefilter& filter) const { if (vin.empty()) @@ -917,8 +937,8 @@ public: int64_t nTimeCreated; int64_t nTimeExpires; std::string strComment; - //// todo: add something to note what created it (user, getnewaddress, change) - //// maybe should have a map<string, string> property map + //! todo: add something to note what created it (user, getnewaddress, change) + //! maybe should have a map<string, string> property map CWalletKey(int64_t nExpires=0); @@ -940,7 +960,8 @@ public: -/** Account information. +/** + * Account information. * Stored in wallet with key "acc"+string account name. */ class CAccount @@ -970,7 +991,8 @@ public: -/** Internal transfers. +/** + * Internal transfers. * Database key is acentry<account><counter>. */ class CAccountingEntry @@ -982,7 +1004,7 @@ public: std::string strOtherAccount; std::string strComment; mapValue_t mapValue; - int64_t nOrderPos; // position in ordered transaction list + int64_t nOrderPos; //! position in ordered transaction list uint64_t nEntryNo; CAccountingEntry() @@ -1007,7 +1029,7 @@ public: inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { if (!(nType & SER_GETHASH)) READWRITE(nVersion); - // Note: strAccount is serialized as part of the key, not here. + //! Note: strAccount is serialized as part of the key, not here. READWRITE(nCreditDebit); READWRITE(nTime); READWRITE(LIMITED_STRING(strOtherAccount, 65536)); |