// Package wire parses the block and transaction encoding both chains share. // // It is not a copy of btcd's wire package. It takes the shape of that package's // transaction and block decoders and the constraints that matter for a body // that has to be hashed and turned into a BIP158 filter: the 1 MB block ceiling, // a coinbase with one input and a null outpoint, and a transaction stream that // consumes the block exactly. It does not carry btcd's script engine, its // policy checks or its error taxonomy, because none of those is needed to // reproduce a merkle root or a filter. // // The fork's version 2 header adds 84 bytes after the 80, and its proof-of-work // hash is not double SHA-256 of those bytes. The construction is nostrino's, // and a fork block's hash is asked of it through the btcwire header type, so // there is one implementation of the fork's hash rule. package wire import ( "encoding/binary" "errors" "fmt" "git.smesh.lol/nostrino/pkg/btcwire" "git.smesh.lol/nostrino/pkg/crypto/chainhash" ) const ( // MaxBlockPayload is the consensus ceiling on a serialized block, // including its header. MaxBlockPayload = 4_000_000 // MaxTxPayload bounds one transaction inside a block. No consensus rule // makes a single transaction larger than the weight limit allows. MaxTxPayload = 4_000_000 // HashSize is the length of a txid or a block hash. HashSize = 32 // MaxScriptSize is the largest script a transaction may carry. MaxScriptSize = 10_000 // Witness marker and flag bytes. witnessMarker = 0x00 witnessFlag = 0x01 // nullOutpointIndex marks a coinbase input. nullOutpointIndex = 0xffffffff ) var ( // ErrShort is a truncated stream. ErrShort = errors.New("wire: truncated data") // ErrBlockTooBig is a block over the ceiling. ErrBlockTooBig = errors.New("wire: block exceeds the size ceiling") // ErrTxTooBig is a transaction over the ceiling. ErrTxTooBig = errors.New("wire: transaction exceeds the size ceiling") // ErrNoTx is a block with no transactions. ErrNoTx = errors.New("wire: block has no transactions") // ErrTrailing is a block with bytes after its last transaction. ErrTrailing = errors.New("wire: bytes after the last transaction") // ErrBadCoinbase is a first transaction that is not a coinbase. ErrBadCoinbase = errors.New("wire: first transaction is not a coinbase") // ErrBadTxIn is a transaction with no inputs. ErrBadTxIn = errors.New("wire: transaction has no inputs") // ErrBadScript is a script over its ceiling. ErrBadScript = errors.New("wire: script exceeds its size ceiling") ) // OutPoint names an output of a transaction. type OutPoint struct { Hash chainhash.Hash Index uint32 } // IsNull reports whether the outpoint is the coinbase's null outpoint. func (o OutPoint) IsNull() bool { return o.Index == nullOutpointIndex && o.Hash == (chainhash.Hash{}) } // String renders the outpoint the way bitcoin-cli does, txid:vout. func (o OutPoint) String() string { return fmt.Sprintf("%s:%d", o.Hash.String(), o.Index) } // TxIn is one input. The witness is kept because a txid must be computed over // the non-witness serialization. type TxIn struct { PreviousOutPoint OutPoint SignatureScript []byte Sequence uint32 Witness [][]byte } // TxOut is one output. type TxOut struct { Value int64 PkScript []byte } // Tx is a parsed transaction. type Tx struct { Version int32 TxIn []TxIn TxOut []TxOut LockTime uint32 // HasWitness records whether the wire form carried the segwit marker. HasWitness bool } // IsCoinBase reports whether the transaction has exactly one input spending // the null outpoint. func (t *Tx) IsCoinBase() bool { return len(t.TxIn) == 1 && t.TxIn[0].PreviousOutPoint.IsNull() } // TxID is the hash of the transaction without its witness, in internal byte // order. It is what a block's merkle root commits to. func (t *Tx) TxID() chainhash.Hash { // The non-witness form differs from what was read only by the absence of // the marker, flag and witnesses, so it is re-serialized rather than // re-read. return chainhash.DoubleHashH(t.SerializeNoWitness()) } // SerializeNoWitness encodes the transaction without marker, flag or witnesses. // A transaction that carried no witness is encoded exactly as it was read. func (t *Tx) SerializeNoWitness() []byte { n := 4 + compactSizeLen(uint64(len(t.TxIn))) + 4 for _, in := range t.TxIn { n += HashSize + 4 + compactSizeLen(uint64(len(in.SignatureScript))) + len(in.SignatureScript) + 4 } n += compactSizeLen(uint64(len(t.TxOut))) for _, out := range t.TxOut { n += 8 + compactSizeLen(uint64(len(out.PkScript))) + len(out.PkScript) } n += 4 buf := make([]byte, 0, n) buf = binary.LittleEndian.AppendUint32(buf, uint32(t.Version)) buf = appendCompactSize(buf, uint64(len(t.TxIn))) for _, in := range t.TxIn { buf = append(buf, in.PreviousOutPoint.Hash[:]...) buf = binary.LittleEndian.AppendUint32(buf, in.PreviousOutPoint.Index) buf = appendCompactSize(buf, uint64(len(in.SignatureScript))) buf = append(buf, in.SignatureScript...) buf = binary.LittleEndian.AppendUint32(buf, in.Sequence) } buf = appendCompactSize(buf, uint64(len(t.TxOut))) for _, out := range t.TxOut { buf = binary.LittleEndian.AppendUint64(buf, uint64(out.Value)) buf = appendCompactSize(buf, uint64(len(out.PkScript))) buf = append(buf, out.PkScript...) } buf = binary.LittleEndian.AppendUint32(buf, t.LockTime) return buf } // Block is a parsed block: its header bytes and its transactions. type Block struct { // Header is the first 80 header bytes: version, prev, merkle root, time, // bits, nonce. On XBT a version 2 header appends 84 bytes after it; they // are in V2 and they are part of what the block hash commits to. Header [80]byte // V2 holds the fork's extra header fields when the header carries the // version 2 flag. It is nil for a Bitcoin-format header. V2 *btcwire.HeaderV2 // Txs are the parsed transactions in order. Txs []Tx // Size is the number of bytes the block occupied on the wire. Size int } // HeaderLen is the 80 bytes of a Bitcoin header, or 164 for a fork header. func (b *Block) HeaderLen() int { if b.V2 != nil { return btcwire.BlockHeaderV2Size } return 80 } // BlockHash is the header's proof-of-work hash: double SHA-256 for a Bitcoin // header, the fork's construction for a version 2 one. func (b *Block) BlockHash() chainhash.Hash { if b.V2 != nil { return b.headerProto().BlockHash() } return chainhash.DoubleHashH(b.Header[:]) } // headerProto is the btcwire header form, which is where the fork's hash // construction lives. There is one implementation of it, in nostrino, and this // is the call into it. func (b *Block) headerProto() *btcwire.BlockHeader { h := &btcwire.BlockHeader{} _ = h.Deserialize(b.Header[:]) h.V2 = b.V2 return h } // HeaderMerkleRoot is the merkle root field of the header, bytes 36..68. It is // at the same offset for both header forms. func (b *Block) HeaderMerkleRoot() chainhash.Hash { var h chainhash.Hash copy(h[:], b.Header[36:68]) return h } // MerkleRoot is the root the transactions' txids produce. A one-transaction // block's root is that txid. func (b *Block) MerkleRoot() chainhash.Hash { ids := make([]chainhash.Hash, len(b.Txs)) for i := range b.Txs { ids[i] = b.Txs[i].TxID() } return MerkleRoot(ids) } // MerkleRoot computes a Bitcoin merkle root over leaf hashes in internal byte // order, duplicating the last hash at each odd level. func MerkleRoot(leaves []chainhash.Hash) chainhash.Hash { if len(leaves) == 0 { return chainhash.Hash{} } level := append([]chainhash.Hash(nil), leaves...) buf := make([]byte, 0, 64) for len(level) > 1 { next := make([]chainhash.Hash, 0, (len(level)+1)/2) for i := 0; i < len(level); i += 2 { right := level[i] if i+1 < len(level) { right = level[i+1] } buf = append(buf[:0], level[i][:]...) buf = append(buf, right[:]...) next = append(next, chainhash.DoubleHashH(buf)) } level = next } return level[0] } // ParseBlock decodes one block and checks the invariants that make it a block: // it fits the ceiling, it has a coinbase first, it has transactions, it ends // exactly at its last transaction, and its transactions' txids produce its // header's merkle root. // // The byte ceiling is checked against the declared length of raw, so a caller // that has already bounded raw does not pay for it twice. func ParseBlock(raw []byte) (*Block, error) { if len(raw) > MaxBlockPayload { return nil, fmt.Errorf("%w: %d bytes", ErrBlockTooBig, len(raw)) } if len(raw) < 80 { return nil, ErrShort } d := &decoder{buf: raw} block := &Block{Size: len(raw)} copy(block.Header[:], raw[:80]) d.pos = 80 // A fork block carries a 164-byte header whose last 84 bytes are mining // fields committed to by the block hash. The flag is in the version word. if binary.LittleEndian.Uint32(raw[:4])&btcwire.HeaderV2Flag != 0 { if len(raw) < btcwire.BlockHeaderV2Size { return nil, ErrShort } var proto btcwire.BlockHeader if err := proto.DeserializeV2(raw[:btcwire.BlockHeaderV2Size]); err != nil { return nil, fmt.Errorf("wire: fork header: %w", err) } block.V2 = proto.V2 d.pos = btcwire.BlockHeaderV2Size } // The transaction count is read but not trusted as a bound: the stream, // not the count, decides when the block ends. A count that disagrees is // caught by the trailing-bytes check after the stream is consumed as far // as the count says. count, err := d.compactSize() if err != nil { return nil, err } if count == 0 { return nil, ErrNoTx } // A transaction costs at least 60 bytes on the wire, so a count above the // bytes available is refused before anything is allocated for it. if count > uint64(len(raw)) { return nil, fmt.Errorf("wire: %d transactions cannot fit in %d bytes", count, len(raw)) } block.Txs = make([]Tx, 0, int(count)) for i := uint64(0); i < count; i++ { tx, err := d.tx() if err != nil { return nil, fmt.Errorf("wire: transaction %d: %w", i, err) } block.Txs = append(block.Txs, *tx) } if d.pos != len(raw) { return nil, fmt.Errorf("%w: %d", ErrTrailing, len(raw)-d.pos) } if !block.Txs[0].IsCoinBase() { return nil, ErrBadCoinbase } if root := block.MerkleRoot(); root != block.HeaderMerkleRoot() { return nil, fmt.Errorf("wire: merkle root %s does not match header %s", root, block.HeaderMerkleRoot()) } return block, nil } // ParseTx decodes one standalone transaction, as a client submitting to the // relay sends it. It accepts all of raw or nothing. func ParseTx(raw []byte) (*Tx, error) { if len(raw) > MaxTxPayload { return nil, fmt.Errorf("%w: %d bytes", ErrTxTooBig, len(raw)) } d := &decoder{buf: raw} tx, err := d.tx() if err != nil { return nil, err } if d.pos != len(raw) { return nil, fmt.Errorf("%w: %d", ErrTrailing, len(raw)-d.pos) } return tx, nil } // decoder is a bounds-checked cursor over one buffer. type decoder struct { buf []byte pos int } func (d *decoder) take(n int) ([]byte, error) { if n < 0 || d.pos+n > len(d.buf) || n > len(d.buf) { return nil, ErrShort } b := d.buf[d.pos : d.pos+n] d.pos += n return b, nil } func (d *decoder) u8() (byte, error) { b, err := d.take(1) if err != nil { return 0, err } return b[0], nil } func (d *decoder) u16() (uint16, error) { b, err := d.take(2) if err != nil { return 0, err } return binary.LittleEndian.Uint16(b), nil } func (d *decoder) u32() (uint32, error) { b, err := d.take(4) if err != nil { return 0, err } return binary.LittleEndian.Uint32(b), nil } func (d *decoder) u64() (uint64, error) { b, err := d.take(8) if err != nil { return 0, err } return binary.LittleEndian.Uint64(b), nil } func (d *decoder) hash() (chainhash.Hash, error) { b, err := d.take(HashSize) if err != nil { return chainhash.Hash{}, err } var h chainhash.Hash copy(h[:], b) return h, nil } // compactSize reads a CompactSize, refusing a non-canonical encoding. func (d *decoder) compactSize() (uint64, error) { first, err := d.u8() if err != nil { return 0, err } switch first { case 0xfd: v, err := d.u16() if err != nil { return 0, err } if v < 0xfd { return 0, fmt.Errorf("wire: non-canonical compact size %d", v) } return uint64(v), nil case 0xfe: v, err := d.u32() if err != nil { return 0, err } if v < 0x10000 { return 0, fmt.Errorf("wire: non-canonical compact size %d", v) } return uint64(v), nil case 0xff: v, err := d.u64() if err != nil { return 0, err } if v < 0x100000000 { return 0, fmt.Errorf("wire: non-canonical compact size %d", v) } return v, nil default: return uint64(first), nil } } // bytes reads a CompactSize-prefixed byte string whose length is capped. func (d *decoder) bytes(max int) ([]byte, error) { n, err := d.compactSize() if err != nil { return nil, err } if n > uint64(max) { return nil, fmt.Errorf("%w: %d > %d", ErrBadScript, n, max) } b, err := d.take(int(n)) if err != nil { return nil, err } return b, nil } // tx decodes one transaction and applies the structural rules a filter builder // and a relay need: at least one input and one output, and scripts inside their // ceiling. func (d *decoder) tx() (*Tx, error) { version, err := d.u32() if err != nil { return nil, err } tx := &Tx{Version: int32(version)} inCount, err := d.compactSize() if err != nil { return nil, err } // Segwit: a zero input count is the marker, and the next byte must be the // flag. Bitcoin Core reads it this way and so does every parser that must // agree with Core about txids. if inCount == 0 { flag, err := d.u8() if err != nil { return nil, err } if flag != witnessFlag { return nil, ErrBadTxIn } tx.HasWitness = true inCount, err = d.compactSize() if err != nil { return nil, err } } if inCount == 0 || inCount > uint64(len(d.buf)) { return nil, ErrBadTxIn } tx.TxIn = make([]TxIn, inCount) for i := range tx.TxIn { h, err := d.hash() if err != nil { return nil, err } index, err := d.u32() if err != nil { return nil, err } script, err := d.bytes(MaxScriptSize) if err != nil { return nil, err } seq, err := d.u32() if err != nil { return nil, err } tx.TxIn[i] = TxIn{ PreviousOutPoint: OutPoint{Hash: h, Index: index}, SignatureScript: script, Sequence: seq, } } outCount, err := d.compactSize() if err != nil { return nil, err } if outCount > uint64(len(d.buf)) { return nil, ErrShort } tx.TxOut = make([]TxOut, outCount) for i := range tx.TxOut { value, err := d.u64() if err != nil { return nil, err } script, err := d.bytes(MaxScriptSize) if err != nil { return nil, err } tx.TxOut[i] = TxOut{Value: int64(value), PkScript: script} } if tx.HasWitness { for i := range tx.TxIn { n, err := d.compactSize() if err != nil { return nil, err } if n > uint64(len(d.buf)) { return nil, ErrShort } witness := make([][]byte, n) for j := range witness { item, err := d.bytes(MaxScriptSize * 520) if err != nil { return nil, err } witness[j] = item } tx.TxIn[i].Witness = witness } } lockTime, err := d.u32() if err != nil { return nil, err } tx.LockTime = lockTime return tx, nil } func compactSizeLen(n uint64) int { switch { case n < 0xfd: return 1 case n <= 0xffff: return 3 case n <= 0xffffffff: return 5 default: return 9 } } func appendCompactSize(buf []byte, n uint64) []byte { switch { case n < 0xfd: return append(buf, byte(n)) case n <= 0xffff: buf = append(buf, 0xfd) return binary.LittleEndian.AppendUint16(buf, uint16(n)) case n <= 0xffffffff: buf = append(buf, 0xfe) return binary.LittleEndian.AppendUint32(buf, uint32(n)) default: buf = append(buf, 0xff) return binary.LittleEndian.AppendUint64(buf, n) } }