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