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 static const int64_t COIN = 100000000;
18 static const int64_t CENT = 1000000;
20 /** No amount larger than this (in satoshi) is valid */
21 static const int64_t MAX_MONEY = 21000000 * COIN;
22 inline bool MoneyRange(int64_t nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
24 /** An outpoint - a combination of a transaction hash and an index n into its vout */
31 COutPoint() { SetNull(); }
32 COutPoint(uint256 hashIn, uint32_t nIn) { hash = hashIn; n = nIn; }
36 template <typename Stream, typename Operation>
37 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
38 READWRITE(FLATDATA(*this));
41 void SetNull() { hash = 0; n = (uint32_t) -1; }
42 bool IsNull() const { return (hash == 0 && n == (uint32_t) -1); }
44 friend bool operator<(const COutPoint& a, const COutPoint& b)
46 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
49 friend bool operator==(const COutPoint& a, const COutPoint& b)
51 return (a.hash == b.hash && a.n == b.n);
54 friend bool operator!=(const COutPoint& a, const COutPoint& b)
59 std::string ToString() const;
62 /** An inpoint - a combination of a transaction and an index n into its vin */
66 const CTransaction* ptx;
69 CInPoint() { SetNull(); }
70 CInPoint(const CTransaction* ptxIn, uint32_t nIn) { ptx = ptxIn; n = nIn; }
71 void SetNull() { ptx = NULL; n = (uint32_t) -1; }
72 bool IsNull() const { return (ptx == NULL && n == (uint32_t) -1); }
75 /** An input of a transaction. It contains the location of the previous
76 * transaction's output that it claims and a signature that matches the
77 * output's public key.
88 nSequence = std::numeric_limits<unsigned int>::max();
91 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), uint32_t nSequenceIn=std::numeric_limits<unsigned int>::max());
92 CTxIn(uint256 hashPrevTx, uint32_t nOut, CScript scriptSigIn=CScript(), uint32_t nSequenceIn=std::numeric_limits<uint32_t>::max());
96 template <typename Stream, typename Operation>
97 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
100 READWRITE(nSequence);
105 return (nSequence == std::numeric_limits<uint32_t>::max());
108 friend bool operator==(const CTxIn& a, const CTxIn& b)
110 return (a.prevout == b.prevout &&
111 a.scriptSig == b.scriptSig &&
112 a.nSequence == b.nSequence);
115 friend bool operator!=(const CTxIn& a, const CTxIn& b)
120 std::string ToString() const;
125 /** Type-safe wrapper class to for fee rates
126 * (how much to pay based on transaction size)
131 int64_t nSatoshisPerK; // unit is satoshis-per-1,000-bytes
133 CFeeRate() : nSatoshisPerK(0) { }
134 explicit CFeeRate(int64_t _nSatoshisPerK): nSatoshisPerK(_nSatoshisPerK) { }
135 CFeeRate(int64_t nFeePaid, size_t nSize);
136 CFeeRate(const CFeeRate& other) { nSatoshisPerK = other.nSatoshisPerK; }
138 int64_t GetFee(size_t size) const; // unit returned is satoshis
139 int64_t GetFeePerK() const { return GetFee(1000); } // satoshis-per-1000-bytes
141 friend bool operator<(const CFeeRate& a, const CFeeRate& b) { return a.nSatoshisPerK < b.nSatoshisPerK; }
142 friend bool operator>(const CFeeRate& a, const CFeeRate& b) { return a.nSatoshisPerK > b.nSatoshisPerK; }
143 friend bool operator==(const CFeeRate& a, const CFeeRate& b) { return a.nSatoshisPerK == b.nSatoshisPerK; }
144 friend bool operator<=(const CFeeRate& a, const CFeeRate& b) { return a.nSatoshisPerK <= b.nSatoshisPerK; }
145 friend bool operator>=(const CFeeRate& a, const CFeeRate& b) { return a.nSatoshisPerK >= b.nSatoshisPerK; }
146 std::string ToString() const;
150 template <typename Stream, typename Operation>
151 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
152 READWRITE(nSatoshisPerK);
157 /** An output of a transaction. It contains the public key that the next input
158 * must be able to sign with to claim it.
164 CScript scriptPubKey;
171 CTxOut(int64_t nValueIn, CScript scriptPubKeyIn);
175 template <typename Stream, typename Operation>
176 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
178 READWRITE(scriptPubKey);
184 scriptPubKey.clear();
189 return (nValue == -1);
192 uint256 GetHash() const;
194 bool IsDust(CFeeRate minRelayTxFee) const
196 // "Dust" is defined in terms of CTransaction::minRelayTxFee,
197 // which has units satoshis-per-kilobyte.
198 // If you'd pay more than 1/3 in fees
199 // to spend something, then we consider it dust.
200 // A typical txout is 34 bytes big, and will
201 // need a CTxIn of at least 148 bytes to spend:
202 // so dust is a txout less than 546 satoshis
203 // with default minRelayTxFee.
204 size_t nSize = GetSerializeSize(SER_DISK,0)+148u;
205 return (nValue < 3*minRelayTxFee.GetFee(nSize));
208 friend bool operator==(const CTxOut& a, const CTxOut& b)
210 return (a.nValue == b.nValue &&
211 a.scriptPubKey == b.scriptPubKey);
214 friend bool operator!=(const CTxOut& a, const CTxOut& b)
219 std::string ToString() const;
223 struct CMutableTransaction;
225 /** The basic transaction that is broadcasted on the network and contained in
226 * blocks. A transaction can contain multiple inputs and outputs.
233 void UpdateHash() const;
236 static const int32_t CURRENT_VERSION=1;
238 // The local variables are made const to prevent unintended modification
239 // without updating the cached hash value. However, CTransaction is not
240 // actually immutable; deserialization and assignment are implemented,
241 // and bypass the constness. This is safe, as they update the entire
242 // structure, including the hash.
243 const int32_t nVersion;
244 const std::vector<CTxIn> vin;
245 const std::vector<CTxOut> vout;
246 const uint32_t nLockTime;
248 /** Construct a CTransaction that qualifies as IsNull() */
251 /** Convert a CMutableTransaction into a CTransaction. */
252 CTransaction(const CMutableTransaction &tx);
254 CTransaction& operator=(const CTransaction& tx);
258 template <typename Stream, typename Operation>
259 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
260 bool fRead = ser_action.ForRead();
262 READWRITE(*const_cast<int32_t*>(&this->nVersion));
263 nVersion = this->nVersion;
264 READWRITE(*const_cast<std::vector<CTxIn>*>(&vin));
265 READWRITE(*const_cast<std::vector<CTxOut>*>(&vout));
266 READWRITE(*const_cast<uint32_t*>(&nLockTime));
271 bool IsNull() const {
272 return vin.empty() && vout.empty();
275 const uint256& GetHash() const {
279 // Return sum of txouts.
280 int64_t GetValueOut() const;
281 // GetValueIn() is a method on CCoinsViewCache, because
282 // inputs must be known to compute value in.
284 // Compute priority, given priority of inputs and (optionally) tx size
285 double ComputePriority(double dPriorityInputs, unsigned int nTxSize=0) const;
287 bool IsCoinBase() const
289 return (vin.size() == 1 && vin[0].prevout.IsNull());
292 friend bool operator==(const CTransaction& a, const CTransaction& b)
294 return a.hash == b.hash;
297 friend bool operator!=(const CTransaction& a, const CTransaction& b)
299 return a.hash != b.hash;
302 std::string ToString() const;
305 /** A mutable version of CTransaction. */
306 struct CMutableTransaction
309 std::vector<CTxIn> vin;
310 std::vector<CTxOut> vout;
313 CMutableTransaction();
314 CMutableTransaction(const CTransaction& tx);
318 template <typename Stream, typename Operation>
319 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
320 READWRITE(this->nVersion);
321 nVersion = this->nVersion;
324 READWRITE(nLockTime);
327 /** Compute the hash of this CMutableTransaction. This is computed on the
328 * fly, as opposed to GetHash() in CTransaction, which uses a cached result.
330 uint256 GetHash() const;
333 /** wrapper for CTxOut that provides a more compact serialization */
334 class CTxOutCompressor
340 static uint64_t CompressAmount(uint64_t nAmount);
341 static uint64_t DecompressAmount(uint64_t nAmount);
343 CTxOutCompressor(CTxOut &txoutIn) : txout(txoutIn) { }
347 template <typename Stream, typename Operation>
348 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
349 bool fRead = ser_action.ForRead();
351 uint64_t nVal = CompressAmount(txout.nValue);
352 READWRITE(VARINT(nVal));
355 READWRITE(VARINT(nVal));
356 txout.nValue = DecompressAmount(nVal);
358 CScriptCompressor cscript(REF(txout.scriptPubKey));
363 /** Undo information for a CTxIn
365 * Contains the prevout's CTxOut being spent, and if this was the
366 * last output of the affected transaction, its metadata as well
367 * (coinbase or not, height, transaction version)
372 CTxOut txout; // the txout data before being spent
373 bool fCoinBase; // if the outpoint was the last unspent: whether it belonged to a coinbase
374 unsigned int nHeight; // if the outpoint was the last unspent: its height
375 int nVersion; // if the outpoint was the last unspent: its version
377 CTxInUndo() : txout(), fCoinBase(false), nHeight(0), nVersion(0) {}
378 CTxInUndo(const CTxOut &txoutIn, bool fCoinBaseIn = false, unsigned int nHeightIn = 0, int nVersionIn = 0) : txout(txoutIn), fCoinBase(fCoinBaseIn), nHeight(nHeightIn), nVersion(nVersionIn) { }
380 unsigned int GetSerializeSize(int nType, int nVersion) const {
381 return ::GetSerializeSize(VARINT(nHeight*2+(fCoinBase ? 1 : 0)), nType, nVersion) +
382 (nHeight > 0 ? ::GetSerializeSize(VARINT(this->nVersion), nType, nVersion) : 0) +
383 ::GetSerializeSize(CTxOutCompressor(REF(txout)), nType, nVersion);
386 template<typename Stream>
387 void Serialize(Stream &s, int nType, int nVersion) const {
388 ::Serialize(s, VARINT(nHeight*2+(fCoinBase ? 1 : 0)), nType, nVersion);
390 ::Serialize(s, VARINT(this->nVersion), nType, nVersion);
391 ::Serialize(s, CTxOutCompressor(REF(txout)), nType, nVersion);
394 template<typename Stream>
395 void Unserialize(Stream &s, int nType, int nVersion) {
396 unsigned int nCode = 0;
397 ::Unserialize(s, VARINT(nCode), nType, nVersion);
399 fCoinBase = nCode & 1;
401 ::Unserialize(s, VARINT(this->nVersion), nType, nVersion);
402 ::Unserialize(s, REF(CTxOutCompressor(REF(txout))), nType, nVersion);
406 /** Undo information for a CTransaction */
410 // undo information for all txins
411 std::vector<CTxInUndo> vprevout;
415 template <typename Stream, typename Operation>
416 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
422 /** Nodes collect new transactions into a block, hash them into a hash tree,
423 * and scan through nonce values to make the block's hash satisfy proof-of-work
424 * requirements. When they solve the proof-of-work, they broadcast the block
425 * to everyone and the block is added to the block chain. The first transaction
426 * in the block is a special one that creates a new coin owned by the creator
433 static const int32_t CURRENT_VERSION=2;
435 uint256 hashPrevBlock;
436 uint256 hashMerkleRoot;
448 template <typename Stream, typename Operation>
449 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
450 READWRITE(this->nVersion);
451 nVersion = this->nVersion;
452 READWRITE(hashPrevBlock);
453 READWRITE(hashMerkleRoot);
461 nVersion = CBlockHeader::CURRENT_VERSION;
474 uint256 GetHash() const;
476 int64_t GetBlockTime() const
478 return (int64_t)nTime;
483 class CBlock : public CBlockHeader
487 std::vector<CTransaction> vtx;
490 mutable std::vector<uint256> vMerkleTree;
497 CBlock(const CBlockHeader &header)
500 *((CBlockHeader*)this) = header;
505 template <typename Stream, typename Operation>
506 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
507 READWRITE(*(CBlockHeader*)this);
513 CBlockHeader::SetNull();
518 CBlockHeader GetBlockHeader() const
521 block.nVersion = nVersion;
522 block.hashPrevBlock = hashPrevBlock;
523 block.hashMerkleRoot = hashMerkleRoot;
526 block.nNonce = nNonce;
530 uint256 BuildMerkleTree() const;
532 std::vector<uint256> GetMerkleBranch(int nIndex) const;
533 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex);
534 std::string ToString() const;
538 /** Describes a place in the block chain to another node such that if the
539 * other node doesn't have the same branch, it can find a recent common trunk.
540 * The further back it is, the further before the fork it may be.
544 std::vector<uint256> vHave;
548 CBlockLocator(const std::vector<uint256>& vHaveIn)
555 template <typename Stream, typename Operation>
556 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
557 if (!(nType & SER_GETHASH))
569 return vHave.empty();
573 #endif // BITCOIN_CORE_H