10707034a25772896bcecc8c4b698559917d36a2
[NovacoinLibrary.git] / Novacoin / CTransaction.cs
1 \feff/**
2  *  Novacoin classes library
3  *  Copyright (C) 2015 Alex D. (balthazar.ad@gmail.com)
4
5  *  This program is free software: you can redistribute it and/or modify
6  *  it under the terms of the GNU Affero General Public License as
7  *  published by the Free Software Foundation, either version 3 of the
8  *  License, or (at your option) any later version.
9
10  *  This program is distributed in the hope that it will be useful,
11  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  *  GNU Affero General Public License for more details.
14
15  *  You should have received a copy of the GNU Affero General Public License
16  *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
17  */
18
19 using System;
20 using System.Text;
21 using System.Collections.Generic;
22 using System.IO;
23
24 namespace Novacoin
25 {
26     [Serializable]
27     public class TransactionConstructorException : Exception
28     {
29         public TransactionConstructorException()
30         {
31         }
32
33         public TransactionConstructorException(string message)
34                 : base(message)
35         {
36         }
37
38         public TransactionConstructorException(string message, Exception inner)
39                 : base(message, inner)
40         {
41         }
42     }
43
44     /// <summary>
45     /// Represents the transaction.
46     /// </summary>
47     public class CTransaction
48     {
49         /// <summary>
50         /// One coin = 1000000 satoshis.
51         /// </summary>
52         public const ulong nCoin = 1000000;
53         /// <summary>
54         /// Sanity checking threshold.
55         /// </summary>
56         public const ulong nMaxMoney = 2000000000 * nCoin;
57
58         /// <summary>
59         /// Maximum transaction size is 250Kb
60         /// </summary>
61         public const uint nMaxTxSize = 250000;
62
63         /// <summary>
64         /// Version of transaction schema.
65         /// </summary>
66         public uint nVersion;
67
68         /// <summary>
69         /// Transaction timestamp.
70         /// </summary>
71         public uint nTime;
72
73         /// <summary>
74         /// Array of transaction inputs
75         /// </summary>
76         public CTxIn[] vin;
77
78         /// <summary>
79         /// Array of transaction outputs
80         /// </summary>
81         public CTxOut[] vout;
82
83         /// <summary>
84         /// Block height or timestamp when transaction is final
85         /// </summary>
86         public uint nLockTime;
87
88         /// <summary>
89         /// Initialize an empty instance
90         /// </summary>
91         public CTransaction()
92         {
93             // Initialize empty input and output arrays. Please note that such 
94             // configuration is not valid for real transaction, you have to supply 
95             // at least one input and one output.
96             nVersion = 1;
97             nTime = 0;
98             vin = new CTxIn[0];
99             vout = new CTxOut[0];
100             nLockTime = 0;
101         }
102
103         /// <summary>
104         /// Initialize new instance as a copy of another transaction
105         /// </summary>
106         /// <param name="tx">Transaction to copy from</param>
107         public CTransaction(CTransaction tx)
108         {
109             nVersion = tx.nVersion;
110             nTime = tx.nTime;
111
112             vin = new CTxIn[tx.vin.Length];
113
114             for (int i = 0; i < vin.Length; i++)
115             {
116                 vin[i] = new CTxIn(tx.vin[i]);
117             }
118
119             vout = new CTxOut[tx.vout.Length];
120
121             for (int i = 0; i < vout.Length; i++)
122             {
123                 vout[i] = new CTxOut(tx.vout[i]);
124             }
125
126             nLockTime = tx.nLockTime;
127         }
128
129         /// <summary>
130         /// Attempts to execute all transaction scripts and validate the results.
131         /// </summary>
132         /// <returns>Checking result.</returns>
133         public bool VerifyScripts()
134         {
135             if (IsCoinBase)
136             {
137                 return true;
138             }
139
140             CTransaction txPrev = null;
141             for (int i = 0; i < vin.Length; i++)
142             {
143                 var outpoint = vin[i].prevout;
144
145                 if (!CBlockStore.Instance.GetTransaction(outpoint.hash, ref txPrev))
146                     return false;
147
148                 if (!ScriptCode.VerifyScript(vin[i].scriptSig, txPrev.vout[outpoint.n].scriptPubKey, this, i, (int)scriptflag.SCRIPT_VERIFY_P2SH, 0))
149                     return false;
150             }
151
152             return true;
153         }
154
155         /// <summary>
156         /// Calculate amount of signature operations without trying to properly evaluate P2SH scripts.
157         /// </summary>
158         public uint LegacySigOpCount
159         {
160             get
161             {
162                 uint nSigOps = 0;
163                 foreach (var txin in vin)
164                 {
165                     nSigOps += txin.scriptSig.GetSigOpCount(false);
166                 }
167                 foreach (var txout in vout)
168                 {
169                     nSigOps += txout.scriptPubKey.GetSigOpCount(false);
170                 }
171
172                 return nSigOps;
173             }
174         }
175
176         /// <summary>
177         /// Basic sanity checkings
178         /// </summary>
179         /// <returns>Checking result</returns>
180         public bool CheckTransaction()
181         {
182             if (Size > nMaxTxSize || vin.Length == 0 || vout.Length == 0)
183             {
184                 return false;
185             }
186
187             // Check for empty or overflow output values
188             ulong nValueOut = 0;
189             for (int i = 0; i < vout.Length; i++)
190             {
191                 CTxOut txout = vout[i];
192                 if (txout.IsEmpty && !IsCoinBase && !IsCoinStake)
193                 {
194                     // Empty outputs aren't allowed for user transactions.
195                     return false;
196                 }
197
198                 nValueOut += txout.nValue;
199                 if (!MoneyRange(nValueOut))
200                 {
201                     return false;
202                 }
203             }
204
205             // Check for duplicate inputs
206             var InOutPoints = new List<COutPoint>();
207             foreach (var txin in vin)
208             {
209                 if (InOutPoints.IndexOf(txin.prevout) != -1)
210                 {
211                     // Duplicate input.
212                     return false;
213                 }
214                 InOutPoints.Add(txin.prevout);
215             }
216
217             if (IsCoinBase)
218             {
219                 if (vin[0].scriptSig.Size < 2 || vin[0].scriptSig.Size > 100)
220                 {
221                     // Script size is invalid
222                     return false;
223                 }
224             }
225             else
226             {
227                 foreach (var txin in vin)
228                 {
229                     if (txin.prevout.IsNull)
230                     {
231                         // Null input in non-coinbase transaction.
232                         return false;
233                     }
234                 }
235             }
236
237             return true;
238         }
239
240         public bool IsFinal(uint nBlockHeight = 0, uint nBlockTime = 0)
241         {
242             // Time based nLockTime
243             if (nLockTime == 0)
244             {
245                 return true;
246             }
247             if (nBlockHeight == 0)
248             {
249                 nBlockHeight = uint.MaxValue; // TODO: stupid stub here, should be best height instead.
250             }
251             if (nBlockTime == 0)
252             {
253                 nBlockTime = NetUtils.GetAdjustedTime();
254             }
255             if (nLockTime < (nLockTime < NetUtils.nLockTimeThreshold ? nBlockHeight : nBlockTime))
256             {
257                 return true;
258             }
259             foreach (var txin in vin)
260             {
261                 if (!txin.IsFinal)
262                 {
263                     return false;
264                 }
265             }
266             return true;
267         }
268         
269         /// <summary>
270         /// Parse byte sequence and initialize new instance of CTransaction
271         /// </summary>
272         /// <param name="txBytes">Byte sequence</param>
273         public CTransaction(byte[] txBytes)
274         {
275             try
276             {
277                 var stream = new MemoryStream(txBytes);
278                 var reader = new BinaryReader(stream);
279
280                 nVersion = reader.ReadUInt32();
281                 nTime = reader.ReadUInt32();
282
283                 int nInputs = (int)VarInt.ReadVarInt(ref reader);
284                 vin = new CTxIn[nInputs];
285
286                 for (int nCurrentInput = 0; nCurrentInput < nInputs; nCurrentInput++)
287                 {
288                     // Fill inputs array
289                     vin[nCurrentInput] = new CTxIn();
290
291                     vin[nCurrentInput].prevout = new COutPoint(reader.ReadBytes(36));
292
293                     int nScriptSigLen = (int)VarInt.ReadVarInt(ref reader);
294                     vin[nCurrentInput].scriptSig = new CScript(reader.ReadBytes(nScriptSigLen));
295
296                     vin[nCurrentInput].nSequence = reader.ReadUInt32();
297                 }
298
299                 int nOutputs = (int)VarInt.ReadVarInt(ref reader);
300                 vout = new CTxOut[nOutputs];
301
302                 for (int nCurrentOutput = 0; nCurrentOutput < nOutputs; nCurrentOutput++)
303                 {
304                     // Fill outputs array
305                     vout[nCurrentOutput] = new CTxOut();
306                     vout[nCurrentOutput].nValue = reader.ReadUInt64();
307
308                     int nScriptPKLen = (int)VarInt.ReadVarInt(ref reader);
309                     vout[nCurrentOutput].scriptPubKey = new CScript(reader.ReadBytes(nScriptPKLen));
310                 }
311
312                 nLockTime = reader.ReadUInt32();
313             }
314             catch (Exception e)
315             {
316                 throw new TransactionConstructorException("Deserialization failed", e);
317             }
318         }
319
320         /// <summary>
321         /// Serialized size
322         /// </summary>
323         public int Size
324         {
325             get
326             {
327                 int nSize = 12; // nVersion, nTime, nLockLime
328
329                 nSize += VarInt.GetEncodedSize(vin.Length);
330                 nSize += VarInt.GetEncodedSize(vout.Length);
331
332                 foreach (var input in vin)
333                 {
334                     nSize += input.Size;
335                 }
336
337                 foreach (var output in vout)
338                 {
339                     nSize += output.Size;
340                 }
341
342                 return nSize;
343             }
344         }
345
346         /// <summary>
347         /// Read transactions array which is encoded in the block body.
348         /// </summary>
349         /// <param name="wTxBytes">Bytes sequence</param>
350         /// <returns>Transactions array</returns>
351         internal static CTransaction[] ReadTransactionsList(ref BinaryReader reader)
352         {
353             try
354             {
355                 // Read amount of transactions
356                 int nTransactions = (int)VarInt.ReadVarInt(ref reader);
357                 var tx = new CTransaction[nTransactions];
358
359                 for (int nTx = 0; nTx < nTransactions; nTx++)
360                 {
361                     // Fill the transactions array
362                     tx[nTx] = new CTransaction();
363
364                     tx[nTx].nVersion = reader.ReadUInt32();
365                     tx[nTx].nTime = reader.ReadUInt32();
366
367                     // Inputs array
368                     tx[nTx].vin = CTxIn.ReadTxInList(ref reader);
369
370                     // outputs array
371                     tx[nTx].vout = CTxOut.ReadTxOutList(ref reader);
372
373                     tx[nTx].nLockTime = reader.ReadUInt32();
374                 }
375
376                 return tx;
377
378             }
379             catch (Exception e)
380             {
381                 throw new TransactionConstructorException("Deserialization failed", e);
382             }
383         }
384
385         public bool IsCoinBase
386         {
387             get { return (vin.Length == 1 && vin[0].prevout.IsNull && vout.Length >= 1); }
388         }
389
390         public bool IsCoinStake
391         {
392             get
393             {
394                 return (vin.Length > 0 && (!vin[0].prevout.IsNull) && vout.Length >= 2 && vout[0].IsEmpty);
395             }
396         }
397
398         /// <summary>
399         /// Transaction hash
400         /// </summary>
401         public Hash256 Hash
402         {
403             get { return Hash256.Compute256(this); }
404         }
405
406         /// <summary>
407         /// A sequence of bytes, which corresponds to the current state of CTransaction.
408         /// </summary>
409         public static implicit operator byte[] (CTransaction tx)
410         {
411             var stream = new MemoryStream();
412             var writer = new BinaryWriter(stream);
413
414             writer.Write(tx.nVersion);
415             writer.Write(tx.nTime);
416             writer.Write(VarInt.EncodeVarInt(tx.vin.LongLength));
417
418             foreach (var input in tx.vin)
419             {
420                 writer.Write(input);
421             }
422
423             writer.Write(VarInt.EncodeVarInt(tx.vout.LongLength));
424
425             foreach (var output in tx.vout)
426             {
427                 writer.Write(output);
428             }
429
430             writer.Write(tx.nLockTime);
431             var resultBytes = stream.ToArray();
432             writer.Close();
433
434             return resultBytes;
435         }
436
437         public override string ToString()
438         {
439             var sb = new StringBuilder();
440
441             sb.AppendFormat("CTransaction(\n nVersion={0},\n nTime={1},\n", nVersion, nTime);
442
443             foreach (var txin in vin)
444             {
445                 sb.AppendFormat(" {0},\n", txin);
446             }
447
448             foreach (var txout in vout)
449             {
450                 sb.AppendFormat(" {0},\n", txout);
451             }
452
453             sb.AppendFormat("\nnLockTime={0}\n)", nLockTime);
454
455             return sb.ToString();
456         }
457
458         public static bool MoneyRange(ulong nValue) { return (nValue <= nMaxMoney); }
459     }
460 }