block_test.go raw

   1  package wire_test
   2  
   3  import (
   4  	"bytes"
   5  	"encoding/hex"
   6  	"encoding/json"
   7  	"os"
   8  	"path/filepath"
   9  	"runtime"
  10  	"testing"
  11  
  12  	"git.smesh.lol/nostrino/pkg/crypto/chainhash"
  13  
  14  	"git.smesh.lol/btcd-lite/internal/wire"
  15  )
  16  
  17  type vector struct {
  18  	Height            uint32   `json:"height"`
  19  	BlockHash         string   `json:"blockHash"`
  20  	Block             string   `json:"block"`
  21  	PrevOutputScripts []string `json:"prevOutputScripts"`
  22  	Filter            string   `json:"filter"`
  23  	Note              string   `json:"note"`
  24  }
  25  
  26  func loadVectors(t *testing.T) []vector {
  27  	t.Helper()
  28  	_, file, _, _ := runtime.Caller(0)
  29  	raw, err := os.ReadFile(filepath.Join(filepath.Dir(file), "..", "..", "testdata", "bip158_testnet19.json"))
  30  	if err != nil {
  31  		t.Fatalf("read vectors: %v", err)
  32  	}
  33  	var vectors []vector
  34  	if err := json.Unmarshal(raw, &vectors); err != nil {
  35  		t.Fatalf("parse vectors: %v", err)
  36  	}
  37  	if len(vectors) == 0 {
  38  		t.Fatal("no vectors")
  39  	}
  40  	return vectors
  41  }
  42  
  43  // TestParseVectors decodes every official test vector block, requires its hash
  44  // to be the vector's, and requires the re-serialized non-witness transactions
  45  // to hash to the leaves of the block's own merkle root.
  46  func TestParseVectors(t *testing.T) {
  47  	for _, v := range loadVectors(t) {
  48  		v := v
  49  		t.Run(v.BlockHash, func(t *testing.T) {
  50  			raw, err := hex.DecodeString(v.Block)
  51  			if err != nil {
  52  				t.Fatalf("decode: %v", err)
  53  			}
  54  			block, err := wire.ParseBlock(raw)
  55  			if err != nil {
  56  				t.Fatalf("parse: %v", err)
  57  			}
  58  			if got := block.BlockHash().String(); got != v.BlockHash {
  59  				t.Fatalf("block hash %s, want %s", got, v.BlockHash)
  60  			}
  61  			if block.Size != len(raw) {
  62  				t.Fatalf("size %d, want %d", block.Size, len(raw))
  63  			}
  64  			if got := block.MerkleRoot(); got != block.HeaderMerkleRoot() {
  65  				t.Fatalf("merkle root %s, header %s", got, block.HeaderMerkleRoot())
  66  			}
  67  			// Every non-witness serialization must be stable: decoding and
  68  			// re-encoding is the identity, which is what makes a txid from a
  69  			// parsed transaction the txid the block committed to.
  70  			for i := range block.Txs {
  71  				tx := &block.Txs[i]
  72  				again, err := wire.ParseTx(tx.SerializeNoWitness())
  73  				if err != nil {
  74  					t.Fatalf("tx %d: re-parse: %v", i, err)
  75  				}
  76  				if again.TxID() != tx.TxID() {
  77  					t.Fatalf("tx %d: txid drift on re-encode", i)
  78  				}
  79  				if tx.HasWitness && bytes.Equal(tx.SerializeNoWitness(), nil) {
  80  					t.Fatalf("tx %d: empty no-witness form", i)
  81  				}
  82  			}
  83  		})
  84  	}
  85  }
  86  
  87  // TestReject checks the invariants a body has to meet before it is a block.
  88  func TestReject(t *testing.T) {
  89  	vectors := loadVectors(t)
  90  	raw, err := hex.DecodeString(vectors[1].Block)
  91  	if err != nil {
  92  		t.Fatal(err)
  93  	}
  94  	if _, err := wire.ParseBlock(raw[:len(raw)-1]); err == nil {
  95  		t.Fatal("a truncated block parsed")
  96  	}
  97  	trailing := append(append([]byte(nil), raw...), 0x00)
  98  	if _, err := wire.ParseBlock(trailing); err == nil {
  99  		t.Fatal("a block with trailing bytes parsed")
 100  	}
 101  	// Flip one byte of the coinbase script; the header no longer matches.
 102  	block, err := wire.ParseBlock(raw)
 103  	if err != nil {
 104  		t.Fatal(err)
 105  	}
 106  	cb := &block.Txs[0]
 107  	if !cb.IsCoinBase() {
 108  		t.Fatal("first transaction is not a coinbase")
 109  	}
 110  	if _, err := wire.ParseTx(raw); err == nil {
 111  		t.Fatal("a whole block parsed as a transaction")
 112  	}
 113  }
 114  
 115  // TestMerkleRoot checks the duplicate-last rule at odd widths against a
 116  // two-leaf and three-leaf tree computed by hand.
 117  func TestMerkleRoot(t *testing.T) {
 118  	leaf := func(b byte) chainhash.Hash {
 119  		var h chainhash.Hash
 120  		h[0] = b
 121  		return h
 122  	}
 123  	d := func(a, b chainhash.Hash) chainhash.Hash {
 124  		buf := append(a[:], b[:]...)
 125  		return chainhash.DoubleHashH(buf)
 126  	}
 127  	a, b, c := leaf(1), leaf(2), leaf(3)
 128  	if got, want := wire.MerkleRoot([]chainhash.Hash{a}), a; got != want {
 129  		t.Fatalf("single: %s want %s", got, want)
 130  	}
 131  	if got, want := wire.MerkleRoot([]chainhash.Hash{a, b}), d(a, b); got != want {
 132  		t.Fatalf("pair: %s want %s", got, want)
 133  	}
 134  	want := d(d(a, b), d(c, c))
 135  	if got := wire.MerkleRoot([]chainhash.Hash{a, b, c}); got != want {
 136  		t.Fatalf("three: %s want %s", got, want)
 137  	}
 138  }
 139