decode_budget_bench_test.go raw

   1  // Copyright (c) 2026 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  	"os"
  10  	"testing"
  11  )
  12  
  13  func benchmarkCountPayload(b *testing.B, prefix []byte, count uint64) []byte {
  14  	b.Helper()
  15  
  16  	var payload bytes.Buffer
  17  	if _, err := payload.Write(prefix); err != nil {
  18  		b.Fatalf("unable to write payload prefix: %v", err)
  19  	}
  20  	if err := WriteVarInt(&payload, ProtocolVersion, count); err != nil {
  21  		b.Fatalf("unable to write element count: %v", err)
  22  	}
  23  
  24  	return payload.Bytes()
  25  }
  26  
  27  func benchmarkCompleteStreamingMessage(b *testing.B, msg Message) {
  28  	b.Helper()
  29  
  30  	var encoded bytes.Buffer
  31  	_, err := WriteMessageWithEncodingN(
  32  		&encoded, msg, ProtocolVersion, MainNet, WitnessEncoding,
  33  	)
  34  	if err != nil {
  35  		b.Fatal(err)
  36  	}
  37  	payload := encoded.Bytes()
  38  
  39  	b.SetBytes(int64(len(payload)))
  40  	b.ReportAllocs()
  41  	b.ResetTimer()
  42  	for i := 0; i < b.N; i++ {
  43  		reader := &readSizeRecorder{
  44  			reader: bytes.NewReader(payload),
  45  		}
  46  		_, _, _, err := ReadMessageWithEncodingN(
  47  			reader, ProtocolVersion, MainNet, WitnessEncoding,
  48  		)
  49  		if err != nil {
  50  			b.Fatal(err)
  51  		}
  52  	}
  53  }
  54  
  55  // BenchmarkCompleteStreamingMessage measures complete framed messages read
  56  // from a reader that does not expose its remaining length.
  57  func BenchmarkCompleteStreamingMessage(b *testing.B) {
  58  	b.Run("ping", func(b *testing.B) {
  59  		benchmarkCompleteStreamingMessage(b, NewMsgPing(1))
  60  	})
  61  
  62  	blockBytes, err := os.ReadFile(
  63  		"testdata/block-00000000000000000021868c2cefc52a480d173c849412fe81c4e5ab806f94ab.blk",
  64  	)
  65  	if err != nil {
  66  		b.Fatal(err)
  67  	}
  68  	var block MsgBlock
  69  	if err := block.Deserialize(bytes.NewReader(blockBytes)); err != nil {
  70  		b.Fatal(err)
  71  	}
  72  	b.Run("block", func(b *testing.B) {
  73  		benchmarkCompleteStreamingMessage(b, &block)
  74  	})
  75  }
  76  
  77  // BenchmarkTruncatedDecodeBudget measures allocation when a length or element
  78  // count is present without the bytes needed to satisfy it.
  79  func BenchmarkTruncatedDecodeBudget(b *testing.B) {
  80  	b.Run("message_payload", func(b *testing.B) {
  81  		header := makeHeader(
  82  			MainNet, CmdBlock, MaxProtocolMessageLength, 0,
  83  		)
  84  
  85  		b.ReportAllocs()
  86  		b.ResetTimer()
  87  		for i := 0; i < b.N; i++ {
  88  			_, _, _, err := ReadMessageN(
  89  				bytes.NewReader(header), ProtocolVersion, MainNet,
  90  			)
  91  			if err == nil {
  92  				b.Fatal("expected a truncated payload error")
  93  			}
  94  		}
  95  	})
  96  
  97  	b.Run("variable_bytes", func(b *testing.B) {
  98  		payload := benchmarkCountPayload(
  99  			b, nil, MaxProtocolMessageLength,
 100  		)
 101  		payload = append(payload, 0x01)
 102  
 103  		b.ReportAllocs()
 104  		b.ResetTimer()
 105  		for i := 0; i < b.N; i++ {
 106  			_, err := ReadVarBytes(
 107  				bytes.NewReader(payload), ProtocolVersion,
 108  				MaxMessagePayload, "payload",
 109  			)
 110  			if err == nil {
 111  				b.Fatal("expected a truncated byte payload error")
 112  			}
 113  		}
 114  	})
 115  
 116  	b.Run("inventory", func(b *testing.B) {
 117  		payload := benchmarkCountPayload(b, nil, MaxInvPerMsg)
 118  
 119  		b.ReportAllocs()
 120  		b.ResetTimer()
 121  		for i := 0; i < b.N; i++ {
 122  			var msg MsgInv
 123  			err := msg.BtcDecode(
 124  				bytes.NewReader(payload), ProtocolVersion, BaseEncoding,
 125  			)
 126  			if err == nil {
 127  				b.Fatal("expected a truncated inventory error")
 128  			}
 129  		}
 130  	})
 131  
 132  	b.Run("merkle_hashes", func(b *testing.B) {
 133  		// The 80-byte block header followed by the 4-byte total transaction
 134  		// count are read by MsgMerkleBlock.BtcDecode before the hash count
 135  		// varint.
 136  		payload := benchmarkCountPayload(
 137  			b, make([]byte, MaxBlockHeaderPayload+4), maxTxPerBlock,
 138  		)
 139  
 140  		b.ReportAllocs()
 141  		b.ResetTimer()
 142  		for i := 0; i < b.N; i++ {
 143  			var msg MsgMerkleBlock
 144  			err := msg.BtcDecode(
 145  				bytes.NewReader(payload), ProtocolVersion, BaseEncoding,
 146  			)
 147  			if err == nil {
 148  				b.Fatal("expected a truncated merkle block error")
 149  			}
 150  		}
 151  	})
 152  
 153  	b.Run("transaction_inputs", func(b *testing.B) {
 154  		// The 4-byte transaction version is read by MsgTx.BtcDecode before
 155  		// the input count varint.
 156  		payload := benchmarkCountPayload(
 157  			b, make([]byte, 4), maxTxInPerMessage,
 158  		)
 159  
 160  		// Prewarm the script arena so the borrow and release pair populates
 161  		// the chunk pool, and the benchmark measures only the count-sized
 162  		// transaction input allocation made while decoding rather than the
 163  		// one-time chunk creation.
 164  		ar := borrowScriptArena()
 165  		ar.release()
 166  
 167  		b.ReportAllocs()
 168  		b.ResetTimer()
 169  		for i := 0; i < b.N; i++ {
 170  			var msg MsgTx
 171  			err := msg.BtcDecode(
 172  				bytes.NewReader(payload), ProtocolVersion, WitnessEncoding,
 173  			)
 174  			if err == nil {
 175  				b.Fatal("expected a truncated transaction input error")
 176  			}
 177  		}
 178  	})
 179  
 180  	b.Run("streaming_transaction_inputs", func(b *testing.B) {
 181  		// The 4-byte transaction version is read by MsgTx.BtcDecode before
 182  		// the input count varint.
 183  		payload := benchmarkCountPayload(
 184  			b, make([]byte, 4), maxTxInPerMessage,
 185  		)
 186  
 187  		ar := borrowScriptArena()
 188  		ar.release()
 189  
 190  		b.ReportAllocs()
 191  		b.ResetTimer()
 192  		for i := 0; i < b.N; i++ {
 193  			reader := &readSizeRecorder{
 194  				reader: bytes.NewReader(payload),
 195  			}
 196  			var msg MsgTx
 197  			err := msg.BtcDecode(
 198  				reader, ProtocolVersion, WitnessEncoding,
 199  			)
 200  			if err == nil {
 201  				b.Fatal("expected a truncated transaction input error")
 202  			}
 203  		}
 204  	})
 205  
 206  	b.Run("streaming_filter_checkpoints", func(b *testing.B) {
 207  		// The 1-byte filter type followed by the 32-byte stop hash are read
 208  		// by MsgCFCheckpt.BtcDecode before the filter header count varint.
 209  		payload := benchmarkCountPayload(
 210  			b, make([]byte, 33), maxCFHeadersLen,
 211  		)
 212  
 213  		b.ReportAllocs()
 214  		b.ResetTimer()
 215  		for i := 0; i < b.N; i++ {
 216  			reader := &readSizeRecorder{
 217  				reader: bytes.NewReader(payload),
 218  			}
 219  			var msg MsgCFCheckpt
 220  			err := msg.BtcDecode(
 221  				reader, ProtocolVersion, BaseEncoding,
 222  			)
 223  			if err == nil {
 224  				b.Fatal("expected a truncated checkpoint error")
 225  			}
 226  		}
 227  	})
 228  }
 229