msgblock.go raw

   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  
  12  	"github.com/btcsuite/btcd/chainhash/v2"
  13  )
  14  
  15  // defaultTransactionAlloc is the default size used for the backing array
  16  // for transactions.  The transaction array will dynamically grow as needed, but
  17  // this figure is intended to provide enough space for the number of
  18  // transactions in the vast majority of blocks without needing to grow the
  19  // backing array multiple times.
  20  const defaultTransactionAlloc = 2048
  21  
  22  // MaxBlocksPerMsg is the maximum number of blocks allowed per message.
  23  const MaxBlocksPerMsg = 500
  24  
  25  // MaxBlockPayload is the maximum bytes a block message can be in bytes.
  26  // After Segregated Witness, the max block payload has been raised to 4MB.
  27  const MaxBlockPayload = 4000000
  28  
  29  // maxTxPerBlock is the maximum number of transactions that could
  30  // possibly fit into a block.
  31  const maxTxPerBlock = (MaxBlockPayload / minTxPayload) + 1
  32  
  33  // TxLoc holds locator data for the offset and length of where a transaction is
  34  // located within a MsgBlock data buffer.
  35  type TxLoc struct {
  36  	TxStart int
  37  	TxLen   int
  38  }
  39  
  40  // MsgBlock implements the Message interface and represents a bitcoin
  41  // block message.  It is used to deliver block and transaction information in
  42  // response to a getdata message (MsgGetData) for a given block hash.
  43  type MsgBlock struct {
  44  	Header       BlockHeader
  45  	Transactions []*MsgTx
  46  }
  47  
  48  // Copy creates a deep copy of MsgBlock.
  49  func (msg *MsgBlock) Copy() *MsgBlock {
  50  	block := &MsgBlock{
  51  		Header:       msg.Header,
  52  		Transactions: make([]*MsgTx, len(msg.Transactions)),
  53  	}
  54  
  55  	for i, tx := range msg.Transactions {
  56  		block.Transactions[i] = tx.Copy()
  57  	}
  58  
  59  	return block
  60  }
  61  
  62  // AddTransaction adds a transaction to the message.
  63  func (msg *MsgBlock) AddTransaction(tx *MsgTx) error {
  64  	msg.Transactions = append(msg.Transactions, tx)
  65  	return nil
  66  
  67  }
  68  
  69  // ClearTransactions removes all transactions from the message.
  70  func (msg *MsgBlock) ClearTransactions() {
  71  	msg.Transactions = make([]*MsgTx, 0, defaultTransactionAlloc)
  72  }
  73  
  74  // BtcDecode decodes r using the bitcoin protocol encoding into the receiver.
  75  // This is part of the Message interface implementation.
  76  // See Deserialize for decoding blocks stored to disk, such as in a database, as
  77  // opposed to decoding blocks from the wire.
  78  func (msg *MsgBlock) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) error {
  79  	buf := binarySerializer.Borrow()
  80  	defer binarySerializer.Return(buf)
  81  
  82  	err := readBlockHeaderBuf(r, pver, &msg.Header, buf)
  83  	if err != nil {
  84  		return err
  85  	}
  86  
  87  	txCount, err := ReadVarIntBuf(r, pver, buf)
  88  	if err != nil {
  89  		return err
  90  	}
  91  
  92  	// Prevent more transactions than could possibly fit into a block.
  93  	// It would be possible to cause memory exhaustion and panics without
  94  	// a sane upper bound on this count.
  95  	if txCount > maxTxPerBlock {
  96  		str := fmt.Sprintf("too many transactions to fit into a block "+
  97  			"[count %d, max %d]", txCount, maxTxPerBlock)
  98  		return messageError("MsgBlock.BtcDecode", str)
  99  	}
 100  	if err := validateElementCount(
 101  		r, txCount, minTxPayload,
 102  	); err != nil {
 103  		return err
 104  	}
 105  
 106  	// A single arena is shared by every transaction in the block.  Each
 107  	// transaction's btcDecode rewinds it, which is safe because the
 108  	// scripts are copied into their final exactly-sized buffer before the
 109  	// next transaction is decoded.
 110  	ar := borrowScriptArena()
 111  	defer ar.release()
 112  
 113  	msg.Transactions = make([]*MsgTx, 0, txCount)
 114  	for i := uint64(0); i < txCount; i++ {
 115  		tx := MsgTx{}
 116  		err := tx.btcDecode(r, pver, enc, buf, ar)
 117  		if err != nil {
 118  			return err
 119  		}
 120  		msg.Transactions = append(msg.Transactions, &tx)
 121  	}
 122  
 123  	return nil
 124  }
 125  
 126  // Deserialize decodes a block from r into the receiver using a format that is
 127  // suitable for long-term storage such as a database while respecting the
 128  // Version field in the block.  This function differs from BtcDecode in that
 129  // BtcDecode decodes from the bitcoin wire protocol as it was sent across the
 130  // network.  The wire encoding can technically differ depending on the protocol
 131  // version and doesn't even really need to match the format of a stored block at
 132  // all.  As of the time this comment was written, the encoded block is the same
 133  // in both instances, but there is a distinct difference and separating the two
 134  // allows the API to be flexible enough to deal with changes.
 135  func (msg *MsgBlock) Deserialize(r io.Reader) error {
 136  	// At the current time, there is no difference between the wire encoding
 137  	// at protocol version 0 and the stable long-term storage format.  As
 138  	// a result, make use of BtcDecode.
 139  	//
 140  	// Passing an encoding type of WitnessEncoding to BtcEncode for the
 141  	// MessageEncoding parameter indicates that the transactions within the
 142  	// block are expected to be serialized according to the new
 143  	// serialization structure defined in BIP0141.
 144  	return msg.BtcDecode(r, 0, WitnessEncoding)
 145  }
 146  
 147  // DeserializeNoWitness decodes a block from r into the receiver similar to
 148  // Deserialize, however DeserializeWitness strips all (if any) witness data
 149  // from the transactions within the block before encoding them.
 150  func (msg *MsgBlock) DeserializeNoWitness(r io.Reader) error {
 151  	return msg.BtcDecode(r, 0, BaseEncoding)
 152  }
 153  
 154  // DeserializeTxLoc decodes r in the same manner Deserialize does, but it takes
 155  // a byte buffer instead of a generic reader and returns a slice containing the
 156  // start and length of each transaction within the raw data that is being
 157  // deserialized.
 158  func (msg *MsgBlock) DeserializeTxLoc(r *bytes.Buffer) ([]TxLoc, error) {
 159  	fullLen := r.Len()
 160  
 161  	buf := binarySerializer.Borrow()
 162  	defer binarySerializer.Return(buf)
 163  
 164  	// At the current time, there is no difference between the wire encoding
 165  	// at protocol version 0 and the stable long-term storage format.  As
 166  	// a result, make use of existing wire protocol functions.
 167  	err := readBlockHeaderBuf(r, 0, &msg.Header, buf)
 168  	if err != nil {
 169  		return nil, err
 170  	}
 171  
 172  	txCount, err := ReadVarIntBuf(r, 0, buf)
 173  	if err != nil {
 174  		return nil, err
 175  	}
 176  
 177  	// Prevent more transactions than could possibly fit into a block.
 178  	// It would be possible to cause memory exhaustion and panics without
 179  	// a sane upper bound on this count.
 180  	if txCount > maxTxPerBlock {
 181  		str := fmt.Sprintf("too many transactions to fit into a block "+
 182  			"[count %d, max %d]", txCount, maxTxPerBlock)
 183  		return nil, messageError("MsgBlock.DeserializeTxLoc", str)
 184  	}
 185  	if err := validateElementCount(
 186  		r, txCount, minTxPayload,
 187  	); err != nil {
 188  		return nil, err
 189  	}
 190  
 191  	ar := borrowScriptArena()
 192  	defer ar.release()
 193  
 194  	// Deserialize each transaction while keeping track of its location
 195  	// within the byte stream.
 196  	msg.Transactions = make([]*MsgTx, 0, txCount)
 197  	txLocs := make([]TxLoc, txCount)
 198  	for i := uint64(0); i < txCount; i++ {
 199  		txLocs[i].TxStart = fullLen - r.Len()
 200  		tx := MsgTx{}
 201  		err := tx.btcDecode(r, 0, WitnessEncoding, buf, ar)
 202  		if err != nil {
 203  			return nil, err
 204  		}
 205  		msg.Transactions = append(msg.Transactions, &tx)
 206  		txLocs[i].TxLen = (fullLen - r.Len()) - txLocs[i].TxStart
 207  	}
 208  
 209  	return txLocs, nil
 210  }
 211  
 212  // BtcEncode encodes the receiver to w using the bitcoin protocol encoding.
 213  // This is part of the Message interface implementation.
 214  // See Serialize for encoding blocks to be stored to disk, such as in a
 215  // database, as opposed to encoding blocks for the wire.
 216  func (msg *MsgBlock) BtcEncode(w io.Writer, pver uint32, enc MessageEncoding) error {
 217  	buf := binarySerializer.Borrow()
 218  	defer binarySerializer.Return(buf)
 219  
 220  	err := writeBlockHeaderBuf(w, pver, &msg.Header, buf)
 221  	if err != nil {
 222  		return err
 223  	}
 224  
 225  	err = WriteVarIntBuf(w, pver, uint64(len(msg.Transactions)), buf)
 226  	if err != nil {
 227  		return err
 228  	}
 229  
 230  	for _, tx := range msg.Transactions {
 231  		err = tx.btcEncode(w, pver, enc, buf)
 232  		if err != nil {
 233  			return err
 234  		}
 235  	}
 236  
 237  	return nil
 238  }
 239  
 240  // Serialize encodes the block to w using a format that suitable for long-term
 241  // storage such as a database while respecting the Version field in the block.
 242  // This function differs from BtcEncode in that BtcEncode encodes the block to
 243  // the bitcoin wire protocol in order to be sent across the network.  The wire
 244  // encoding can technically differ depending on the protocol version and doesn't
 245  // even really need to match the format of a stored block at all.  As of the
 246  // time this comment was written, the encoded block is the same in both
 247  // instances, but there is a distinct difference and separating the two allows
 248  // the API to be flexible enough to deal with changes.
 249  func (msg *MsgBlock) Serialize(w io.Writer) error {
 250  	// At the current time, there is no difference between the wire encoding
 251  	// at protocol version 0 and the stable long-term storage format.  As
 252  	// a result, make use of BtcEncode.
 253  	//
 254  	// Passing WitnessEncoding as the encoding type here indicates that
 255  	// each of the transactions should be serialized using the witness
 256  	// serialization structure defined in BIP0141.
 257  	return msg.BtcEncode(w, 0, WitnessEncoding)
 258  }
 259  
 260  // SerializeNoWitness encodes a block to w using an identical format to
 261  // Serialize, with all (if any) witness data stripped from all transactions.
 262  // This method is provided in addition to the regular Serialize, in order to
 263  // allow one to selectively encode transaction witness data to non-upgraded
 264  // peers which are unaware of the new encoding.
 265  func (msg *MsgBlock) SerializeNoWitness(w io.Writer) error {
 266  	return msg.BtcEncode(w, 0, BaseEncoding)
 267  }
 268  
 269  // SerializeSize returns the number of bytes it would take to serialize the
 270  // block, factoring in any witness data within transaction.
 271  func (msg *MsgBlock) SerializeSize() int {
 272  	// Block header bytes + Serialized varint size for the number of
 273  	// transactions.
 274  	n := blockHeaderLen + VarIntSerializeSize(uint64(len(msg.Transactions)))
 275  
 276  	for _, tx := range msg.Transactions {
 277  		n += tx.SerializeSize()
 278  	}
 279  
 280  	return n
 281  }
 282  
 283  // SerializeSizeStripped returns the number of bytes it would take to serialize
 284  // the block, excluding any witness data (if any).
 285  func (msg *MsgBlock) SerializeSizeStripped() int {
 286  	// Block header bytes + Serialized varint size for the number of
 287  	// transactions.
 288  	n := blockHeaderLen + VarIntSerializeSize(uint64(len(msg.Transactions)))
 289  
 290  	for _, tx := range msg.Transactions {
 291  		n += tx.SerializeSizeStripped()
 292  	}
 293  
 294  	return n
 295  }
 296  
 297  // Command returns the protocol command string for the message.  This is part
 298  // of the Message interface implementation.
 299  func (msg *MsgBlock) Command() string {
 300  	return CmdBlock
 301  }
 302  
 303  // MaxPayloadLength returns the maximum length the payload can be for the
 304  // receiver.  This is part of the Message interface implementation.
 305  func (msg *MsgBlock) MaxPayloadLength(pver uint32) uint32 {
 306  	// Block header at 80 bytes + transaction count + max transactions
 307  	// which can vary up to the MaxBlockPayload (including the block header
 308  	// and transaction count).
 309  	return MaxBlockPayload
 310  }
 311  
 312  // BlockHash computes the block identifier hash for this block.
 313  func (msg *MsgBlock) BlockHash() chainhash.Hash {
 314  	return msg.Header.BlockHash()
 315  }
 316  
 317  // TxHashes returns a slice of hashes of all of transactions in this block.
 318  func (msg *MsgBlock) TxHashes() ([]chainhash.Hash, error) {
 319  	hashList := make([]chainhash.Hash, 0, len(msg.Transactions))
 320  	for _, tx := range msg.Transactions {
 321  		hashList = append(hashList, tx.TxHash())
 322  	}
 323  	return hashList, nil
 324  }
 325  
 326  // NewMsgBlock returns a new bitcoin block message that conforms to the
 327  // Message interface.  See MsgBlock for details.
 328  func NewMsgBlock(blockHeader *BlockHeader) *MsgBlock {
 329  	return &MsgBlock{
 330  		Header:       *blockHeader,
 331  		Transactions: make([]*MsgTx, 0, defaultTransactionAlloc),
 332  	}
 333  }
 334