1// Copyright (c) 2013-2016 The btcsuite developers
2// Use of this source code is governed by an ISC
3// license that can be found in the LICENSE file.
4
5package wire
6
7import (
8	"bytes"
9	"fmt"
10	"io"
11	"strconv"
12
13	"github.com/btcsuite/btcd/chaincfg/chainhash"
14)
15
16const (
17	// TxVersion is the current latest supported transaction version.
18	TxVersion = 1
19
20	// MaxTxInSequenceNum is the maximum sequence number the sequence field
21	// of a transaction input can be.
22	MaxTxInSequenceNum uint32 = 0xffffffff
23
24	// MaxPrevOutIndex is the maximum index the index field of a previous
25	// outpoint can be.
26	MaxPrevOutIndex uint32 = 0xffffffff
27
28	// SequenceLockTimeDisabled is a flag that if set on a transaction
29	// input's sequence number, the sequence number will not be interpreted
30	// as a relative locktime.
31	SequenceLockTimeDisabled = 1 << 31
32
33	// SequenceLockTimeIsSeconds is a flag that if set on a transaction
34	// input's sequence number, the relative locktime has units of 512
35	// seconds.
36	SequenceLockTimeIsSeconds = 1 << 22
37
38	// SequenceLockTimeMask is a mask that extracts the relative locktime
39	// when masked against the transaction input sequence number.
40	SequenceLockTimeMask = 0x0000ffff
41
42	// SequenceLockTimeGranularity is the defined time based granularity
43	// for seconds-based relative time locks. When converting from seconds
44	// to a sequence number, the value is right shifted by this amount,
45	// therefore the granularity of relative time locks in 512 or 2^9
46	// seconds. Enforced relative lock times are multiples of 512 seconds.
47	SequenceLockTimeGranularity = 9
48
49	// defaultTxInOutAlloc is the default size used for the backing array for
50	// transaction inputs and outputs.  The array will dynamically grow as needed,
51	// but this figure is intended to provide enough space for the number of
52	// inputs and outputs in a typical transaction without needing to grow the
53	// backing array multiple times.
54	defaultTxInOutAlloc = 15
55
56	// minTxInPayload is the minimum payload size for a transaction input.
57	// PreviousOutPoint.Hash + PreviousOutPoint.Index 4 bytes + Varint for
58	// SignatureScript length 1 byte + Sequence 4 bytes.
59	minTxInPayload = 9 + chainhash.HashSize
60
61	// maxTxInPerMessage is the maximum number of transactions inputs that
62	// a transaction which fits into a message could possibly have.
63	maxTxInPerMessage = (MaxMessagePayload / minTxInPayload) + 1
64
65	// MinTxOutPayload is the minimum payload size for a transaction output.
66	// Value 8 bytes + Varint for PkScript length 1 byte.
67	MinTxOutPayload = 9
68
69	// maxTxOutPerMessage is the maximum number of transactions outputs that
70	// a transaction which fits into a message could possibly have.
71	maxTxOutPerMessage = (MaxMessagePayload / MinTxOutPayload) + 1
72
73	// minTxPayload is the minimum payload size for a transaction.  Note
74	// that any realistically usable transaction must have at least one
75	// input or output, but that is a rule enforced at a higher layer, so
76	// it is intentionally not included here.
77	// Version 4 bytes + Varint number of transaction inputs 1 byte + Varint
78	// number of transaction outputs 1 byte + LockTime 4 bytes + min input
79	// payload + min output payload.
80	minTxPayload = 10
81
82	// freeListMaxScriptSize is the size of each buffer in the free list
83	// that	is used for deserializing scripts from the wire before they are
84	// concatenated into a single contiguous buffers.  This value was chosen
85	// because it is slightly more than twice the size of the vast majority
86	// of all "standard" scripts.  Larger scripts are still deserialized
87	// properly as the free list will simply be bypassed for them.
88	freeListMaxScriptSize = 512
89
90	// freeListMaxItems is the number of buffers to keep in the free list
91	// to use for script deserialization.  This value allows up to 100
92	// scripts per transaction being simultaneously deserialized by 125
93	// peers.  Thus, the peak usage of the free list is 12,500 * 512 =
94	// 6,400,000 bytes.
95	freeListMaxItems = 12500
96
97	// maxWitnessItemsPerInput is the maximum number of witness items to
98	// be read for the witness data for a single TxIn. This number is
99	// derived using a possble lower bound for the encoding of a witness
100	// item: 1 byte for length + 1 byte for the witness item itself, or two
101	// bytes. This value is then divided by the currently allowed maximum
102	// "cost" for a transaction.
103	maxWitnessItemsPerInput = 500000
104
105	// maxWitnessItemSize is the maximum allowed size for an item within
106	// an input's witness data. This number is derived from the fact that
107	// for script validation, each pushed item onto the stack must be less
108	// than 10k bytes.
109	maxWitnessItemSize = 11000
110)
111
112// witnessMarkerBytes are a pair of bytes specific to the witness encoding. If
113// this sequence is encoutered, then it indicates a transaction has iwtness
114// data. The first byte is an always 0x00 marker byte, which allows decoders to
115// distinguish a serialized transaction with witnesses from a regular (legacy)
116// one. The second byte is the Flag field, which at the moment is always 0x01,
117// but may be extended in the future to accommodate auxiliary non-committed
118// fields.
119var witessMarkerBytes = []byte{0x00, 0x01}
120
121// scriptFreeList defines a free list of byte slices (up to the maximum number
122// defined by the freeListMaxItems constant) that have a cap according to the
123// freeListMaxScriptSize constant.  It is used to provide temporary buffers for
124// deserializing scripts in order to greatly reduce the number of allocations
125// required.
126//
127// The caller can obtain a buffer from the free list by calling the Borrow
128// function and should return it via the Return function when done using it.
129type scriptFreeList chan []byte
130
131// Borrow returns a byte slice from the free list with a length according the
132// provided size.  A new buffer is allocated if there are any items available.
133//
134// When the size is larger than the max size allowed for items on the free list
135// a new buffer of the appropriate size is allocated and returned.  It is safe
136// to attempt to return said buffer via the Return function as it will be
137// ignored and allowed to go the garbage collector.
138func (c scriptFreeList) Borrow(size uint64) []byte {
139	if size > freeListMaxScriptSize {
140		return make([]byte, size)
141	}
142
143	var buf []byte
144	select {
145	case buf = <-c:
146	default:
147		buf = make([]byte, freeListMaxScriptSize)
148	}
149	return buf[:size]
150}
151
152// Return puts the provided byte slice back on the free list when it has a cap
153// of the expected length.  The buffer is expected to have been obtained via
154// the Borrow function.  Any slices that are not of the appropriate size, such
155// as those whose size is greater than the largest allowed free list item size
156// are simply ignored so they can go to the garbage collector.
157func (c scriptFreeList) Return(buf []byte) {
158	// Ignore any buffers returned that aren't the expected size for the
159	// free list.
160	if cap(buf) != freeListMaxScriptSize {
161		return
162	}
163
164	// Return the buffer to the free list when it's not full.  Otherwise let
165	// it be garbage collected.
166	select {
167	case c <- buf:
168	default:
169		// Let it go to the garbage collector.
170	}
171}
172
173// Create the concurrent safe free list to use for script deserialization.  As
174// previously described, this free list is maintained to significantly reduce
175// the number of allocations.
176var scriptPool scriptFreeList = make(chan []byte, freeListMaxItems)
177
178// OutPoint defines a bitcoin data type that is used to track previous
179// transaction outputs.
180type OutPoint struct {
181	Hash  chainhash.Hash
182	Index uint32
183}
184
185// NewOutPoint returns a new bitcoin transaction outpoint point with the
186// provided hash and index.
187func NewOutPoint(hash *chainhash.Hash, index uint32) *OutPoint {
188	return &OutPoint{
189		Hash:  *hash,
190		Index: index,
191	}
192}
193
194// String returns the OutPoint in the human-readable form "hash:index".
195func (o OutPoint) String() string {
196	// Allocate enough for hash string, colon, and 10 digits.  Although
197	// at the time of writing, the number of digits can be no greater than
198	// the length of the decimal representation of maxTxOutPerMessage, the
199	// maximum message payload may increase in the future and this
200	// optimization may go unnoticed, so allocate space for 10 decimal
201	// digits, which will fit any uint32.
202	buf := make([]byte, 2*chainhash.HashSize+1, 2*chainhash.HashSize+1+10)
203	copy(buf, o.Hash.String())
204	buf[2*chainhash.HashSize] = ':'
205	buf = strconv.AppendUint(buf, uint64(o.Index), 10)
206	return string(buf)
207}
208
209// TxIn defines a bitcoin transaction input.
210type TxIn struct {
211	PreviousOutPoint OutPoint
212	SignatureScript  []byte
213	Witness          TxWitness
214	Sequence         uint32
215}
216
217// SerializeSize returns the number of bytes it would take to serialize the
218// the transaction input.
219func (t *TxIn) SerializeSize() int {
220	// Outpoint Hash 32 bytes + Outpoint Index 4 bytes + Sequence 4 bytes +
221	// serialized varint size for the length of SignatureScript +
222	// SignatureScript bytes.
223	return 40 + VarIntSerializeSize(uint64(len(t.SignatureScript))) +
224		len(t.SignatureScript)
225}
226
227// NewTxIn returns a new bitcoin transaction input with the provided
228// previous outpoint point and signature script with a default sequence of
229// MaxTxInSequenceNum.
230func NewTxIn(prevOut *OutPoint, signatureScript []byte, witness [][]byte) *TxIn {
231	return &TxIn{
232		PreviousOutPoint: *prevOut,
233		SignatureScript:  signatureScript,
234		Witness:          witness,
235		Sequence:         MaxTxInSequenceNum,
236	}
237}
238
239// TxWitness defines the witness for a TxIn. A witness is to be interpreted as
240// a slice of byte slices, or a stack with one or many elements.
241type TxWitness [][]byte
242
243// SerializeSize returns the number of bytes it would take to serialize the the
244// transaction input's witness.
245func (t TxWitness) SerializeSize() int {
246	// A varint to signal the number of elements the witness has.
247	n := VarIntSerializeSize(uint64(len(t)))
248
249	// For each element in the witness, we'll need a varint to signal the
250	// size of the element, then finally the number of bytes the element
251	// itself comprises.
252	for _, witItem := range t {
253		n += VarIntSerializeSize(uint64(len(witItem)))
254		n += len(witItem)
255	}
256
257	return n
258}
259
260// TxOut defines a bitcoin transaction output.
261type TxOut struct {
262	Value    int64
263	PkScript []byte
264}
265
266// SerializeSize returns the number of bytes it would take to serialize the
267// the transaction output.
268func (t *TxOut) SerializeSize() int {
269	// Value 8 bytes + serialized varint size for the length of PkScript +
270	// PkScript bytes.
271	return 8 + VarIntSerializeSize(uint64(len(t.PkScript))) + len(t.PkScript)
272}
273
274// NewTxOut returns a new bitcoin transaction output with the provided
275// transaction value and public key script.
276func NewTxOut(value int64, pkScript []byte) *TxOut {
277	return &TxOut{
278		Value:    value,
279		PkScript: pkScript,
280	}
281}
282
283// MsgTx implements the Message interface and represents a bitcoin tx message.
284// It is used to deliver transaction information in response to a getdata
285// message (MsgGetData) for a given transaction.
286//
287// Use the AddTxIn and AddTxOut functions to build up the list of transaction
288// inputs and outputs.
289type MsgTx struct {
290	Version  int32
291	TxIn     []*TxIn
292	TxOut    []*TxOut
293	LockTime uint32
294}
295
296// AddTxIn adds a transaction input to the message.
297func (msg *MsgTx) AddTxIn(ti *TxIn) {
298	msg.TxIn = append(msg.TxIn, ti)
299}
300
301// AddTxOut adds a transaction output to the message.
302func (msg *MsgTx) AddTxOut(to *TxOut) {
303	msg.TxOut = append(msg.TxOut, to)
304}
305
306// TxHash generates the Hash for the transaction.
307func (msg *MsgTx) TxHash() chainhash.Hash {
308	// Encode the transaction and calculate double sha256 on the result.
309	// Ignore the error returns since the only way the encode could fail
310	// is being out of memory or due to nil pointers, both of which would
311	// cause a run-time panic.
312	buf := bytes.NewBuffer(make([]byte, 0, msg.SerializeSizeStripped()))
313	_ = msg.SerializeNoWitness(buf)
314	return chainhash.DoubleHashH(buf.Bytes())
315}
316
317// WitnessHash generates the hash of the transaction serialized according to
318// the new witness serialization defined in BIP0141 and BIP0144. The final
319// output is used within the Segregated Witness commitment of all the witnesses
320// within a block. If a transaction has no witness data, then the witness hash,
321// is the same as its txid.
322func (msg *MsgTx) WitnessHash() chainhash.Hash {
323	if msg.HasWitness() {
324		buf := bytes.NewBuffer(make([]byte, 0, msg.SerializeSize()))
325		_ = msg.Serialize(buf)
326		return chainhash.DoubleHashH(buf.Bytes())
327	}
328
329	return msg.TxHash()
330}
331
332// Copy creates a deep copy of a transaction so that the original does not get
333// modified when the copy is manipulated.
334func (msg *MsgTx) Copy() *MsgTx {
335	// Create new tx and start by copying primitive values and making space
336	// for the transaction inputs and outputs.
337	newTx := MsgTx{
338		Version:  msg.Version,
339		TxIn:     make([]*TxIn, 0, len(msg.TxIn)),
340		TxOut:    make([]*TxOut, 0, len(msg.TxOut)),
341		LockTime: msg.LockTime,
342	}
343
344	// Deep copy the old TxIn data.
345	for _, oldTxIn := range msg.TxIn {
346		// Deep copy the old previous outpoint.
347		oldOutPoint := oldTxIn.PreviousOutPoint
348		newOutPoint := OutPoint{}
349		newOutPoint.Hash.SetBytes(oldOutPoint.Hash[:])
350		newOutPoint.Index = oldOutPoint.Index
351
352		// Deep copy the old signature script.
353		var newScript []byte
354		oldScript := oldTxIn.SignatureScript
355		oldScriptLen := len(oldScript)
356		if oldScriptLen > 0 {
357			newScript = make([]byte, oldScriptLen)
358			copy(newScript, oldScript[:oldScriptLen])
359		}
360
361		// Create new txIn with the deep copied data.
362		newTxIn := TxIn{
363			PreviousOutPoint: newOutPoint,
364			SignatureScript:  newScript,
365			Sequence:         oldTxIn.Sequence,
366		}
367
368		// If the transaction is witnessy, then also copy the
369		// witnesses.
370		if len(oldTxIn.Witness) != 0 {
371			// Deep copy the old witness data.
372			newTxIn.Witness = make([][]byte, len(oldTxIn.Witness))
373			for i, oldItem := range oldTxIn.Witness {
374				newItem := make([]byte, len(oldItem))
375				copy(newItem, oldItem)
376				newTxIn.Witness[i] = newItem
377			}
378		}
379
380		// Finally, append this fully copied txin.
381		newTx.TxIn = append(newTx.TxIn, &newTxIn)
382	}
383
384	// Deep copy the old TxOut data.
385	for _, oldTxOut := range msg.TxOut {
386		// Deep copy the old PkScript
387		var newScript []byte
388		oldScript := oldTxOut.PkScript
389		oldScriptLen := len(oldScript)
390		if oldScriptLen > 0 {
391			newScript = make([]byte, oldScriptLen)
392			copy(newScript, oldScript[:oldScriptLen])
393		}
394
395		// Create new txOut with the deep copied data and append it to
396		// new Tx.
397		newTxOut := TxOut{
398			Value:    oldTxOut.Value,
399			PkScript: newScript,
400		}
401		newTx.TxOut = append(newTx.TxOut, &newTxOut)
402	}
403
404	return &newTx
405}
406
407// BtcDecode decodes r using the bitcoin protocol encoding into the receiver.
408// This is part of the Message interface implementation.
409// See Deserialize for decoding transactions stored to disk, such as in a
410// database, as opposed to decoding transactions from the wire.
411func (msg *MsgTx) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) error {
412	version, err := binarySerializer.Uint32(r, littleEndian)
413	if err != nil {
414		return err
415	}
416	msg.Version = int32(version)
417
418	count, err := ReadVarInt(r, pver)
419	if err != nil {
420		return err
421	}
422
423	// A count of zero (meaning no TxIn's to the uninitiated) indicates
424	// this is a transaction with witness data.
425	var flag [1]byte
426	if count == 0 && enc == WitnessEncoding {
427		// Next, we need to read the flag, which is a single byte.
428		if _, err = io.ReadFull(r, flag[:]); err != nil {
429			return err
430		}
431
432		// At the moment, the flag MUST be 0x01. In the future other
433		// flag types may be supported.
434		if flag[0] != 0x01 {
435			str := fmt.Sprintf("witness tx but flag byte is %x", flag)
436			return messageError("MsgTx.BtcDecode", str)
437		}
438
439		// With the Segregated Witness specific fields decoded, we can
440		// now read in the actual txin count.
441		count, err = ReadVarInt(r, pver)
442		if err != nil {
443			return err
444		}
445	}
446
447	// Prevent more input transactions than could possibly fit into a
448	// message.  It would be possible to cause memory exhaustion and panics
449	// without a sane upper bound on this count.
450	if count > uint64(maxTxInPerMessage) {
451		str := fmt.Sprintf("too many input transactions to fit into "+
452			"max message size [count %d, max %d]", count,
453			maxTxInPerMessage)
454		return messageError("MsgTx.BtcDecode", str)
455	}
456
457	// returnScriptBuffers is a closure that returns any script buffers that
458	// were borrowed from the pool when there are any deserialization
459	// errors.  This is only valid to call before the final step which
460	// replaces the scripts with the location in a contiguous buffer and
461	// returns them.
462	returnScriptBuffers := func() {
463		for _, txIn := range msg.TxIn {
464			if txIn == nil {
465				continue
466			}
467
468			if txIn.SignatureScript != nil {
469				scriptPool.Return(txIn.SignatureScript)
470			}
471
472			for _, witnessElem := range txIn.Witness {
473				if witnessElem != nil {
474					scriptPool.Return(witnessElem)
475				}
476			}
477		}
478		for _, txOut := range msg.TxOut {
479			if txOut == nil || txOut.PkScript == nil {
480				continue
481			}
482			scriptPool.Return(txOut.PkScript)
483		}
484	}
485
486	// Deserialize the inputs.
487	var totalScriptSize uint64
488	txIns := make([]TxIn, count)
489	msg.TxIn = make([]*TxIn, count)
490	for i := uint64(0); i < count; i++ {
491		// The pointer is set now in case a script buffer is borrowed
492		// and needs to be returned to the pool on error.
493		ti := &txIns[i]
494		msg.TxIn[i] = ti
495		err = readTxIn(r, pver, msg.Version, ti)
496		if err != nil {
497			returnScriptBuffers()
498			return err
499		}
500		totalScriptSize += uint64(len(ti.SignatureScript))
501	}
502
503	count, err = ReadVarInt(r, pver)
504	if err != nil {
505		returnScriptBuffers()
506		return err
507	}
508
509	// Prevent more output transactions than could possibly fit into a
510	// message.  It would be possible to cause memory exhaustion and panics
511	// without a sane upper bound on this count.
512	if count > uint64(maxTxOutPerMessage) {
513		returnScriptBuffers()
514		str := fmt.Sprintf("too many output transactions to fit into "+
515			"max message size [count %d, max %d]", count,
516			maxTxOutPerMessage)
517		return messageError("MsgTx.BtcDecode", str)
518	}
519
520	// Deserialize the outputs.
521	txOuts := make([]TxOut, count)
522	msg.TxOut = make([]*TxOut, count)
523	for i := uint64(0); i < count; i++ {
524		// The pointer is set now in case a script buffer is borrowed
525		// and needs to be returned to the pool on error.
526		to := &txOuts[i]
527		msg.TxOut[i] = to
528		err = readTxOut(r, pver, msg.Version, to)
529		if err != nil {
530			returnScriptBuffers()
531			return err
532		}
533		totalScriptSize += uint64(len(to.PkScript))
534	}
535
536	// If the transaction's flag byte isn't 0x00 at this point, then one or
537	// more of its inputs has accompanying witness data.
538	if flag[0] != 0 && enc == WitnessEncoding {
539		for _, txin := range msg.TxIn {
540			// For each input, the witness is encoded as a stack
541			// with one or more items. Therefore, we first read a
542			// varint which encodes the number of stack items.
543			witCount, err := ReadVarInt(r, pver)
544			if err != nil {
545				returnScriptBuffers()
546				return err
547			}
548
549			// Prevent a possible memory exhaustion attack by
550			// limiting the witCount value to a sane upper bound.
551			if witCount > maxWitnessItemsPerInput {
552				returnScriptBuffers()
553				str := fmt.Sprintf("too many witness items to fit "+
554					"into max message size [count %d, max %d]",
555					witCount, maxWitnessItemsPerInput)
556				return messageError("MsgTx.BtcDecode", str)
557			}
558
559			// Then for witCount number of stack items, each item
560			// has a varint length prefix, followed by the witness
561			// item itself.
562			txin.Witness = make([][]byte, witCount)
563			for j := uint64(0); j < witCount; j++ {
564				txin.Witness[j], err = readScript(r, pver,
565					maxWitnessItemSize, "script witness item")
566				if err != nil {
567					returnScriptBuffers()
568					return err
569				}
570				totalScriptSize += uint64(len(txin.Witness[j]))
571			}
572		}
573	}
574
575	msg.LockTime, err = binarySerializer.Uint32(r, littleEndian)
576	if err != nil {
577		returnScriptBuffers()
578		return err
579	}
580
581	// Create a single allocation to house all of the scripts and set each
582	// input signature script and output public key script to the
583	// appropriate subslice of the overall contiguous buffer.  Then, return
584	// each individual script buffer back to the pool so they can be reused
585	// for future deserializations.  This is done because it significantly
586	// reduces the number of allocations the garbage collector needs to
587	// track, which in turn improves performance and drastically reduces the
588	// amount of runtime overhead that would otherwise be needed to keep
589	// track of millions of small allocations.
590	//
591	// NOTE: It is no longer valid to call the returnScriptBuffers closure
592	// after these blocks of code run because it is already done and the
593	// scripts in the transaction inputs and outputs no longer point to the
594	// buffers.
595	var offset uint64
596	scripts := make([]byte, totalScriptSize)
597	for i := 0; i < len(msg.TxIn); i++ {
598		// Copy the signature script into the contiguous buffer at the
599		// appropriate offset.
600		signatureScript := msg.TxIn[i].SignatureScript
601		copy(scripts[offset:], signatureScript)
602
603		// Reset the signature script of the transaction input to the
604		// slice of the contiguous buffer where the script lives.
605		scriptSize := uint64(len(signatureScript))
606		end := offset + scriptSize
607		msg.TxIn[i].SignatureScript = scripts[offset:end:end]
608		offset += scriptSize
609
610		// Return the temporary script buffer to the pool.
611		scriptPool.Return(signatureScript)
612
613		for j := 0; j < len(msg.TxIn[i].Witness); j++ {
614			// Copy each item within the witness stack for this
615			// input into the contiguous buffer at the appropriate
616			// offset.
617			witnessElem := msg.TxIn[i].Witness[j]
618			copy(scripts[offset:], witnessElem)
619
620			// Reset the witness item within the stack to the slice
621			// of the contiguous buffer where the witness lives.
622			witnessElemSize := uint64(len(witnessElem))
623			end := offset + witnessElemSize
624			msg.TxIn[i].Witness[j] = scripts[offset:end:end]
625			offset += witnessElemSize
626
627			// Return the temporary buffer used for the witness stack
628			// item to the pool.
629			scriptPool.Return(witnessElem)
630		}
631	}
632	for i := 0; i < len(msg.TxOut); i++ {
633		// Copy the public key script into the contiguous buffer at the
634		// appropriate offset.
635		pkScript := msg.TxOut[i].PkScript
636		copy(scripts[offset:], pkScript)
637
638		// Reset the public key script of the transaction output to the
639		// slice of the contiguous buffer where the script lives.
640		scriptSize := uint64(len(pkScript))
641		end := offset + scriptSize
642		msg.TxOut[i].PkScript = scripts[offset:end:end]
643		offset += scriptSize
644
645		// Return the temporary script buffer to the pool.
646		scriptPool.Return(pkScript)
647	}
648
649	return nil
650}
651
652// Deserialize decodes a transaction from r into the receiver using a format
653// that is suitable for long-term storage such as a database while respecting
654// the Version field in the transaction.  This function differs from BtcDecode
655// in that BtcDecode decodes from the bitcoin wire protocol as it was sent
656// across the network.  The wire encoding can technically differ depending on
657// the protocol version and doesn't even really need to match the format of a
658// stored transaction at all.  As of the time this comment was written, the
659// encoded transaction is the same in both instances, but there is a distinct
660// difference and separating the two allows the API to be flexible enough to
661// deal with changes.
662func (msg *MsgTx) Deserialize(r io.Reader) error {
663	// At the current time, there is no difference between the wire encoding
664	// at protocol version 0 and the stable long-term storage format.  As
665	// a result, make use of BtcDecode.
666	return msg.BtcDecode(r, 0, WitnessEncoding)
667}
668
669// DeserializeNoWitness decodes a transaction from r into the receiver, where
670// the transaction encoding format within r MUST NOT utilize the new
671// serialization format created to encode transaction bearing witness data
672// within inputs.
673func (msg *MsgTx) DeserializeNoWitness(r io.Reader) error {
674	return msg.BtcDecode(r, 0, BaseEncoding)
675}
676
677// BtcEncode encodes the receiver to w using the bitcoin protocol encoding.
678// This is part of the Message interface implementation.
679// See Serialize for encoding transactions to be stored to disk, such as in a
680// database, as opposed to encoding transactions for the wire.
681func (msg *MsgTx) BtcEncode(w io.Writer, pver uint32, enc MessageEncoding) error {
682	err := binarySerializer.PutUint32(w, littleEndian, uint32(msg.Version))
683	if err != nil {
684		return err
685	}
686
687	// If the encoding version is set to WitnessEncoding, and the Flags
688	// field for the MsgTx aren't 0x00, then this indicates the transaction
689	// is to be encoded using the new witness inclusionary structure
690	// defined in BIP0144.
691	doWitness := enc == WitnessEncoding && msg.HasWitness()
692	if doWitness {
693		// After the txn's Version field, we include two additional
694		// bytes specific to the witness encoding. The first byte is an
695		// always 0x00 marker byte, which allows decoders to
696		// distinguish a serialized transaction with witnesses from a
697		// regular (legacy) one. The second byte is the Flag field,
698		// which at the moment is always 0x01, but may be extended in
699		// the future to accommodate auxiliary non-committed fields.
700		if _, err := w.Write(witessMarkerBytes); err != nil {
701			return err
702		}
703	}
704
705	count := uint64(len(msg.TxIn))
706	err = WriteVarInt(w, pver, count)
707	if err != nil {
708		return err
709	}
710
711	for _, ti := range msg.TxIn {
712		err = writeTxIn(w, pver, msg.Version, ti)
713		if err != nil {
714			return err
715		}
716	}
717
718	count = uint64(len(msg.TxOut))
719	err = WriteVarInt(w, pver, count)
720	if err != nil {
721		return err
722	}
723
724	for _, to := range msg.TxOut {
725		err = WriteTxOut(w, pver, msg.Version, to)
726		if err != nil {
727			return err
728		}
729	}
730
731	// If this transaction is a witness transaction, and the witness
732	// encoded is desired, then encode the witness for each of the inputs
733	// within the transaction.
734	if doWitness {
735		for _, ti := range msg.TxIn {
736			err = writeTxWitness(w, pver, msg.Version, ti.Witness)
737			if err != nil {
738				return err
739			}
740		}
741	}
742
743	return binarySerializer.PutUint32(w, littleEndian, msg.LockTime)
744}
745
746// HasWitness returns false if none of the inputs within the transaction
747// contain witness data, true false otherwise.
748func (msg *MsgTx) HasWitness() bool {
749	for _, txIn := range msg.TxIn {
750		if len(txIn.Witness) != 0 {
751			return true
752		}
753	}
754
755	return false
756}
757
758// Serialize encodes the transaction to w using a format that suitable for
759// long-term storage such as a database while respecting the Version field in
760// the transaction.  This function differs from BtcEncode in that BtcEncode
761// encodes the transaction to the bitcoin wire protocol in order to be sent
762// across the network.  The wire encoding can technically differ depending on
763// the protocol version and doesn't even really need to match the format of a
764// stored transaction at all.  As of the time this comment was written, the
765// encoded transaction is the same in both instances, but there is a distinct
766// difference and separating the two allows the API to be flexible enough to
767// deal with changes.
768func (msg *MsgTx) Serialize(w io.Writer) error {
769	// At the current time, there is no difference between the wire encoding
770	// at protocol version 0 and the stable long-term storage format.  As
771	// a result, make use of BtcEncode.
772	//
773	// Passing a encoding type of WitnessEncoding to BtcEncode for MsgTx
774	// indicates that the transaction's witnesses (if any) should be
775	// serialized according to the new serialization structure defined in
776	// BIP0144.
777	return msg.BtcEncode(w, 0, WitnessEncoding)
778}
779
780// SerializeNoWitness encodes the transaction to w in an identical manner to
781// Serialize, however even if the source transaction has inputs with witness
782// data, the old serialization format will still be used.
783func (msg *MsgTx) SerializeNoWitness(w io.Writer) error {
784	return msg.BtcEncode(w, 0, BaseEncoding)
785}
786
787// baseSize returns the serialized size of the transaction without accounting
788// for any witness data.
789func (msg *MsgTx) baseSize() int {
790	// Version 4 bytes + LockTime 4 bytes + Serialized varint size for the
791	// number of transaction inputs and outputs.
792	n := 8 + VarIntSerializeSize(uint64(len(msg.TxIn))) +
793		VarIntSerializeSize(uint64(len(msg.TxOut)))
794
795	for _, txIn := range msg.TxIn {
796		n += txIn.SerializeSize()
797	}
798
799	for _, txOut := range msg.TxOut {
800		n += txOut.SerializeSize()
801	}
802
803	return n
804}
805
806// SerializeSize returns the number of bytes it would take to serialize the
807// the transaction.
808func (msg *MsgTx) SerializeSize() int {
809	n := msg.baseSize()
810
811	if msg.HasWitness() {
812		// The marker, and flag fields take up two additional bytes.
813		n += 2
814
815		// Additionally, factor in the serialized size of each of the
816		// witnesses for each txin.
817		for _, txin := range msg.TxIn {
818			n += txin.Witness.SerializeSize()
819		}
820	}
821
822	return n
823}
824
825// SerializeSizeStripped returns the number of bytes it would take to serialize
826// the transaction, excluding any included witness data.
827func (msg *MsgTx) SerializeSizeStripped() int {
828	return msg.baseSize()
829}
830
831// Command returns the protocol command string for the message.  This is part
832// of the Message interface implementation.
833func (msg *MsgTx) Command() string {
834	return CmdTx
835}
836
837// MaxPayloadLength returns the maximum length the payload can be for the
838// receiver.  This is part of the Message interface implementation.
839func (msg *MsgTx) MaxPayloadLength(pver uint32) uint32 {
840	return MaxBlockPayload
841}
842
843// PkScriptLocs returns a slice containing the start of each public key script
844// within the raw serialized transaction.  The caller can easily obtain the
845// length of each script by using len on the script available via the
846// appropriate transaction output entry.
847func (msg *MsgTx) PkScriptLocs() []int {
848	numTxOut := len(msg.TxOut)
849	if numTxOut == 0 {
850		return nil
851	}
852
853	// The starting offset in the serialized transaction of the first
854	// transaction output is:
855	//
856	// Version 4 bytes + serialized varint size for the number of
857	// transaction inputs and outputs + serialized size of each transaction
858	// input.
859	n := 4 + VarIntSerializeSize(uint64(len(msg.TxIn))) +
860		VarIntSerializeSize(uint64(numTxOut))
861
862	// If this transaction has a witness input, the an additional two bytes
863	// for the marker, and flag byte need to be taken into account.
864	if len(msg.TxIn) > 0 && msg.TxIn[0].Witness != nil {
865		n += 2
866	}
867
868	for _, txIn := range msg.TxIn {
869		n += txIn.SerializeSize()
870	}
871
872	// Calculate and set the appropriate offset for each public key script.
873	pkScriptLocs := make([]int, numTxOut)
874	for i, txOut := range msg.TxOut {
875		// The offset of the script in the transaction output is:
876		//
877		// Value 8 bytes + serialized varint size for the length of
878		// PkScript.
879		n += 8 + VarIntSerializeSize(uint64(len(txOut.PkScript)))
880		pkScriptLocs[i] = n
881		n += len(txOut.PkScript)
882	}
883
884	return pkScriptLocs
885}
886
887// NewMsgTx returns a new bitcoin tx message that conforms to the Message
888// interface.  The return instance has a default version of TxVersion and there
889// are no transaction inputs or outputs.  Also, the lock time is set to zero
890// to indicate the transaction is valid immediately as opposed to some time in
891// future.
892func NewMsgTx(version int32) *MsgTx {
893	return &MsgTx{
894		Version: version,
895		TxIn:    make([]*TxIn, 0, defaultTxInOutAlloc),
896		TxOut:   make([]*TxOut, 0, defaultTxInOutAlloc),
897	}
898}
899
900// readOutPoint reads the next sequence of bytes from r as an OutPoint.
901func readOutPoint(r io.Reader, pver uint32, version int32, op *OutPoint) error {
902	_, err := io.ReadFull(r, op.Hash[:])
903	if err != nil {
904		return err
905	}
906
907	op.Index, err = binarySerializer.Uint32(r, littleEndian)
908	return err
909}
910
911// writeOutPoint encodes op to the bitcoin protocol encoding for an OutPoint
912// to w.
913func writeOutPoint(w io.Writer, pver uint32, version int32, op *OutPoint) error {
914	_, err := w.Write(op.Hash[:])
915	if err != nil {
916		return err
917	}
918
919	return binarySerializer.PutUint32(w, littleEndian, op.Index)
920}
921
922// readScript reads a variable length byte array that represents a transaction
923// script.  It is encoded as a varInt containing the length of the array
924// followed by the bytes themselves.  An error is returned if the length is
925// greater than the passed maxAllowed parameter which helps protect against
926// memory exhaustion attacks and forced panics through malformed messages.  The
927// fieldName parameter is only used for the error message so it provides more
928// context in the error.
929func readScript(r io.Reader, pver uint32, maxAllowed uint32, fieldName string) ([]byte, error) {
930	count, err := ReadVarInt(r, pver)
931	if err != nil {
932		return nil, err
933	}
934
935	// Prevent byte array larger than the max message size.  It would
936	// be possible to cause memory exhaustion and panics without a sane
937	// upper bound on this count.
938	if count > uint64(maxAllowed) {
939		str := fmt.Sprintf("%s is larger than the max allowed size "+
940			"[count %d, max %d]", fieldName, count, maxAllowed)
941		return nil, messageError("readScript", str)
942	}
943
944	b := scriptPool.Borrow(count)
945	_, err = io.ReadFull(r, b)
946	if err != nil {
947		scriptPool.Return(b)
948		return nil, err
949	}
950	return b, nil
951}
952
953// readTxIn reads the next sequence of bytes from r as a transaction input
954// (TxIn).
955func readTxIn(r io.Reader, pver uint32, version int32, ti *TxIn) error {
956	err := readOutPoint(r, pver, version, &ti.PreviousOutPoint)
957	if err != nil {
958		return err
959	}
960
961	ti.SignatureScript, err = readScript(r, pver, MaxMessagePayload,
962		"transaction input signature script")
963	if err != nil {
964		return err
965	}
966
967	return readElement(r, &ti.Sequence)
968}
969
970// writeTxIn encodes ti to the bitcoin protocol encoding for a transaction
971// input (TxIn) to w.
972func writeTxIn(w io.Writer, pver uint32, version int32, ti *TxIn) error {
973	err := writeOutPoint(w, pver, version, &ti.PreviousOutPoint)
974	if err != nil {
975		return err
976	}
977
978	err = WriteVarBytes(w, pver, ti.SignatureScript)
979	if err != nil {
980		return err
981	}
982
983	return binarySerializer.PutUint32(w, littleEndian, ti.Sequence)
984}
985
986// readTxOut reads the next sequence of bytes from r as a transaction output
987// (TxOut).
988func readTxOut(r io.Reader, pver uint32, version int32, to *TxOut) error {
989	err := readElement(r, &to.Value)
990	if err != nil {
991		return err
992	}
993
994	to.PkScript, err = readScript(r, pver, MaxMessagePayload,
995		"transaction output public key script")
996	return err
997}
998
999// WriteTxOut encodes to into the bitcoin protocol encoding for a transaction
1000// output (TxOut) to w.
1001//
1002// NOTE: This function is exported in order to allow txscript to compute the
1003// new sighashes for witness transactions (BIP0143).
1004func WriteTxOut(w io.Writer, pver uint32, version int32, to *TxOut) error {
1005	err := binarySerializer.PutUint64(w, littleEndian, uint64(to.Value))
1006	if err != nil {
1007		return err
1008	}
1009
1010	return WriteVarBytes(w, pver, to.PkScript)
1011}
1012
1013// writeTxWitness encodes the bitcoin protocol encoding for a transaction
1014// input's witness into to w.
1015func writeTxWitness(w io.Writer, pver uint32, version int32, wit [][]byte) error {
1016	err := WriteVarInt(w, pver, uint64(len(wit)))
1017	if err != nil {
1018		return err
1019	}
1020	for _, item := range wit {
1021		err = WriteVarBytes(w, pver, item)
1022		if err != nil {
1023			return err
1024		}
1025	}
1026	return nil
1027}
1028