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 5 package wire
6 7 import (
8 "encoding/hex"
9 "errors"
10 "fmt"
11 "io"
12 "strconv"
13 "strings"
14 15 "github.com/btcsuite/btcd/chainhash/v2"
16 )
17 18 const (
19 // TxVersion is the current latest supported transaction version.
20 TxVersion = 1
21 22 // MaxTxInSequenceNum is the maximum sequence number the sequence field
23 // of a transaction input can be.
24 MaxTxInSequenceNum uint32 = 0xffffffff
25 26 // MaxPrevOutIndex is the maximum index the index field of a previous
27 // outpoint can be.
28 MaxPrevOutIndex uint32 = 0xffffffff
29 30 // SequenceLockTimeDisabled is a flag that if set on a transaction
31 // input's sequence number, the sequence number will not be interpreted
32 // as a relative locktime.
33 SequenceLockTimeDisabled = 1 << 31
34 35 // SequenceLockTimeIsSeconds is a flag that if set on a transaction
36 // input's sequence number, the relative locktime has units of 512
37 // seconds.
38 SequenceLockTimeIsSeconds = 1 << 22
39 40 // SequenceLockTimeMask is a mask that extracts the relative locktime
41 // when masked against the transaction input sequence number.
42 SequenceLockTimeMask = 0x0000ffff
43 44 // SequenceLockTimeGranularity is the defined time based granularity
45 // for seconds-based relative time locks. When converting from seconds
46 // to a sequence number, the value is right shifted by this amount,
47 // therefore the granularity of relative time locks in 512 or 2^9
48 // seconds. Enforced relative lock times are multiples of 512 seconds.
49 SequenceLockTimeGranularity = 9
50 51 // defaultTxInOutAlloc is the default size used for the backing array for
52 // transaction inputs and outputs. The array will dynamically grow as needed,
53 // but this figure is intended to provide enough space for the number of
54 // inputs and outputs in a typical transaction without needing to grow the
55 // backing array multiple times.
56 defaultTxInOutAlloc = 15
57 58 // minTxInPayload is the minimum payload size for a transaction input.
59 // PreviousOutPoint.Hash + PreviousOutPoint.Index 4 bytes + Varint for
60 // SignatureScript length 1 byte + Sequence 4 bytes.
61 minTxInPayload = 9 + chainhash.HashSize
62 63 // maxTxInPerMessage is the maximum number of transactions inputs that
64 // a transaction which fits into a message could possibly have.
65 maxTxInPerMessage = (MaxMessagePayload / minTxInPayload) + 1
66 67 // MinTxOutPayload is the minimum payload size for a transaction output.
68 // Value 8 bytes + Varint for PkScript length 1 byte.
69 MinTxOutPayload = 9
70 71 // maxTxOutPerMessage is the maximum number of transactions outputs that
72 // a transaction which fits into a message could possibly have.
73 maxTxOutPerMessage = (MaxMessagePayload / MinTxOutPayload) + 1
74 75 // minTxPayload is the minimum payload size for a transaction. Note
76 // that any realistically usable transaction must have at least one
77 // input or output, but that is a rule enforced at a higher layer, so
78 // it is intentionally not included here.
79 // Version 4 bytes + Varint number of transaction inputs 1 byte + Varint
80 // number of transaction outputs 1 byte + LockTime 4 bytes + min input
81 // payload + min output payload.
82 minTxPayload = 10
83 84 // maxWitnessItemsPerInput is the maximum number of witness items to
85 // be read for the witness data for a single TxIn. This number is
86 // derived using a possible lower bound for the encoding of a witness
87 // item: 1 byte for length + 1 byte for the witness item itself, or two
88 // bytes. This value is then divided by the currently allowed maximum
89 // "cost" for a transaction. We use this for an upper bound for the
90 // buffer and consensus makes sure that the weight of a transaction
91 // cannot be more than 4000000.
92 maxWitnessItemsPerInput = 4_000_000
93 94 // maxWitnessItemSize is the maximum allowed size for an item within
95 // an input's witness data. This value is bounded by the largest
96 // possible block size, post segwit v1 (taproot).
97 maxWitnessItemSize = 4_000_000
98 )
99 100 var (
101 // errSuperfluousWitnessRecord is returned during tx deserialization when
102 // a tx has the witness marker flag set but has no witnesses.
103 errSuperfluousWitnessRecord = fmt.Errorf(
104 "witness flag set but tx has no witnesses",
105 )
106 )
107 108 // TxFlagMarker is the first byte of the FLAG field in a bitcoin tx
109 // message. It allows decoders to distinguish a regular serialized
110 // transaction from one that would require a different parsing logic.
111 //
112 // Position of FLAG in a bitcoin tx message:
113 //
114 // ┌─────────┬────────────────────┬─────────────┬─────┐
115 // │ VERSION │ FLAG │ TX-IN-COUNT │ ... │
116 // │ 4 bytes │ 2 bytes (optional) │ varint │ │
117 // └─────────┴────────────────────┴─────────────┴─────┘
118 //
119 // Zooming into the FLAG field:
120 //
121 // ┌── FLAG ─────────────┬────────┐
122 // │ TxFlagMarker (0x00) │ TxFlag │
123 // │ 1 byte │ 1 byte │
124 // └─────────────────────┴────────┘
125 const TxFlagMarker = 0x00
126 127 // TxFlag is the second byte of the FLAG field in a bitcoin tx message.
128 // It indicates the decoding logic to use in the transaction parser, if
129 // TxFlagMarker is detected in the tx message.
130 //
131 // As of writing this, only the witness flag (0x01) is supported, but may be
132 // extended in the future to accommodate auxiliary non-committed fields.
133 type TxFlag = byte
134 135 const (
136 // WitnessFlag is a flag specific to witness encoding. If the TxFlagMarker
137 // is encountered followed by the WitnessFlag, then it indicates a
138 // transaction has witness data. This allows decoders to distinguish a
139 // serialized transaction with witnesses from a legacy one.
140 WitnessFlag TxFlag = 0x01
141 )
142 143 // OutPoint defines a bitcoin data type that is used to track previous
144 // transaction outputs.
145 type OutPoint struct {
146 Hash chainhash.Hash
147 Index uint32
148 }
149 150 // NewOutPoint returns a new bitcoin transaction outpoint point with the
151 // provided hash and index.
152 func NewOutPoint(hash *chainhash.Hash, index uint32) *OutPoint {
153 return &OutPoint{
154 Hash: *hash,
155 Index: index,
156 }
157 }
158 159 // NewOutPointFromString returns a new bitcoin transaction outpoint parsed from
160 // the provided string, which should be in the format "hash:index".
161 func NewOutPointFromString(outpoint string) (*OutPoint, error) {
162 parts := strings.Split(outpoint, ":")
163 if len(parts) != 2 {
164 return nil, errors.New("outpoint should be of the form txid:index")
165 }
166 167 if len(parts[0]) != chainhash.MaxHashStringSize {
168 return nil, errors.New("outpoint txid should be 64 hex chars")
169 }
170 171 hash, err := chainhash.NewHashFromStr(parts[0])
172 if err != nil {
173 return nil, err
174 }
175 176 outputIndex, err := strconv.ParseUint(parts[1], 10, 32)
177 if err != nil {
178 return nil, fmt.Errorf("invalid output index: %v", err)
179 }
180 181 return &OutPoint{
182 Hash: *hash,
183 Index: uint32(outputIndex),
184 }, nil
185 }
186 187 // String returns the OutPoint in the human-readable form "hash:index".
188 func (o OutPoint) String() string {
189 // Allocate enough for hash string, colon, and 10 digits. Although
190 // at the time of writing, the number of digits can be no greater than
191 // the length of the decimal representation of maxTxOutPerMessage, the
192 // maximum message payload may increase in the future and this
193 // optimization may go unnoticed, so allocate space for 10 decimal
194 // digits, which will fit any uint32.
195 buf := make([]byte, 2*chainhash.HashSize+1, 2*chainhash.HashSize+1+10)
196 copy(buf, o.Hash.String())
197 buf[2*chainhash.HashSize] = ':'
198 buf = strconv.AppendUint(buf, uint64(o.Index), 10)
199 return string(buf)
200 }
201 202 // TxIn defines a bitcoin transaction input.
203 type TxIn struct {
204 PreviousOutPoint OutPoint
205 SignatureScript []byte
206 Witness TxWitness
207 Sequence uint32
208 }
209 210 // SerializeSize returns the number of bytes it would take to serialize the
211 // the transaction input.
212 func (t *TxIn) SerializeSize() int {
213 // Outpoint Hash 32 bytes + Outpoint Index 4 bytes + Sequence 4 bytes +
214 // serialized varint size for the length of SignatureScript +
215 // SignatureScript bytes.
216 return 40 + VarIntSerializeSize(uint64(len(t.SignatureScript))) +
217 len(t.SignatureScript)
218 }
219 220 // NewTxIn returns a new bitcoin transaction input with the provided
221 // previous outpoint point and signature script with a default sequence of
222 // MaxTxInSequenceNum.
223 func NewTxIn(prevOut *OutPoint, signatureScript []byte, witness [][]byte) *TxIn {
224 return &TxIn{
225 PreviousOutPoint: *prevOut,
226 SignatureScript: signatureScript,
227 Witness: witness,
228 Sequence: MaxTxInSequenceNum,
229 }
230 }
231 232 // TxWitness defines the witness for a TxIn. A witness is to be interpreted as
233 // a slice of byte slices, or a stack with one or many elements.
234 type TxWitness [][]byte
235 236 // SerializeSize returns the number of bytes it would take to serialize the
237 // transaction input's witness.
238 func (t TxWitness) SerializeSize() int {
239 // A varint to signal the number of elements the witness has.
240 n := VarIntSerializeSize(uint64(len(t)))
241 242 // For each element in the witness, we'll need a varint to signal the
243 // size of the element, then finally the number of bytes the element
244 // itself comprises.
245 for _, witItem := range t {
246 n += VarIntSerializeSize(uint64(len(witItem)))
247 n += len(witItem)
248 }
249 250 return n
251 }
252 253 // ToHexStrings formats the witness stack as a slice of hex-encoded strings.
254 func (t TxWitness) ToHexStrings() []string {
255 // Ensure nil is returned when there are no entries versus an empty
256 // slice so it can properly be omitted as necessary.
257 if len(t) == 0 {
258 return nil
259 }
260 261 result := make([]string, len(t))
262 for idx, wit := range t {
263 result[idx] = hex.EncodeToString(wit)
264 }
265 266 return result
267 }
268 269 // TxOut defines a bitcoin transaction output.
270 type TxOut struct {
271 Value int64
272 PkScript []byte
273 }
274 275 // SerializeSize returns the number of bytes it would take to serialize the
276 // the transaction output.
277 func (t *TxOut) SerializeSize() int {
278 // Value 8 bytes + serialized varint size for the length of PkScript +
279 // PkScript bytes.
280 return 8 + VarIntSerializeSize(uint64(len(t.PkScript))) + len(t.PkScript)
281 }
282 283 // NewTxOut returns a new bitcoin transaction output with the provided
284 // transaction value and public key script.
285 func NewTxOut(value int64, pkScript []byte) *TxOut {
286 return &TxOut{
287 Value: value,
288 PkScript: pkScript,
289 }
290 }
291 292 // MsgTx implements the Message interface and represents a bitcoin tx message.
293 // It is used to deliver transaction information in response to a getdata
294 // message (MsgGetData) for a given transaction.
295 //
296 // Use the AddTxIn and AddTxOut functions to build up the list of transaction
297 // inputs and outputs.
298 type MsgTx struct {
299 Version int32
300 TxIn []*TxIn
301 TxOut []*TxOut
302 LockTime uint32
303 }
304 305 // AddTxIn adds a transaction input to the message.
306 func (msg *MsgTx) AddTxIn(ti *TxIn) {
307 msg.TxIn = append(msg.TxIn, ti)
308 }
309 310 // AddTxOut adds a transaction output to the message.
311 func (msg *MsgTx) AddTxOut(to *TxOut) {
312 msg.TxOut = append(msg.TxOut, to)
313 }
314 315 // TxHash generates the Hash for the transaction.
316 func (msg *MsgTx) TxHash() chainhash.Hash {
317 return chainhash.DoubleHashRaw(msg.SerializeNoWitness)
318 }
319 320 // TxID generates the transaction ID of the transaction.
321 func (msg *MsgTx) TxID() string {
322 return msg.TxHash().String()
323 }
324 325 // WitnessHash generates the hash of the transaction serialized according to
326 // the new witness serialization defined in BIP0141 and BIP0144. The final
327 // output is used within the Segregated Witness commitment of all the witnesses
328 // within a block. If a transaction has no witness data, then the witness hash,
329 // is the same as its txid.
330 func (msg *MsgTx) WitnessHash() chainhash.Hash {
331 if msg.HasWitness() {
332 return chainhash.DoubleHashRaw(msg.Serialize)
333 }
334 335 return msg.TxHash()
336 }
337 338 // Copy creates a deep copy of a transaction so that the original does not get
339 // modified when the copy is manipulated.
340 func (msg *MsgTx) Copy() *MsgTx {
341 // Create new tx and start by copying primitive values and making space
342 // for the transaction inputs and outputs.
343 newTx := MsgTx{
344 Version: msg.Version,
345 TxIn: make([]*TxIn, 0, len(msg.TxIn)),
346 TxOut: make([]*TxOut, 0, len(msg.TxOut)),
347 LockTime: msg.LockTime,
348 }
349 350 // Deep copy the old TxIn data.
351 for _, oldTxIn := range msg.TxIn {
352 // Deep copy the old previous outpoint.
353 oldOutPoint := oldTxIn.PreviousOutPoint
354 newOutPoint := OutPoint{}
355 newOutPoint.Hash.SetBytes(oldOutPoint.Hash[:])
356 newOutPoint.Index = oldOutPoint.Index
357 358 // Deep copy the old signature script.
359 var newScript []byte
360 oldScript := oldTxIn.SignatureScript
361 oldScriptLen := len(oldScript)
362 if oldScriptLen > 0 {
363 newScript = make([]byte, oldScriptLen)
364 copy(newScript, oldScript[:oldScriptLen])
365 }
366 367 // Create new txIn with the deep copied data.
368 newTxIn := TxIn{
369 PreviousOutPoint: newOutPoint,
370 SignatureScript: newScript,
371 Sequence: oldTxIn.Sequence,
372 }
373 374 // If the transaction is witnessy, then also copy the
375 // witnesses.
376 if len(oldTxIn.Witness) != 0 {
377 // Deep copy the old witness data.
378 newTxIn.Witness = make([][]byte, len(oldTxIn.Witness))
379 for i, oldItem := range oldTxIn.Witness {
380 newItem := make([]byte, len(oldItem))
381 copy(newItem, oldItem)
382 newTxIn.Witness[i] = newItem
383 }
384 }
385 386 // Finally, append this fully copied txin.
387 newTx.TxIn = append(newTx.TxIn, &newTxIn)
388 }
389 390 // Deep copy the old TxOut data.
391 for _, oldTxOut := range msg.TxOut {
392 // Deep copy the old PkScript
393 var newScript []byte
394 oldScript := oldTxOut.PkScript
395 oldScriptLen := len(oldScript)
396 if oldScriptLen > 0 {
397 newScript = make([]byte, oldScriptLen)
398 copy(newScript, oldScript[:oldScriptLen])
399 }
400 401 // Create new txOut with the deep copied data and append it to
402 // new Tx.
403 newTxOut := TxOut{
404 Value: oldTxOut.Value,
405 PkScript: newScript,
406 }
407 newTx.TxOut = append(newTx.TxOut, &newTxOut)
408 }
409 410 return &newTx
411 }
412 413 // BtcDecode decodes r using the bitcoin protocol encoding into the receiver.
414 // This is part of the Message interface implementation.
415 // See Deserialize for decoding transactions stored to disk, such as in a
416 // database, as opposed to decoding transactions from the wire.
417 // If decoding fails, TxIn and TxOut are cleared. Other fields may be partially
418 // populated, so the receiver's contents must not be used unless a subsequent
419 // decode succeeds.
420 func (msg *MsgTx) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) error {
421 buf := binarySerializer.Borrow()
422 defer binarySerializer.Return(buf)
423 424 ar := borrowScriptArena()
425 defer ar.release()
426 427 err := msg.btcDecode(r, pver, enc, buf, ar)
428 if err != nil {
429 // Drop staged scripts before their arena is returned to the pool.
430 msg.TxIn = nil
431 msg.TxOut = nil
432 }
433 return err
434 }
435 436 func (msg *MsgTx) btcDecode(r io.Reader, pver uint32, enc MessageEncoding,
437 buf []byte, ar *scriptArena) error {
438 439 // Any script data staged by a previous transaction decoded with this
440 // arena has already been copied into its final exactly-sized buffer,
441 // so the arena memory can be reused from the start.
442 ar.rewind()
443 444 if _, err := io.ReadFull(r, buf[:4]); err != nil {
445 return err
446 }
447 msg.Version = int32(littleEndian.Uint32(buf[:4]))
448 449 count, err := ReadVarIntBuf(r, pver, buf)
450 if err != nil {
451 return err
452 }
453 454 // A count of zero (meaning no TxIn's to the uninitiated) means that the
455 // value is a TxFlagMarker, and hence indicates the presence of a flag.
456 var flag [1]TxFlag
457 if count == TxFlagMarker && enc == WitnessEncoding {
458 // The count varint was in fact the flag marker byte. Next, we need to
459 // read the flag value, which is a single byte.
460 if _, err = io.ReadFull(r, flag[:]); err != nil {
461 return err
462 }
463 464 // At the moment, the flag MUST be WitnessFlag (0x01). In the future
465 // other flag types may be supported.
466 if flag[0] != WitnessFlag {
467 str := fmt.Sprintf("witness tx but flag byte is %x", flag)
468 return messageError("MsgTx.BtcDecode", str)
469 }
470 471 // With the Segregated Witness specific fields decoded, we can
472 // now read in the actual txin count.
473 count, err = ReadVarIntBuf(r, pver, buf)
474 if err != nil {
475 return err
476 }
477 }
478 479 // Prevent more input transactions than could possibly fit into a
480 // message. It would be possible to cause memory exhaustion and panics
481 // without a sane upper bound on this count.
482 if count > uint64(maxTxInPerMessage) {
483 str := fmt.Sprintf("too many input transactions to fit into "+
484 "max message size [count %d, max %d]", count,
485 maxTxInPerMessage)
486 return messageError("MsgTx.BtcDecode", str)
487 }
488 preallocateInputs, err := canPreallocateElements(
489 r, count, minTxInPayload,
490 )
491 if err != nil {
492 return err
493 }
494 495 // Deserialize the inputs.
496 var totalScriptSize uint64
497 var txIns []TxIn
498 if preallocateInputs {
499 txIns = make([]TxIn, count)
500 msg.TxIn = make([]*TxIn, count)
501 } else {
502 txIns = make(
503 []TxIn, 0, min(count, defaultStreamingElementCap),
504 )
505 msg.TxIn = nil
506 }
507 for i := uint64(0); i < count; i++ {
508 if !preallocateInputs {
509 txIns = append(txIns, TxIn{})
510 }
511 512 // Buffered inputs can point into their final backing array before
513 // the decode call populates it. Streaming inputs are wired up once
514 // their backing array stops growing.
515 ti := &txIns[i]
516 if preallocateInputs {
517 msg.TxIn[i] = ti
518 }
519 err = readTxInBuf(r, pver, msg.Version, ti, buf, ar)
520 if err != nil {
521 return err
522 }
523 totalScriptSize += uint64(len(ti.SignatureScript))
524 }
525 if !preallocateInputs {
526 msg.TxIn = make([]*TxIn, len(txIns))
527 for i := range txIns {
528 msg.TxIn[i] = &txIns[i]
529 }
530 }
531 532 count, err = ReadVarIntBuf(r, pver, buf)
533 if err != nil {
534 return err
535 }
536 537 // Prevent more output transactions than could possibly fit into a
538 // message. It would be possible to cause memory exhaustion and panics
539 // without a sane upper bound on this count.
540 if count > uint64(maxTxOutPerMessage) {
541 str := fmt.Sprintf("too many output transactions to fit into "+
542 "max message size [count %d, max %d]", count,
543 maxTxOutPerMessage)
544 return messageError("MsgTx.BtcDecode", str)
545 }
546 preallocateOutputs, err := canPreallocateElements(
547 r, count, MinTxOutPayload,
548 )
549 if err != nil {
550 return err
551 }
552 553 // Deserialize the outputs.
554 var txOuts []TxOut
555 if preallocateOutputs {
556 txOuts = make([]TxOut, count)
557 msg.TxOut = make([]*TxOut, count)
558 } else {
559 txOuts = make(
560 []TxOut, 0, min(count, defaultStreamingElementCap),
561 )
562 msg.TxOut = nil
563 }
564 for i := uint64(0); i < count; i++ {
565 if !preallocateOutputs {
566 txOuts = append(txOuts, TxOut{})
567 }
568 569 // Buffered outputs can point into their final backing array before
570 // the decode call populates it. Streaming outputs are wired up once
571 // their backing array stops growing.
572 to := &txOuts[i]
573 if preallocateOutputs {
574 msg.TxOut[i] = to
575 }
576 err = readTxOutBuf(r, pver, msg.Version, to, buf, ar)
577 if err != nil {
578 return err
579 }
580 totalScriptSize += uint64(len(to.PkScript))
581 }
582 if !preallocateOutputs {
583 msg.TxOut = make([]*TxOut, len(txOuts))
584 for i := range txOuts {
585 msg.TxOut[i] = &txOuts[i]
586 }
587 }
588 589 // If the transaction's flag byte isn't 0x00 at this point, then one or
590 // more of its inputs has accompanying witness data.
591 if flag[0] != 0 && enc == WitnessEncoding {
592 for _, txin := range msg.TxIn {
593 // For each input, the witness is encoded as a stack
594 // with one or more items. Therefore, we first read a
595 // varint which encodes the number of stack items.
596 witCount, err := ReadVarIntBuf(r, pver, buf)
597 if err != nil {
598 return err
599 }
600 601 // Prevent a possible memory exhaustion attack by
602 // limiting the witCount value to a sane upper bound.
603 if witCount > maxWitnessItemsPerInput {
604 str := fmt.Sprintf("too many witness items to fit "+
605 "into max message size [count %d, max %d]",
606 witCount, maxWitnessItemsPerInput)
607 return messageError("MsgTx.BtcDecode", str)
608 }
609 preallocateWitness, err := canPreallocateElements(
610 r, witCount, 1,
611 )
612 if err != nil {
613 return err
614 }
615 616 // Then for witCount number of stack items, each item
617 // has a varint length prefix, followed by the witness
618 // item itself.
619 if preallocateWitness {
620 txin.Witness = make([][]byte, witCount)
621 } else {
622 txin.Witness = make(
623 [][]byte, 0,
624 min(witCount, defaultStreamingElementCap),
625 )
626 }
627 for j := uint64(0); j < witCount; j++ {
628 item, err := readScriptBuf(
629 r, pver, buf, ar, "script witness item",
630 )
631 if err != nil {
632 return err
633 }
634 if preallocateWitness {
635 txin.Witness[j] = item
636 } else {
637 txin.Witness = append(txin.Witness, item)
638 }
639 totalScriptSize += uint64(len(item))
640 }
641 }
642 643 // Check that if the witness flag is set that we actually have
644 // witnesses. This check is also done by bitcoind.
645 if !msg.HasWitness() {
646 return errSuperfluousWitnessRecord
647 }
648 }
649 650 if _, err := io.ReadFull(r, buf[:4]); err != nil {
651 return err
652 }
653 msg.LockTime = littleEndian.Uint32(buf[:4])
654 655 // Create a single allocation to house all of the scripts and set each
656 // input signature script, witness item, and output public key script
657 // to the appropriate subslice of the overall contiguous buffer. This
658 // copies the scripts out of the transient decode arena into memory
659 // the transaction owns, which is what makes rewinding the arena for
660 // the next transaction safe. A single backing allocation also
661 // significantly reduces the number of allocations the garbage
662 // collector needs to track, which in turn improves performance and
663 // drastically reduces the amount of runtime overhead that would
664 // otherwise be needed to keep track of millions of small allocations.
665 //
666 // NOTE: After these blocks of code run, no script in the transaction
667 // points into the arena any longer.
668 var offset uint64
669 scripts := make([]byte, totalScriptSize)
670 for i := 0; i < len(msg.TxIn); i++ {
671 // Copy the signature script into the contiguous buffer at the
672 // appropriate offset.
673 signatureScript := msg.TxIn[i].SignatureScript
674 copy(scripts[offset:], signatureScript)
675 676 // Reset the signature script of the transaction input to the
677 // slice of the contiguous buffer where the script lives.
678 scriptSize := uint64(len(signatureScript))
679 end := offset + scriptSize
680 msg.TxIn[i].SignatureScript = scripts[offset:end:end]
681 offset += scriptSize
682 683 for j := 0; j < len(msg.TxIn[i].Witness); j++ {
684 // Copy each item within the witness stack for this
685 // input into the contiguous buffer at the appropriate
686 // offset.
687 witnessElem := msg.TxIn[i].Witness[j]
688 copy(scripts[offset:], witnessElem)
689 690 // Reset the witness item within the stack to the slice
691 // of the contiguous buffer where the witness lives.
692 witnessElemSize := uint64(len(witnessElem))
693 end := offset + witnessElemSize
694 msg.TxIn[i].Witness[j] = scripts[offset:end:end]
695 offset += witnessElemSize
696 }
697 }
698 for i := 0; i < len(msg.TxOut); i++ {
699 // Copy the public key script into the contiguous buffer at the
700 // appropriate offset.
701 pkScript := msg.TxOut[i].PkScript
702 copy(scripts[offset:], pkScript)
703 704 // Reset the public key script of the transaction output to the
705 // slice of the contiguous buffer where the script lives.
706 scriptSize := uint64(len(pkScript))
707 end := offset + scriptSize
708 msg.TxOut[i].PkScript = scripts[offset:end:end]
709 offset += scriptSize
710 }
711 712 return nil
713 }
714 715 // Deserialize decodes a transaction from r into the receiver using a format
716 // that is suitable for long-term storage such as a database while respecting
717 // the Version field in the transaction. This function differs from BtcDecode
718 // in that BtcDecode decodes from the bitcoin wire protocol as it was sent
719 // across the network. The wire encoding can technically differ depending on
720 // the protocol version and doesn't even really need to match the format of a
721 // stored transaction at all. As of the time this comment was written, the
722 // encoded transaction is the same in both instances, but there is a distinct
723 // difference and separating the two allows the API to be flexible enough to
724 // deal with changes.
725 func (msg *MsgTx) Deserialize(r io.Reader) error {
726 // At the current time, there is no difference between the wire encoding
727 // at protocol version 0 and the stable long-term storage format. As
728 // a result, make use of BtcDecode.
729 return msg.BtcDecode(r, 0, WitnessEncoding)
730 }
731 732 // DeserializeNoWitness decodes a transaction from r into the receiver, where
733 // the transaction encoding format within r MUST NOT utilize the new
734 // serialization format created to encode transaction bearing witness data
735 // within inputs.
736 func (msg *MsgTx) DeserializeNoWitness(r io.Reader) error {
737 return msg.BtcDecode(r, 0, BaseEncoding)
738 }
739 740 // BtcEncode encodes the receiver to w using the bitcoin protocol encoding.
741 // This is part of the Message interface implementation.
742 // See Serialize for encoding transactions to be stored to disk, such as in a
743 // database, as opposed to encoding transactions for the wire.
744 func (msg *MsgTx) BtcEncode(w io.Writer, pver uint32, enc MessageEncoding) error {
745 buf := binarySerializer.Borrow()
746 defer binarySerializer.Return(buf)
747 748 err := msg.btcEncode(w, pver, enc, buf)
749 return err
750 }
751 752 func (msg *MsgTx) btcEncode(w io.Writer, pver uint32, enc MessageEncoding,
753 buf []byte) error {
754 755 littleEndian.PutUint32(buf[:4], uint32(msg.Version))
756 if _, err := w.Write(buf[:4]); err != nil {
757 return err
758 }
759 760 // If the encoding version is set to WitnessEncoding, and the Flags
761 // field for the MsgTx aren't 0x00, then this indicates the transaction
762 // is to be encoded using the new witness inclusionary structure
763 // defined in BIP0144.
764 doWitness := enc == WitnessEncoding && msg.HasWitness()
765 if doWitness {
766 // After the transaction's Version field, we include two additional
767 // bytes specific to the witness encoding. This byte sequence is known
768 // as a flag. The first byte is a marker byte (TxFlagMarker) and the
769 // second one is the flag value to indicate presence of witness data.
770 if _, err := w.Write([]byte{TxFlagMarker, WitnessFlag}); err != nil {
771 return err
772 }
773 }
774 775 count := uint64(len(msg.TxIn))
776 err := WriteVarIntBuf(w, pver, count, buf)
777 if err != nil {
778 return err
779 }
780 781 for _, ti := range msg.TxIn {
782 err = writeTxInBuf(w, pver, msg.Version, ti, buf)
783 if err != nil {
784 return err
785 }
786 }
787 788 count = uint64(len(msg.TxOut))
789 err = WriteVarIntBuf(w, pver, count, buf)
790 if err != nil {
791 return err
792 }
793 794 for _, to := range msg.TxOut {
795 err = WriteTxOutBuf(w, pver, msg.Version, to, buf)
796 if err != nil {
797 return err
798 }
799 }
800 801 // If this transaction is a witness transaction, and the witness
802 // encoded is desired, then encode the witness for each of the inputs
803 // within the transaction.
804 if doWitness {
805 for _, ti := range msg.TxIn {
806 err = writeTxWitnessBuf(w, pver, msg.Version, ti.Witness, buf)
807 if err != nil {
808 return err
809 }
810 }
811 }
812 813 littleEndian.PutUint32(buf[:4], msg.LockTime)
814 _, err = w.Write(buf[:4])
815 return err
816 }
817 818 // HasWitness returns false if none of the inputs within the transaction
819 // contain witness data, true false otherwise.
820 func (msg *MsgTx) HasWitness() bool {
821 for _, txIn := range msg.TxIn {
822 if len(txIn.Witness) != 0 {
823 return true
824 }
825 }
826 827 return false
828 }
829 830 // Serialize encodes the transaction to w using a format that suitable for
831 // long-term storage such as a database while respecting the Version field in
832 // the transaction. This function differs from BtcEncode in that BtcEncode
833 // encodes the transaction to the bitcoin wire protocol in order to be sent
834 // across the network. The wire encoding can technically differ depending on
835 // the protocol version and doesn't even really need to match the format of a
836 // stored transaction at all. As of the time this comment was written, the
837 // encoded transaction is the same in both instances, but there is a distinct
838 // difference and separating the two allows the API to be flexible enough to
839 // deal with changes.
840 func (msg *MsgTx) Serialize(w io.Writer) error {
841 // At the current time, there is no difference between the wire encoding
842 // at protocol version 0 and the stable long-term storage format. As
843 // a result, make use of BtcEncode.
844 //
845 // Passing a encoding type of WitnessEncoding to BtcEncode for MsgTx
846 // indicates that the transaction's witnesses (if any) should be
847 // serialized according to the new serialization structure defined in
848 // BIP0144.
849 return msg.BtcEncode(w, 0, WitnessEncoding)
850 }
851 852 // SerializeNoWitness encodes the transaction to w in an identical manner to
853 // Serialize, however even if the source transaction has inputs with witness
854 // data, the old serialization format will still be used.
855 func (msg *MsgTx) SerializeNoWitness(w io.Writer) error {
856 return msg.BtcEncode(w, 0, BaseEncoding)
857 }
858 859 // baseSize returns the serialized size of the transaction without accounting
860 // for any witness data.
861 func (msg *MsgTx) baseSize() int {
862 // Version 4 bytes + LockTime 4 bytes + Serialized varint size for the
863 // number of transaction inputs and outputs.
864 n := 8 + VarIntSerializeSize(uint64(len(msg.TxIn))) +
865 VarIntSerializeSize(uint64(len(msg.TxOut)))
866 867 for _, txIn := range msg.TxIn {
868 n += txIn.SerializeSize()
869 }
870 871 for _, txOut := range msg.TxOut {
872 n += txOut.SerializeSize()
873 }
874 875 return n
876 }
877 878 // SerializeSize returns the number of bytes it would take to serialize the
879 // the transaction.
880 func (msg *MsgTx) SerializeSize() int {
881 n := msg.baseSize()
882 883 if msg.HasWitness() {
884 // The marker, and flag fields take up two additional bytes.
885 n += 2
886 887 // Additionally, factor in the serialized size of each of the
888 // witnesses for each txin.
889 for _, txin := range msg.TxIn {
890 n += txin.Witness.SerializeSize()
891 }
892 }
893 894 return n
895 }
896 897 // SerializeSizeStripped returns the number of bytes it would take to serialize
898 // the transaction, excluding any included witness data.
899 func (msg *MsgTx) SerializeSizeStripped() int {
900 return msg.baseSize()
901 }
902 903 // Command returns the protocol command string for the message. This is part
904 // of the Message interface implementation.
905 func (msg *MsgTx) Command() string {
906 return CmdTx
907 }
908 909 // MaxPayloadLength returns the maximum length the payload can be for the
910 // receiver. This is part of the Message interface implementation.
911 func (msg *MsgTx) MaxPayloadLength(pver uint32) uint32 {
912 return MaxBlockPayload
913 }
914 915 // PkScriptLocs returns a slice containing the start of each public key script
916 // within the raw serialized transaction. The caller can easily obtain the
917 // length of each script by using len on the script available via the
918 // appropriate transaction output entry.
919 func (msg *MsgTx) PkScriptLocs() []int {
920 numTxOut := len(msg.TxOut)
921 if numTxOut == 0 {
922 return nil
923 }
924 925 // The starting offset in the serialized transaction of the first
926 // transaction output is:
927 //
928 // Version 4 bytes + serialized varint size for the number of
929 // transaction inputs and outputs + serialized size of each transaction
930 // input.
931 n := 4 + VarIntSerializeSize(uint64(len(msg.TxIn))) +
932 VarIntSerializeSize(uint64(numTxOut))
933 934 // If this transaction has a witness input, the an additional two bytes
935 // for the marker, and flag byte need to be taken into account.
936 if len(msg.TxIn) > 0 && msg.TxIn[0].Witness != nil {
937 n += 2
938 }
939 940 for _, txIn := range msg.TxIn {
941 n += txIn.SerializeSize()
942 }
943 944 // Calculate and set the appropriate offset for each public key script.
945 pkScriptLocs := make([]int, numTxOut)
946 for i, txOut := range msg.TxOut {
947 // The offset of the script in the transaction output is:
948 //
949 // Value 8 bytes + serialized varint size for the length of
950 // PkScript.
951 n += 8 + VarIntSerializeSize(uint64(len(txOut.PkScript)))
952 pkScriptLocs[i] = n
953 n += len(txOut.PkScript)
954 }
955 956 return pkScriptLocs
957 }
958 959 // NewMsgTx returns a new bitcoin tx message that conforms to the Message
960 // interface. The return instance has a default version of TxVersion and there
961 // are no transaction inputs or outputs. Also, the lock time is set to zero
962 // to indicate the transaction is valid immediately as opposed to some time in
963 // future.
964 func NewMsgTx(version int32) *MsgTx {
965 return &MsgTx{
966 Version: version,
967 TxIn: make([]*TxIn, 0, defaultTxInOutAlloc),
968 TxOut: make([]*TxOut, 0, defaultTxInOutAlloc),
969 }
970 }
971 972 // readOutPointBuf reads the next sequence of bytes from r as an OutPoint.
973 //
974 // NOTE: buf MUST be at least an 8-byte slice.
975 func readOutPointBuf(r io.Reader, pver uint32, version int32, op *OutPoint,
976 buf []byte) error {
977 978 _, err := io.ReadFull(r, op.Hash[:])
979 if err != nil {
980 return err
981 }
982 983 if _, err := io.ReadFull(r, buf[:4]); err != nil {
984 return err
985 }
986 op.Index = littleEndian.Uint32(buf[:4])
987 988 return nil
989 }
990 991 // WriteOutPoint encodes op to the bitcoin protocol encoding for an OutPoint to
992 // w.
993 func WriteOutPoint(w io.Writer, pver uint32, version int32, op *OutPoint) error {
994 buf := binarySerializer.Borrow()
995 defer binarySerializer.Return(buf)
996 997 err := writeOutPointBuf(w, pver, version, op, buf)
998 return err
999 }
1000 1001 // writeOutPointBuf encodes op to the bitcoin protocol encoding for an OutPoint
1002 // to w.
1003 //
1004 // NOTE: buf MUST be at least an 8-byte slice.
1005 func writeOutPointBuf(w io.Writer, pver uint32, version int32, op *OutPoint,
1006 buf []byte) error {
1007 1008 _, err := w.Write(op.Hash[:])
1009 if err != nil {
1010 return err
1011 }
1012 1013 littleEndian.PutUint32(buf[:4], op.Index)
1014 _, err = w.Write(buf[:4])
1015 return err
1016 }
1017 1018 // readScriptBuf reads a variable length byte array that represents a
1019 // transaction script. It is encoded as a varInt containing the length of the
1020 // array followed by the bytes themselves. The script bytes are staged in the
1021 // provided arena, so the returned slice is only valid until the arena is
1022 // rewound or released. An error is returned if the length is greater than
1023 // the max allowed script size which helps protect against memory exhaustion
1024 // attacks and forced panics through malformed messages. The fieldName
1025 // parameter is only used for the error message so it provides more context in
1026 // the error.
1027 //
1028 // NOTE: buf MUST be at least an 8-byte slice.
1029 func readScriptBuf(r io.Reader, pver uint32, buf []byte, ar *scriptArena,
1030 fieldName string) ([]byte, error) {
1031 1032 count, err := ReadVarIntBuf(r, pver, buf)
1033 if err != nil {
1034 return nil, err
1035 }
1036 1037 // Prevent byte array larger than the max message size. It would
1038 // be possible to cause memory exhaustion and panics without a sane
1039 // upper bound on this count.
1040 if count > maxWitnessItemSize {
1041 str := fmt.Sprintf("%s is larger than the max allowed size "+
1042 "[count %d, max %d]", fieldName, count,
1043 maxWitnessItemSize)
1044 return nil, messageError("readScript", str)
1045 }
1046 1047 // Stage the script in the decode arena. This fails if the total
1048 // script data staged for the transaction being decoded exceeds the
1049 // arena capacity, which no valid transaction can reach.
1050 s, err := ar.alloc(int(count))
1051 if err != nil {
1052 str := fmt.Sprintf("%s exceeds remaining buffer "+
1053 "capacity [count %d, remaining %d]",
1054 fieldName, count, ar.remaining())
1055 return nil, messageError("readScript", str)
1056 }
1057 1058 _, err = io.ReadFull(r, s)
1059 if err != nil {
1060 return nil, err
1061 }
1062 return s, nil
1063 }
1064 1065 // readTxInBuf reads the next sequence of bytes from r as a transaction input
1066 // (TxIn).
1067 //
1068 // NOTE: buf MUST be at least an 8-byte slice.
1069 func readTxInBuf(r io.Reader, pver uint32, version int32, ti *TxIn,
1070 buf []byte, ar *scriptArena) error {
1071 1072 err := readOutPointBuf(r, pver, version, &ti.PreviousOutPoint, buf)
1073 if err != nil {
1074 return err
1075 }
1076 1077 ti.SignatureScript, err = readScriptBuf(
1078 r, pver, buf, ar, "transaction input signature script",
1079 )
1080 if err != nil {
1081 return err
1082 }
1083 1084 if _, err := io.ReadFull(r, buf[:4]); err != nil {
1085 return err
1086 }
1087 1088 ti.Sequence = littleEndian.Uint32(buf[:4])
1089 1090 return nil
1091 }
1092 1093 // writeTxInBuf encodes ti to the bitcoin protocol encoding for a transaction
1094 // input (TxIn) to w. The buf parameter is the scratch buffer used for
1095 // serializing small values.
1096 func writeTxInBuf(w io.Writer, pver uint32, version int32, ti *TxIn,
1097 buf []byte) error {
1098 1099 err := writeOutPointBuf(w, pver, version, &ti.PreviousOutPoint, buf)
1100 if err != nil {
1101 return err
1102 }
1103 1104 err = WriteVarBytesBuf(w, pver, ti.SignatureScript, buf)
1105 if err != nil {
1106 return err
1107 }
1108 1109 littleEndian.PutUint32(buf[:4], ti.Sequence)
1110 _, err = w.Write(buf[:4])
1111 1112 return err
1113 }
1114 1115 // ReadTxOut reads the next sequence of bytes from r as a transaction output
1116 // (TxOut).
1117 func ReadTxOut(r io.Reader, pver uint32, version int32, to *TxOut) error {
1118 buf := binarySerializer.Borrow()
1119 defer binarySerializer.Return(buf)
1120 1121 ar := borrowScriptArena()
1122 defer ar.release()
1123 1124 err := readTxOutBuf(r, pver, version, to, buf, ar)
1125 if err != nil {
1126 return err
1127 }
1128 1129 // The script is staged in the arena, which is recycled once this
1130 // function returns, so copy it into an exactly-sized allocation the
1131 // returned output owns.
1132 pkScript := make([]byte, len(to.PkScript))
1133 copy(pkScript, to.PkScript)
1134 to.PkScript = pkScript
1135 1136 return nil
1137 }
1138 1139 // readTxOutBuf reads the next sequence of bytes from r as a transaction output
1140 // (TxOut). The buf parameter is the scratch buffer used for serializing
1141 // small values.
1142 func readTxOutBuf(r io.Reader, pver uint32, version int32, to *TxOut,
1143 buf []byte, ar *scriptArena) error {
1144 1145 _, err := io.ReadFull(r, buf)
1146 if err != nil {
1147 return err
1148 }
1149 to.Value = int64(littleEndian.Uint64(buf))
1150 1151 to.PkScript, err = readScriptBuf(
1152 r, pver, buf, ar, "transaction output public key script",
1153 )
1154 return err
1155 }
1156 1157 // WriteTxOut encodes to into the bitcoin protocol encoding for a transaction
1158 // output (TxOut) to w.
1159 //
1160 // NOTE: This function is exported in order to allow txscript to compute the
1161 // new sighashes for witness transactions (BIP0143).
1162 func WriteTxOut(w io.Writer, pver uint32, version int32, to *TxOut) error {
1163 buf := binarySerializer.Borrow()
1164 defer binarySerializer.Return(buf)
1165 1166 err := WriteTxOutBuf(w, pver, version, to, buf)
1167 return err
1168 }
1169 1170 // WriteTxOutBuf encodes to into the bitcoin protocol encoding for a transaction
1171 // output (TxOut) to w. The buf parameter is the scratch buffer used for
1172 // serializing small values.
1173 //
1174 // NOTE: This function is exported in order to allow txscript to compute the
1175 // new sighashes for witness transactions (BIP0143).
1176 func WriteTxOutBuf(w io.Writer, pver uint32, version int32, to *TxOut,
1177 buf []byte) error {
1178 1179 littleEndian.PutUint64(buf, uint64(to.Value))
1180 _, err := w.Write(buf)
1181 if err != nil {
1182 return err
1183 }
1184 1185 return WriteVarBytesBuf(w, pver, to.PkScript, buf)
1186 }
1187 1188 // writeTxWitnessBuf encodes the bitcoin protocol encoding for a transaction
1189 // input's witness into to w. The buf parameter is the scratch buffer used
1190 // for serializing small values.
1191 func writeTxWitnessBuf(w io.Writer, pver uint32, version int32, wit [][]byte,
1192 buf []byte) error {
1193 1194 err := WriteVarIntBuf(w, pver, uint64(len(wit)), buf)
1195 if err != nil {
1196 return err
1197 }
1198 for _, item := range wit {
1199 err = WriteVarBytesBuf(w, pver, item, buf)
1200 if err != nil {
1201 return err
1202 }
1203 }
1204 1205 return nil
1206 }
1207