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.
13 "github.com/btcsuite/btcd/chaincfg/chainhash"
17 // TxVersion is the current latest supported transaction version.
20 // MaxTxInSequenceNum is the maximum sequence number the sequence field
21 // of a transaction input can be.
22 MaxTxInSequenceNum uint32 = 0xffffffff
24 // MaxPrevOutIndex is the maximum index the index field of a previous
26 MaxPrevOutIndex uint32 = 0xffffffff
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
33 // SequenceLockTimeIsSeconds is a flag that if set on a transaction
34 // input's sequence number, the relative locktime has units of 512
36 SequenceLockTimeIsSeconds = 1 << 22
38 // SequenceLockTimeMask is a mask that extracts the relative locktime
39 // when masked against the transaction input sequence number.
40 SequenceLockTimeMask = 0x0000ffff
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
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
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
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
65 // minTxOutPayload is the minimum payload size for a transaction output.
66 // Value 8 bytes + Varint for PkScript length 1 byte.
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
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.
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
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 =
95 freeListMaxItems = 12500
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
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
109 maxWitnessItemSize = 11000
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
119 var witessMarkerBytes = []byte{0x00, 0x01}
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
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.
129 type scriptFreeList chan []byte
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.
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.
138 func (c scriptFreeList) Borrow(size uint64) []byte {
139 if size > freeListMaxScriptSize {
140 return make([]byte, size)
147 buf = make([]byte, freeListMaxScriptSize)
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.
157 func (c scriptFreeList) Return(buf []byte) {
158 // Ignore any buffers returned that aren't the expected size for the
160 if cap(buf) != freeListMaxScriptSize {
164 // Return the buffer to the free list when it's not full. Otherwise let
165 // it be garbage collected.
169 // Let it go to the garbage collector.
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.
176 var scriptPool scriptFreeList = make(chan []byte, freeListMaxItems)
178 // OutPoint defines a bitcoin data type that is used to track previous
179 // transaction outputs.
180 type OutPoint struct {
185 // NewOutPoint returns a new bitcoin transaction outpoint point with the
186 // provided hash and index.
187 func NewOutPoint(hash *chainhash.Hash, index uint32) *OutPoint {
194 // String returns the OutPoint in the human-readable form "hash:index".
195 func (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)
209 // TxIn defines a bitcoin transaction input.
211 PreviousOutPoint OutPoint
212 SignatureScript []byte
217 // SerializeSize returns the number of bytes it would take to serialize the
218 // the transaction input.
219 func (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)
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.
230 func NewTxIn(prevOut *OutPoint, signatureScript []byte, witness [][]byte) *TxIn {
232 PreviousOutPoint: *prevOut,
233 SignatureScript: signatureScript,
235 Sequence: MaxTxInSequenceNum,
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.
241 type TxWitness [][]byte
243 // SerializeSize returns the number of bytes it would take to serialize the the
244 // transaction input's witness.
245 func (t TxWitness) SerializeSize() int {
246 // A varint to signal the number of elements the witness has.
247 n := VarIntSerializeSize(uint64(len(t)))
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
252 for _, witItem := range t {
253 n += VarIntSerializeSize(uint64(len(witItem)))
260 // TxOut defines a bitcoin transaction output.
266 // SerializeSize returns the number of bytes it would take to serialize the
267 // the transaction output.
268 func (t *TxOut) SerializeSize() int {
269 // Value 8 bytes + serialized varint size for the length of PkScript +
271 return 8 + VarIntSerializeSize(uint64(len(t.PkScript))) + len(t.PkScript)
274 // NewTxOut returns a new bitcoin transaction output with the provided
275 // transaction value and public key script.
276 func NewTxOut(value int64, pkScript []byte) *TxOut {
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.
287 // Use the AddTxIn and AddTxOut functions to build up the list of transaction
288 // inputs and outputs.
296 // AddTxIn adds a transaction input to the message.
297 func (msg *MsgTx) AddTxIn(ti *TxIn) {
298 msg.TxIn = append(msg.TxIn, ti)
301 // AddTxOut adds a transaction output to the message.
302 func (msg *MsgTx) AddTxOut(to *TxOut) {
303 msg.TxOut = append(msg.TxOut, to)
306 // TxHash generates the Hash for the transaction.
307 func (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())
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.
322 func (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())
332 // Copy creates a deep copy of a transaction so that the original does not get
333 // modified when the copy is manipulated.
334 func (msg *MsgTx) Copy() *MsgTx {
335 // Create new tx and start by copying primitive values and making space
336 // for the transaction inputs and outputs.
338 Version: msg.Version,
339 TxIn: make([]*TxIn, 0, len(msg.TxIn)),
340 TxOut: make([]*TxOut, 0, len(msg.TxOut)),
341 LockTime: msg.LockTime,
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
352 // Deep copy the old signature script.
354 oldScript := oldTxIn.SignatureScript
355 oldScriptLen := len(oldScript)
356 if oldScriptLen > 0 {
357 newScript = make([]byte, oldScriptLen)
358 copy(newScript, oldScript[:oldScriptLen])
361 // Create new txIn with the deep copied data.
363 PreviousOutPoint: newOutPoint,
364 SignatureScript: newScript,
365 Sequence: oldTxIn.Sequence,
368 // If the transaction is witnessy, then also copy the
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
380 // Finally, append this fully copied txin.
381 newTx.TxIn = append(newTx.TxIn, &newTxIn)
384 // Deep copy the old TxOut data.
385 for _, oldTxOut := range msg.TxOut {
386 // Deep copy the old PkScript
388 oldScript := oldTxOut.PkScript
389 oldScriptLen := len(oldScript)
390 if oldScriptLen > 0 {
391 newScript = make([]byte, oldScriptLen)
392 copy(newScript, oldScript[:oldScriptLen])
395 // Create new txOut with the deep copied data and append it to
398 Value: oldTxOut.Value,
401 newTx.TxOut = append(newTx.TxOut, &newTxOut)
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.
411 func (msg *MsgTx) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) error {
412 version, err := binarySerializer.Uint32(r, littleEndian)
416 msg.Version = int32(version)
418 count, err := ReadVarInt(r, pver)
423 // A count of zero (meaning no TxIn's to the uninitiated) indicates
424 // this is a transaction with witness data.
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 {
432 // At the moment, the flag MUST be 0x01. In the future other
433 // flag types may be supported.
435 str := fmt.Sprintf("witness tx but flag byte is %x", flag)
436 return messageError("MsgTx.BtcDecode", str)
439 // With the Segregated Witness specific fields decoded, we can
440 // now read in the actual txin count.
441 count, err = ReadVarInt(r, pver)
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,
454 return messageError("MsgTx.BtcDecode", str)
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
462 returnScriptBuffers := func() {
463 for _, txIn := range msg.TxIn {
468 if txIn.SignatureScript != nil {
469 scriptPool.Return(txIn.SignatureScript)
472 for _, witnessElem := range txIn.Witness {
473 if witnessElem != nil {
474 scriptPool.Return(witnessElem)
478 for _, txOut := range msg.TxOut {
479 if txOut == nil || txOut.PkScript == nil {
482 scriptPool.Return(txOut.PkScript)
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.
495 err = readTxIn(r, pver, msg.Version, ti)
497 returnScriptBuffers()
500 totalScriptSize += uint64(len(ti.SignatureScript))
503 count, err = ReadVarInt(r, pver)
505 returnScriptBuffers()
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,
517 return messageError("MsgTx.BtcDecode", str)
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.
528 err = readTxOut(r, pver, msg.Version, to)
530 returnScriptBuffers()
533 totalScriptSize += uint64(len(to.PkScript))
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)
545 returnScriptBuffers()
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)
559 // Then for witCount number of stack items, each item
560 // has a varint length prefix, followed by the witness
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")
567 returnScriptBuffers()
570 totalScriptSize += uint64(len(txin.Witness[j]))
575 msg.LockTime, err = binarySerializer.Uint32(r, littleEndian)
577 returnScriptBuffers()
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.
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
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)
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]
610 // Return the temporary script buffer to the pool.
611 scriptPool.Return(signatureScript)
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
617 witnessElem := msg.TxIn[i].Witness[j]
618 copy(scripts[offset:], witnessElem)
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
627 // Return the temporary buffer used for the witness stack
629 scriptPool.Return(witnessElem)
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)
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]
645 // Return the temporary script buffer to the pool.
646 scriptPool.Return(pkScript)
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.
662 func (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)
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
673 func (msg *MsgTx) DeserializeNoWitness(r io.Reader) error {
674 return msg.BtcDecode(r, 0, BaseEncoding)
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.
681 func (msg *MsgTx) BtcEncode(w io.Writer, pver uint32, enc MessageEncoding) error {
682 err := binarySerializer.PutUint32(w, littleEndian, uint32(msg.Version))
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()
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 {
705 count := uint64(len(msg.TxIn))
706 err = WriteVarInt(w, pver, count)
711 for _, ti := range msg.TxIn {
712 err = writeTxIn(w, pver, msg.Version, ti)
718 count = uint64(len(msg.TxOut))
719 err = WriteVarInt(w, pver, count)
724 for _, to := range msg.TxOut {
725 err = WriteTxOut(w, pver, msg.Version, to)
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.
735 for _, ti := range msg.TxIn {
736 err = writeTxWitness(w, pver, msg.Version, ti.Witness)
743 return binarySerializer.PutUint32(w, littleEndian, msg.LockTime)
746 // HasWitness returns false if none of the inputs within the transaction
747 // contain witness data, true false otherwise.
748 func (msg *MsgTx) HasWitness() bool {
749 for _, txIn := range msg.TxIn {
750 if len(txIn.Witness) != 0 {
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.
768 func (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.
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
777 return msg.BtcEncode(w, 0, WitnessEncoding)
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.
783 func (msg *MsgTx) SerializeNoWitness(w io.Writer) error {
784 return msg.BtcEncode(w, 0, BaseEncoding)
787 // baseSize returns the serialized size of the transaction without accounting
788 // for any witness data.
789 func (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)))
795 for _, txIn := range msg.TxIn {
796 n += txIn.SerializeSize()
799 for _, txOut := range msg.TxOut {
800 n += txOut.SerializeSize()
806 // SerializeSize returns the number of bytes it would take to serialize the
808 func (msg *MsgTx) SerializeSize() int {
811 if msg.HasWitness() {
812 // The marker, and flag fields take up two additional bytes.
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()
825 // SerializeSizeStripped returns the number of bytes it would take to serialize
826 // the transaction, excluding any included witness data.
827 func (msg *MsgTx) SerializeSizeStripped() int {
828 return msg.baseSize()
831 // Command returns the protocol command string for the message. This is part
832 // of the Message interface implementation.
833 func (msg *MsgTx) Command() string {
837 // MaxPayloadLength returns the maximum length the payload can be for the
838 // receiver. This is part of the Message interface implementation.
839 func (msg *MsgTx) MaxPayloadLength(pver uint32) uint32 {
840 return MaxBlockPayload
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.
847 func (msg *MsgTx) PkScriptLocs() []int {
848 numTxOut := len(msg.TxOut)
853 // The starting offset in the serialized transaction of the first
854 // transaction output is:
856 // Version 4 bytes + serialized varint size for the number of
857 // transaction inputs and outputs + serialized size of each transaction
859 n := 4 + VarIntSerializeSize(uint64(len(msg.TxIn))) +
860 VarIntSerializeSize(uint64(numTxOut))
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 {
868 for _, txIn := range msg.TxIn {
869 n += txIn.SerializeSize()
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:
877 // Value 8 bytes + serialized varint size for the length of
879 n += 8 + VarIntSerializeSize(uint64(len(txOut.PkScript)))
881 n += len(txOut.PkScript)
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
892 func NewMsgTx(version int32) *MsgTx {
895 TxIn: make([]*TxIn, 0, defaultTxInOutAlloc),
896 TxOut: make([]*TxOut, 0, defaultTxInOutAlloc),
900 // readOutPoint reads the next sequence of bytes from r as an OutPoint.
901 func readOutPoint(r io.Reader, pver uint32, version int32, op *OutPoint) error {
902 _, err := io.ReadFull(r, op.Hash[:])
907 op.Index, err = binarySerializer.Uint32(r, littleEndian)
911 // writeOutPoint encodes op to the bitcoin protocol encoding for an OutPoint
913 func writeOutPoint(w io.Writer, pver uint32, version int32, op *OutPoint) error {
914 _, err := w.Write(op.Hash[:])
919 return binarySerializer.PutUint32(w, littleEndian, op.Index)
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 exhuastion attacks and forced panics thorugh malformed messages. The
927 // fieldName parameter is only used for the error message so it provides more
928 // context in the error.
929 func readScript(r io.Reader, pver uint32, maxAllowed uint32, fieldName string) ([]byte, error) {
930 count, err := ReadVarInt(r, pver)
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)
944 b := scriptPool.Borrow(count)
945 _, err = io.ReadFull(r, b)
953 // readTxIn reads the next sequence of bytes from r as a transaction input
955 func readTxIn(r io.Reader, pver uint32, version int32, ti *TxIn) error {
956 err := readOutPoint(r, pver, version, &ti.PreviousOutPoint)
961 ti.SignatureScript, err = readScript(r, pver, MaxMessagePayload,
962 "transaction input signature script")
967 return readElement(r, &ti.Sequence)
970 // writeTxIn encodes ti to the bitcoin protocol encoding for a transaction
971 // input (TxIn) to w.
972 func writeTxIn(w io.Writer, pver uint32, version int32, ti *TxIn) error {
973 err := writeOutPoint(w, pver, version, &ti.PreviousOutPoint)
978 err = WriteVarBytes(w, pver, ti.SignatureScript)
983 return binarySerializer.PutUint32(w, littleEndian, ti.Sequence)
986 // readTxOut reads the next sequence of bytes from r as a transaction output
988 func readTxOut(r io.Reader, pver uint32, version int32, to *TxOut) error {
989 err := readElement(r, &to.Value)
994 to.PkScript, err = readScript(r, pver, MaxMessagePayload,
995 "transaction output public key script")
999 // WriteTxOut encodes to into the bitcoin protocol encoding for a transaction
1000 // output (TxOut) to w.
1002 // NOTE: This function is exported in order to allow txscript to compute the
1003 // new sighashes for witness transactions (BIP0143).
1004 func WriteTxOut(w io.Writer, pver uint32, version int32, to *TxOut) error {
1005 err := binarySerializer.PutUint64(w, littleEndian, uint64(to.Value))
1010 return WriteVarBytes(w, pver, to.PkScript)
1013 // writeTxWitness encodes the bitcoin protocol encoding for a transaction
1014 // input's witness into to w.
1015 func writeTxWitness(w io.Writer, pver uint32, version int32, wit [][]byte) error {
1016 err := WriteVarInt(w, pver, uint64(len(wit)))
1020 for _, item := range wit {
1021 err = WriteVarBytes(w, pver, item)