1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2013 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
10 #include "serialize.h"
17 /** No amount larger than this (in satoshi) is valid */
18 static const int64_t MAX_MONEY = 21000000 * COIN;
19 inline bool MoneyRange(int64_t nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
21 /** An outpoint - a combination of a transaction hash and an index n into its vout */
28 COutPoint() { SetNull(); }
29 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
30 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
31 void SetNull() { hash = 0; n = (unsigned int) -1; }
32 bool IsNull() const { return (hash == 0 && n == (unsigned int) -1); }
34 friend bool operator<(const COutPoint& a, const COutPoint& b)
36 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
39 friend bool operator==(const COutPoint& a, const COutPoint& b)
41 return (a.hash == b.hash && a.n == b.n);
44 friend bool operator!=(const COutPoint& a, const COutPoint& b)
49 std::string ToString() const;
53 /** An inpoint - a combination of a transaction and an index n into its vin */
57 const CTransaction* ptx;
60 CInPoint() { SetNull(); }
61 CInPoint(const CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
62 void SetNull() { ptx = NULL; n = (unsigned int) -1; }
63 bool IsNull() const { return (ptx == NULL && n == (unsigned int) -1); }
66 /** An input of a transaction. It contains the location of the previous
67 * transaction's output that it claims and a signature that matches the
68 * output's public key.
75 unsigned int nSequence;
79 nSequence = std::numeric_limits<unsigned int>::max();
82 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max());
83 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max());
94 return (nSequence == std::numeric_limits<unsigned int>::max());
97 friend bool operator==(const CTxIn& a, const CTxIn& b)
99 return (a.prevout == b.prevout &&
100 a.scriptSig == b.scriptSig &&
101 a.nSequence == b.nSequence);
104 friend bool operator!=(const CTxIn& a, const CTxIn& b)
109 std::string ToString() const;
115 /** Type-safe wrapper class to for fee rates
116 * (how much to pay based on transaction size)
121 int64_t nSatoshisPerK; // unit is satoshis-per-1,000-bytes
123 CFeeRate() : nSatoshisPerK(0) { }
124 explicit CFeeRate(int64_t _nSatoshisPerK): nSatoshisPerK(_nSatoshisPerK) { }
125 CFeeRate(int64_t nFeePaid, size_t nSize);
126 CFeeRate(const CFeeRate& other) { nSatoshisPerK = other.nSatoshisPerK; }
128 int64_t GetFee(size_t size) const; // unit returned is satoshis
129 int64_t GetFeePerK() const { return GetFee(1000); } // satoshis-per-1000-bytes
131 friend bool operator<(const CFeeRate& a, const CFeeRate& b) { return a.nSatoshisPerK < b.nSatoshisPerK; }
132 friend bool operator>(const CFeeRate& a, const CFeeRate& b) { return a.nSatoshisPerK > b.nSatoshisPerK; }
133 friend bool operator==(const CFeeRate& a, const CFeeRate& b) { return a.nSatoshisPerK == b.nSatoshisPerK; }
134 friend bool operator<=(const CFeeRate& a, const CFeeRate& b) { return a.nSatoshisPerK <= b.nSatoshisPerK; }
135 friend bool operator>=(const CFeeRate& a, const CFeeRate& b) { return a.nSatoshisPerK >= b.nSatoshisPerK; }
136 std::string ToString() const;
138 IMPLEMENT_SERIALIZE( READWRITE(nSatoshisPerK); )
142 /** An output of a transaction. It contains the public key that the next input
143 * must be able to sign with to claim it.
149 CScript scriptPubKey;
156 CTxOut(int64_t nValueIn, CScript scriptPubKeyIn);
161 READWRITE(scriptPubKey);
167 scriptPubKey.clear();
172 return (nValue == -1);
175 uint256 GetHash() const;
177 bool IsDust(CFeeRate minRelayTxFee) const
179 // "Dust" is defined in terms of CTransaction::minRelayTxFee,
180 // which has units satoshis-per-kilobyte.
181 // If you'd pay more than 1/3 in fees
182 // to spend something, then we consider it dust.
183 // A typical txout is 34 bytes big, and will
184 // need a CTxIn of at least 148 bytes to spend:
185 // so dust is a txout less than 546 satoshis
186 // with default minRelayTxFee.
187 size_t nSize = GetSerializeSize(SER_DISK,0)+148u;
188 return (nValue < 3*minRelayTxFee.GetFee(nSize));
191 friend bool operator==(const CTxOut& a, const CTxOut& b)
193 return (a.nValue == b.nValue &&
194 a.scriptPubKey == b.scriptPubKey);
197 friend bool operator!=(const CTxOut& a, const CTxOut& b)
202 std::string ToString() const;
207 struct CMutableTransaction;
209 /** The basic transaction that is broadcasted on the network and contained in
210 * blocks. A transaction can contain multiple inputs and outputs.
217 void UpdateHash() const;
220 static const int CURRENT_VERSION=1;
222 // The local variables are made const to prevent unintended modification
223 // without updating the cached hash value. However, CTransaction is not
224 // actually immutable; deserialization and assignment are implemented,
225 // and bypass the constness. This is safe, as they update the entire
226 // structure, including the hash.
228 const std::vector<CTxIn> vin;
229 const std::vector<CTxOut> vout;
230 const unsigned int nLockTime;
232 /** Construct a CTransaction that qualifies as IsNull() */
235 /** Convert a CMutableTransaction into a CTransaction. */
236 CTransaction(const CMutableTransaction &tx);
238 CTransaction& operator=(const CTransaction& tx);
241 READWRITE(*const_cast<int*>(&this->nVersion));
242 nVersion = this->nVersion;
243 READWRITE(*const_cast<std::vector<CTxIn>*>(&vin));
244 READWRITE(*const_cast<std::vector<CTxOut>*>(&vout));
245 READWRITE(*const_cast<unsigned int*>(&nLockTime));
250 bool IsNull() const {
251 return vin.empty() && vout.empty();
254 const uint256& GetHash() const {
258 // True if only scriptSigs are different
259 bool IsEquivalentTo(const CTransaction& tx) const;
261 // Return sum of txouts.
262 int64_t GetValueOut() const;
263 // GetValueIn() is a method on CCoinsViewCache, because
264 // inputs must be known to compute value in.
266 // Compute priority, given priority of inputs and (optionally) tx size
267 double ComputePriority(double dPriorityInputs, unsigned int nTxSize=0) const;
269 bool IsCoinBase() const
271 return (vin.size() == 1 && vin[0].prevout.IsNull());
274 friend bool operator==(const CTransaction& a, const CTransaction& b)
276 return a.hash == b.hash;
279 friend bool operator!=(const CTransaction& a, const CTransaction& b)
281 return a.hash != b.hash;
284 std::string ToString() const;
288 /** A mutable version of CTransaction. */
289 struct CMutableTransaction
292 std::vector<CTxIn> vin;
293 std::vector<CTxOut> vout;
294 unsigned int nLockTime;
296 CMutableTransaction();
297 CMutableTransaction(const CTransaction& tx);
300 READWRITE(this->nVersion);
301 nVersion = this->nVersion;
304 READWRITE(nLockTime);
307 /** Compute the hash of this CMutableTransaction. This is computed on the
308 * fly, as opposed to GetHash() in CTransaction, which uses a cached result.
310 uint256 GetHash() const;
313 /** wrapper for CTxOut that provides a more compact serialization */
314 class CTxOutCompressor
320 static uint64_t CompressAmount(uint64_t nAmount);
321 static uint64_t DecompressAmount(uint64_t nAmount);
323 CTxOutCompressor(CTxOut &txoutIn) : txout(txoutIn) { }
325 IMPLEMENT_SERIALIZE(({
327 uint64_t nVal = CompressAmount(txout.nValue);
328 READWRITE(VARINT(nVal));
331 READWRITE(VARINT(nVal));
332 txout.nValue = DecompressAmount(nVal);
334 CScriptCompressor cscript(REF(txout.scriptPubKey));
339 /** Undo information for a CTxIn
341 * Contains the prevout's CTxOut being spent, and if this was the
342 * last output of the affected transaction, its metadata as well
343 * (coinbase or not, height, transaction version)
348 CTxOut txout; // the txout data before being spent
349 bool fCoinBase; // if the outpoint was the last unspent: whether it belonged to a coinbase
350 unsigned int nHeight; // if the outpoint was the last unspent: its height
351 int nVersion; // if the outpoint was the last unspent: its version
353 CTxInUndo() : txout(), fCoinBase(false), nHeight(0), nVersion(0) {}
354 CTxInUndo(const CTxOut &txoutIn, bool fCoinBaseIn = false, unsigned int nHeightIn = 0, int nVersionIn = 0) : txout(txoutIn), fCoinBase(fCoinBaseIn), nHeight(nHeightIn), nVersion(nVersionIn) { }
356 unsigned int GetSerializeSize(int nType, int nVersion) const {
357 return ::GetSerializeSize(VARINT(nHeight*2+(fCoinBase ? 1 : 0)), nType, nVersion) +
358 (nHeight > 0 ? ::GetSerializeSize(VARINT(this->nVersion), nType, nVersion) : 0) +
359 ::GetSerializeSize(CTxOutCompressor(REF(txout)), nType, nVersion);
362 template<typename Stream>
363 void Serialize(Stream &s, int nType, int nVersion) const {
364 ::Serialize(s, VARINT(nHeight*2+(fCoinBase ? 1 : 0)), nType, nVersion);
366 ::Serialize(s, VARINT(this->nVersion), nType, nVersion);
367 ::Serialize(s, CTxOutCompressor(REF(txout)), nType, nVersion);
370 template<typename Stream>
371 void Unserialize(Stream &s, int nType, int nVersion) {
372 unsigned int nCode = 0;
373 ::Unserialize(s, VARINT(nCode), nType, nVersion);
375 fCoinBase = nCode & 1;
377 ::Unserialize(s, VARINT(this->nVersion), nType, nVersion);
378 ::Unserialize(s, REF(CTxOutCompressor(REF(txout))), nType, nVersion);
382 /** Undo information for a CTransaction */
386 // undo information for all txins
387 std::vector<CTxInUndo> vprevout;
395 /** Nodes collect new transactions into a block, hash them into a hash tree,
396 * and scan through nonce values to make the block's hash satisfy proof-of-work
397 * requirements. When they solve the proof-of-work, they broadcast the block
398 * to everyone and the block is added to the block chain. The first transaction
399 * in the block is a special one that creates a new coin owned by the creator
406 static const int CURRENT_VERSION=2;
408 uint256 hashPrevBlock;
409 uint256 hashMerkleRoot;
421 READWRITE(this->nVersion);
422 nVersion = this->nVersion;
423 READWRITE(hashPrevBlock);
424 READWRITE(hashMerkleRoot);
432 nVersion = CBlockHeader::CURRENT_VERSION;
445 uint256 GetHash() const;
447 int64_t GetBlockTime() const
449 return (int64_t)nTime;
454 class CBlock : public CBlockHeader
458 std::vector<CTransaction> vtx;
461 mutable std::vector<uint256> vMerkleTree;
468 CBlock(const CBlockHeader &header)
471 *((CBlockHeader*)this) = header;
476 READWRITE(*(CBlockHeader*)this);
482 CBlockHeader::SetNull();
487 CBlockHeader GetBlockHeader() const
490 block.nVersion = nVersion;
491 block.hashPrevBlock = hashPrevBlock;
492 block.hashMerkleRoot = hashMerkleRoot;
495 block.nNonce = nNonce;
499 uint256 BuildMerkleTree() const;
501 std::vector<uint256> GetMerkleBranch(int nIndex) const;
502 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex);
507 /** Describes a place in the block chain to another node such that if the
508 * other node doesn't have the same branch, it can find a recent common trunk.
509 * The further back it is, the further before the fork it may be.
513 std::vector<uint256> vHave;
517 CBlockLocator(const std::vector<uint256>& vHaveIn)
524 if (!(nType & SER_GETHASH))
536 return vHave.empty();