block.go raw

   1  // Package wire parses the block and transaction encoding both chains share.
   2  //
   3  // It is not a copy of btcd's wire package. It takes the shape of that package's
   4  // transaction and block decoders and the constraints that matter for a body
   5  // that has to be hashed and turned into a BIP158 filter: the 1 MB block ceiling,
   6  // a coinbase with one input and a null outpoint, and a transaction stream that
   7  // consumes the block exactly. It does not carry btcd's script engine, its
   8  // policy checks or its error taxonomy, because none of those is needed to
   9  // reproduce a merkle root or a filter.
  10  //
  11  // The fork's version 2 header adds 84 bytes after the 80, and its proof-of-work
  12  // hash is not double SHA-256 of those bytes. The construction is nostrino's,
  13  // and a fork block's hash is asked of it through the btcwire header type, so
  14  // there is one implementation of the fork's hash rule.
  15  package wire
  16  
  17  import (
  18  	"encoding/binary"
  19  	"errors"
  20  	"fmt"
  21  
  22  	"git.smesh.lol/nostrino/pkg/btcwire"
  23  	"git.smesh.lol/nostrino/pkg/crypto/chainhash"
  24  )
  25  
  26  const (
  27  	// MaxBlockPayload is the consensus ceiling on a serialized block,
  28  	// including its header.
  29  	MaxBlockPayload = 4_000_000
  30  	// MaxTxPayload bounds one transaction inside a block. No consensus rule
  31  	// makes a single transaction larger than the weight limit allows.
  32  	MaxTxPayload = 4_000_000
  33  	// HashSize is the length of a txid or a block hash.
  34  	HashSize = 32
  35  	// MaxScriptSize is the largest script a transaction may carry.
  36  	MaxScriptSize = 10_000
  37  	// Witness marker and flag bytes.
  38  	witnessMarker = 0x00
  39  	witnessFlag   = 0x01
  40  	// nullOutpointIndex marks a coinbase input.
  41  	nullOutpointIndex = 0xffffffff
  42  )
  43  
  44  var (
  45  	// ErrShort is a truncated stream.
  46  	ErrShort = errors.New("wire: truncated data")
  47  	// ErrBlockTooBig is a block over the ceiling.
  48  	ErrBlockTooBig = errors.New("wire: block exceeds the size ceiling")
  49  	// ErrTxTooBig is a transaction over the ceiling.
  50  	ErrTxTooBig = errors.New("wire: transaction exceeds the size ceiling")
  51  	// ErrNoTx is a block with no transactions.
  52  	ErrNoTx = errors.New("wire: block has no transactions")
  53  	// ErrTrailing is a block with bytes after its last transaction.
  54  	ErrTrailing = errors.New("wire: bytes after the last transaction")
  55  	// ErrBadCoinbase is a first transaction that is not a coinbase.
  56  	ErrBadCoinbase = errors.New("wire: first transaction is not a coinbase")
  57  	// ErrBadTxIn is a transaction with no inputs.
  58  	ErrBadTxIn = errors.New("wire: transaction has no inputs")
  59  	// ErrBadScript is a script over its ceiling.
  60  	ErrBadScript = errors.New("wire: script exceeds its size ceiling")
  61  )
  62  
  63  // OutPoint names an output of a transaction.
  64  type OutPoint struct {
  65  	Hash  chainhash.Hash
  66  	Index uint32
  67  }
  68  
  69  // IsNull reports whether the outpoint is the coinbase's null outpoint.
  70  func (o OutPoint) IsNull() bool {
  71  	return o.Index == nullOutpointIndex && o.Hash == (chainhash.Hash{})
  72  }
  73  
  74  // String renders the outpoint the way bitcoin-cli does, txid:vout.
  75  func (o OutPoint) String() string {
  76  	return fmt.Sprintf("%s:%d", o.Hash.String(), o.Index)
  77  }
  78  
  79  // TxIn is one input. The witness is kept because a txid must be computed over
  80  // the non-witness serialization.
  81  type TxIn struct {
  82  	PreviousOutPoint OutPoint
  83  	SignatureScript  []byte
  84  	Sequence         uint32
  85  	Witness          [][]byte
  86  }
  87  
  88  // TxOut is one output.
  89  type TxOut struct {
  90  	Value    int64
  91  	PkScript []byte
  92  }
  93  
  94  // Tx is a parsed transaction.
  95  type Tx struct {
  96  	Version  int32
  97  	TxIn     []TxIn
  98  	TxOut    []TxOut
  99  	LockTime uint32
 100  	// HasWitness records whether the wire form carried the segwit marker.
 101  	HasWitness bool
 102  }
 103  
 104  // IsCoinBase reports whether the transaction has exactly one input spending
 105  // the null outpoint.
 106  func (t *Tx) IsCoinBase() bool {
 107  	return len(t.TxIn) == 1 && t.TxIn[0].PreviousOutPoint.IsNull()
 108  }
 109  
 110  // TxID is the hash of the transaction without its witness, in internal byte
 111  // order. It is what a block's merkle root commits to.
 112  func (t *Tx) TxID() chainhash.Hash {
 113  	// The non-witness form differs from what was read only by the absence of
 114  	// the marker, flag and witnesses, so it is re-serialized rather than
 115  	// re-read.
 116  	return chainhash.DoubleHashH(t.SerializeNoWitness())
 117  }
 118  
 119  // SerializeNoWitness encodes the transaction without marker, flag or witnesses.
 120  // A transaction that carried no witness is encoded exactly as it was read.
 121  func (t *Tx) SerializeNoWitness() []byte {
 122  	n := 4 + compactSizeLen(uint64(len(t.TxIn))) + 4
 123  	for _, in := range t.TxIn {
 124  		n += HashSize + 4 + compactSizeLen(uint64(len(in.SignatureScript))) +
 125  			len(in.SignatureScript) + 4
 126  	}
 127  	n += compactSizeLen(uint64(len(t.TxOut)))
 128  	for _, out := range t.TxOut {
 129  		n += 8 + compactSizeLen(uint64(len(out.PkScript))) + len(out.PkScript)
 130  	}
 131  	n += 4
 132  	buf := make([]byte, 0, n)
 133  	buf = binary.LittleEndian.AppendUint32(buf, uint32(t.Version))
 134  	buf = appendCompactSize(buf, uint64(len(t.TxIn)))
 135  	for _, in := range t.TxIn {
 136  		buf = append(buf, in.PreviousOutPoint.Hash[:]...)
 137  		buf = binary.LittleEndian.AppendUint32(buf, in.PreviousOutPoint.Index)
 138  		buf = appendCompactSize(buf, uint64(len(in.SignatureScript)))
 139  		buf = append(buf, in.SignatureScript...)
 140  		buf = binary.LittleEndian.AppendUint32(buf, in.Sequence)
 141  	}
 142  	buf = appendCompactSize(buf, uint64(len(t.TxOut)))
 143  	for _, out := range t.TxOut {
 144  		buf = binary.LittleEndian.AppendUint64(buf, uint64(out.Value))
 145  		buf = appendCompactSize(buf, uint64(len(out.PkScript)))
 146  		buf = append(buf, out.PkScript...)
 147  	}
 148  	buf = binary.LittleEndian.AppendUint32(buf, t.LockTime)
 149  	return buf
 150  }
 151  
 152  // Block is a parsed block: its header bytes and its transactions.
 153  type Block struct {
 154  	// Header is the first 80 header bytes: version, prev, merkle root, time,
 155  	// bits, nonce. On XBT a version 2 header appends 84 bytes after it; they
 156  	// are in V2 and they are part of what the block hash commits to.
 157  	Header [80]byte
 158  	// V2 holds the fork's extra header fields when the header carries the
 159  	// version 2 flag. It is nil for a Bitcoin-format header.
 160  	V2 *btcwire.HeaderV2
 161  	// Txs are the parsed transactions in order.
 162  	Txs []Tx
 163  	// Size is the number of bytes the block occupied on the wire.
 164  	Size int
 165  }
 166  
 167  // HeaderLen is the 80 bytes of a Bitcoin header, or 164 for a fork header.
 168  func (b *Block) HeaderLen() int {
 169  	if b.V2 != nil {
 170  		return btcwire.BlockHeaderV2Size
 171  	}
 172  	return 80
 173  }
 174  
 175  // BlockHash is the header's proof-of-work hash: double SHA-256 for a Bitcoin
 176  // header, the fork's construction for a version 2 one.
 177  func (b *Block) BlockHash() chainhash.Hash {
 178  	if b.V2 != nil {
 179  		return b.headerProto().BlockHash()
 180  	}
 181  	return chainhash.DoubleHashH(b.Header[:])
 182  }
 183  
 184  // headerProto is the btcwire header form, which is where the fork's hash
 185  // construction lives. There is one implementation of it, in nostrino, and this
 186  // is the call into it.
 187  func (b *Block) headerProto() *btcwire.BlockHeader {
 188  	h := &btcwire.BlockHeader{}
 189  	_ = h.Deserialize(b.Header[:])
 190  	h.V2 = b.V2
 191  	return h
 192  }
 193  
 194  // HeaderMerkleRoot is the merkle root field of the header, bytes 36..68. It is
 195  // at the same offset for both header forms.
 196  func (b *Block) HeaderMerkleRoot() chainhash.Hash {
 197  	var h chainhash.Hash
 198  	copy(h[:], b.Header[36:68])
 199  	return h
 200  }
 201  
 202  // MerkleRoot is the root the transactions' txids produce. A one-transaction
 203  // block's root is that txid.
 204  func (b *Block) MerkleRoot() chainhash.Hash {
 205  	ids := make([]chainhash.Hash, len(b.Txs))
 206  	for i := range b.Txs {
 207  		ids[i] = b.Txs[i].TxID()
 208  	}
 209  	return MerkleRoot(ids)
 210  }
 211  
 212  // MerkleRoot computes a Bitcoin merkle root over leaf hashes in internal byte
 213  // order, duplicating the last hash at each odd level.
 214  func MerkleRoot(leaves []chainhash.Hash) chainhash.Hash {
 215  	if len(leaves) == 0 {
 216  		return chainhash.Hash{}
 217  	}
 218  	level := append([]chainhash.Hash(nil), leaves...)
 219  	buf := make([]byte, 0, 64)
 220  	for len(level) > 1 {
 221  		next := make([]chainhash.Hash, 0, (len(level)+1)/2)
 222  		for i := 0; i < len(level); i += 2 {
 223  			right := level[i]
 224  			if i+1 < len(level) {
 225  				right = level[i+1]
 226  			}
 227  			buf = append(buf[:0], level[i][:]...)
 228  			buf = append(buf, right[:]...)
 229  			next = append(next, chainhash.DoubleHashH(buf))
 230  		}
 231  		level = next
 232  	}
 233  	return level[0]
 234  }
 235  
 236  // ParseBlock decodes one block and checks the invariants that make it a block:
 237  // it fits the ceiling, it has a coinbase first, it has transactions, it ends
 238  // exactly at its last transaction, and its transactions' txids produce its
 239  // header's merkle root.
 240  //
 241  // The byte ceiling is checked against the declared length of raw, so a caller
 242  // that has already bounded raw does not pay for it twice.
 243  func ParseBlock(raw []byte) (*Block, error) {
 244  	if len(raw) > MaxBlockPayload {
 245  		return nil, fmt.Errorf("%w: %d bytes", ErrBlockTooBig, len(raw))
 246  	}
 247  	if len(raw) < 80 {
 248  		return nil, ErrShort
 249  	}
 250  	d := &decoder{buf: raw}
 251  	block := &Block{Size: len(raw)}
 252  	copy(block.Header[:], raw[:80])
 253  	d.pos = 80
 254  	// A fork block carries a 164-byte header whose last 84 bytes are mining
 255  	// fields committed to by the block hash. The flag is in the version word.
 256  	if binary.LittleEndian.Uint32(raw[:4])&btcwire.HeaderV2Flag != 0 {
 257  		if len(raw) < btcwire.BlockHeaderV2Size {
 258  			return nil, ErrShort
 259  		}
 260  		var proto btcwire.BlockHeader
 261  		if err := proto.DeserializeV2(raw[:btcwire.BlockHeaderV2Size]); err != nil {
 262  			return nil, fmt.Errorf("wire: fork header: %w", err)
 263  		}
 264  		block.V2 = proto.V2
 265  		d.pos = btcwire.BlockHeaderV2Size
 266  	}
 267  
 268  	// The transaction count is read but not trusted as a bound: the stream,
 269  	// not the count, decides when the block ends. A count that disagrees is
 270  	// caught by the trailing-bytes check after the stream is consumed as far
 271  	// as the count says.
 272  	count, err := d.compactSize()
 273  	if err != nil {
 274  		return nil, err
 275  	}
 276  	if count == 0 {
 277  		return nil, ErrNoTx
 278  	}
 279  	// A transaction costs at least 60 bytes on the wire, so a count above the
 280  	// bytes available is refused before anything is allocated for it.
 281  	if count > uint64(len(raw)) {
 282  		return nil, fmt.Errorf("wire: %d transactions cannot fit in %d bytes", count, len(raw))
 283  	}
 284  	block.Txs = make([]Tx, 0, int(count))
 285  	for i := uint64(0); i < count; i++ {
 286  		tx, err := d.tx()
 287  		if err != nil {
 288  			return nil, fmt.Errorf("wire: transaction %d: %w", i, err)
 289  		}
 290  		block.Txs = append(block.Txs, *tx)
 291  	}
 292  	if d.pos != len(raw) {
 293  		return nil, fmt.Errorf("%w: %d", ErrTrailing, len(raw)-d.pos)
 294  	}
 295  	if !block.Txs[0].IsCoinBase() {
 296  		return nil, ErrBadCoinbase
 297  	}
 298  	if root := block.MerkleRoot(); root != block.HeaderMerkleRoot() {
 299  		return nil, fmt.Errorf("wire: merkle root %s does not match header %s",
 300  			root, block.HeaderMerkleRoot())
 301  	}
 302  	return block, nil
 303  }
 304  
 305  // ParseTx decodes one standalone transaction, as a client submitting to the
 306  // relay sends it. It accepts all of raw or nothing.
 307  func ParseTx(raw []byte) (*Tx, error) {
 308  	if len(raw) > MaxTxPayload {
 309  		return nil, fmt.Errorf("%w: %d bytes", ErrTxTooBig, len(raw))
 310  	}
 311  	d := &decoder{buf: raw}
 312  	tx, err := d.tx()
 313  	if err != nil {
 314  		return nil, err
 315  	}
 316  	if d.pos != len(raw) {
 317  		return nil, fmt.Errorf("%w: %d", ErrTrailing, len(raw)-d.pos)
 318  	}
 319  	return tx, nil
 320  }
 321  
 322  // decoder is a bounds-checked cursor over one buffer.
 323  type decoder struct {
 324  	buf []byte
 325  	pos int
 326  }
 327  
 328  func (d *decoder) take(n int) ([]byte, error) {
 329  	if n < 0 || d.pos+n > len(d.buf) || n > len(d.buf) {
 330  		return nil, ErrShort
 331  	}
 332  	b := d.buf[d.pos : d.pos+n]
 333  	d.pos += n
 334  	return b, nil
 335  }
 336  
 337  func (d *decoder) u8() (byte, error) {
 338  	b, err := d.take(1)
 339  	if err != nil {
 340  		return 0, err
 341  	}
 342  	return b[0], nil
 343  }
 344  
 345  func (d *decoder) u16() (uint16, error) {
 346  	b, err := d.take(2)
 347  	if err != nil {
 348  		return 0, err
 349  	}
 350  	return binary.LittleEndian.Uint16(b), nil
 351  }
 352  
 353  func (d *decoder) u32() (uint32, error) {
 354  	b, err := d.take(4)
 355  	if err != nil {
 356  		return 0, err
 357  	}
 358  	return binary.LittleEndian.Uint32(b), nil
 359  }
 360  
 361  func (d *decoder) u64() (uint64, error) {
 362  	b, err := d.take(8)
 363  	if err != nil {
 364  		return 0, err
 365  	}
 366  	return binary.LittleEndian.Uint64(b), nil
 367  }
 368  
 369  func (d *decoder) hash() (chainhash.Hash, error) {
 370  	b, err := d.take(HashSize)
 371  	if err != nil {
 372  		return chainhash.Hash{}, err
 373  	}
 374  	var h chainhash.Hash
 375  	copy(h[:], b)
 376  	return h, nil
 377  }
 378  
 379  // compactSize reads a CompactSize, refusing a non-canonical encoding.
 380  func (d *decoder) compactSize() (uint64, error) {
 381  	first, err := d.u8()
 382  	if err != nil {
 383  		return 0, err
 384  	}
 385  	switch first {
 386  	case 0xfd:
 387  		v, err := d.u16()
 388  		if err != nil {
 389  			return 0, err
 390  		}
 391  		if v < 0xfd {
 392  			return 0, fmt.Errorf("wire: non-canonical compact size %d", v)
 393  		}
 394  		return uint64(v), nil
 395  	case 0xfe:
 396  		v, err := d.u32()
 397  		if err != nil {
 398  			return 0, err
 399  		}
 400  		if v < 0x10000 {
 401  			return 0, fmt.Errorf("wire: non-canonical compact size %d", v)
 402  		}
 403  		return uint64(v), nil
 404  	case 0xff:
 405  		v, err := d.u64()
 406  		if err != nil {
 407  			return 0, err
 408  		}
 409  		if v < 0x100000000 {
 410  			return 0, fmt.Errorf("wire: non-canonical compact size %d", v)
 411  		}
 412  		return v, nil
 413  	default:
 414  		return uint64(first), nil
 415  	}
 416  }
 417  
 418  // bytes reads a CompactSize-prefixed byte string whose length is capped.
 419  func (d *decoder) bytes(max int) ([]byte, error) {
 420  	n, err := d.compactSize()
 421  	if err != nil {
 422  		return nil, err
 423  	}
 424  	if n > uint64(max) {
 425  		return nil, fmt.Errorf("%w: %d > %d", ErrBadScript, n, max)
 426  	}
 427  	b, err := d.take(int(n))
 428  	if err != nil {
 429  		return nil, err
 430  	}
 431  	return b, nil
 432  }
 433  
 434  // tx decodes one transaction and applies the structural rules a filter builder
 435  // and a relay need: at least one input and one output, and scripts inside their
 436  // ceiling.
 437  func (d *decoder) tx() (*Tx, error) {
 438  	version, err := d.u32()
 439  	if err != nil {
 440  		return nil, err
 441  	}
 442  	tx := &Tx{Version: int32(version)}
 443  	inCount, err := d.compactSize()
 444  	if err != nil {
 445  		return nil, err
 446  	}
 447  	// Segwit: a zero input count is the marker, and the next byte must be the
 448  	// flag. Bitcoin Core reads it this way and so does every parser that must
 449  	// agree with Core about txids.
 450  	if inCount == 0 {
 451  		flag, err := d.u8()
 452  		if err != nil {
 453  			return nil, err
 454  		}
 455  		if flag != witnessFlag {
 456  			return nil, ErrBadTxIn
 457  		}
 458  		tx.HasWitness = true
 459  		inCount, err = d.compactSize()
 460  		if err != nil {
 461  			return nil, err
 462  		}
 463  	}
 464  	if inCount == 0 || inCount > uint64(len(d.buf)) {
 465  		return nil, ErrBadTxIn
 466  	}
 467  	tx.TxIn = make([]TxIn, inCount)
 468  	for i := range tx.TxIn {
 469  		h, err := d.hash()
 470  		if err != nil {
 471  			return nil, err
 472  		}
 473  		index, err := d.u32()
 474  		if err != nil {
 475  			return nil, err
 476  		}
 477  		script, err := d.bytes(MaxScriptSize)
 478  		if err != nil {
 479  			return nil, err
 480  		}
 481  		seq, err := d.u32()
 482  		if err != nil {
 483  			return nil, err
 484  		}
 485  		tx.TxIn[i] = TxIn{
 486  			PreviousOutPoint: OutPoint{Hash: h, Index: index},
 487  			SignatureScript:  script,
 488  			Sequence:         seq,
 489  		}
 490  	}
 491  	outCount, err := d.compactSize()
 492  	if err != nil {
 493  		return nil, err
 494  	}
 495  	if outCount > uint64(len(d.buf)) {
 496  		return nil, ErrShort
 497  	}
 498  	tx.TxOut = make([]TxOut, outCount)
 499  	for i := range tx.TxOut {
 500  		value, err := d.u64()
 501  		if err != nil {
 502  			return nil, err
 503  		}
 504  		script, err := d.bytes(MaxScriptSize)
 505  		if err != nil {
 506  			return nil, err
 507  		}
 508  		tx.TxOut[i] = TxOut{Value: int64(value), PkScript: script}
 509  	}
 510  	if tx.HasWitness {
 511  		for i := range tx.TxIn {
 512  			n, err := d.compactSize()
 513  			if err != nil {
 514  				return nil, err
 515  			}
 516  			if n > uint64(len(d.buf)) {
 517  				return nil, ErrShort
 518  			}
 519  			witness := make([][]byte, n)
 520  			for j := range witness {
 521  				item, err := d.bytes(MaxScriptSize * 520)
 522  				if err != nil {
 523  					return nil, err
 524  				}
 525  				witness[j] = item
 526  			}
 527  			tx.TxIn[i].Witness = witness
 528  		}
 529  	}
 530  	lockTime, err := d.u32()
 531  	if err != nil {
 532  		return nil, err
 533  	}
 534  	tx.LockTime = lockTime
 535  	return tx, nil
 536  }
 537  
 538  func compactSizeLen(n uint64) int {
 539  	switch {
 540  	case n < 0xfd:
 541  		return 1
 542  	case n <= 0xffff:
 543  		return 3
 544  	case n <= 0xffffffff:
 545  		return 5
 546  	default:
 547  		return 9
 548  	}
 549  }
 550  
 551  func appendCompactSize(buf []byte, n uint64) []byte {
 552  	switch {
 553  	case n < 0xfd:
 554  		return append(buf, byte(n))
 555  	case n <= 0xffff:
 556  		buf = append(buf, 0xfd)
 557  		return binary.LittleEndian.AppendUint16(buf, uint16(n))
 558  	case n <= 0xffffffff:
 559  		buf = append(buf, 0xfe)
 560  		return binary.LittleEndian.AppendUint32(buf, uint32(n))
 561  	default:
 562  		buf = append(buf, 0xff)
 563  		return binary.LittleEndian.AppendUint64(buf, n)
 564  	}
 565  }
 566