realblock_test.go raw

   1  package utxo_test
   2  
   3  import (
   4  	"encoding/hex"
   5  	"os"
   6  	"strings"
   7  	"testing"
   8  
   9  	"git.smesh.lol/btcd-lite/internal/utxo"
  10  	"git.smesh.lol/btcd-lite/internal/wire"
  11  )
  12  
  13  // TestRealBlockTouches: a real regtest block with a spend in it, walked into a
  14  // set. The block is the node's own bytes from `getblock ... 0`; the first
  15  // transaction is the coinbase and the second spends an output of an earlier
  16  // block, which is the case the synthetic tests never had.
  17  func TestRealBlockTouches(t *testing.T) {
  18  	raw, err := os.ReadFile("testdata/regtest-block-105.hex")
  19  	if err != nil {
  20  		t.Skip("no captured block")
  21  	}
  22  	b, err := wire.ParseBlock(mustHex(t, strings.TrimSpace(string(raw))))
  23  	if err != nil {
  24  		t.Fatalf("parse: %v", err)
  25  	}
  26  	if len(b.Txs) != 2 {
  27  		t.Fatalf("%d transactions", len(b.Txs))
  28  	}
  29  	if b.Txs[0].IsCoinBase() == false {
  30  		t.Fatal("the first transaction is not the coinbase")
  31  	}
  32  	// The set the block is applied to holds the outpoint it spends.
  33  	spent := b.Txs[1].TxIn[0].PreviousOutPoint
  34  	prior := []utxo.Entry{{OutPoint: spent, Value: 5_000_000_000, Height: 104}}
  35  	lookup := utxo.Lookup(func(op wire.OutPoint) (utxo.Entry, bool) { return utxo.Find(prior, op) })
  36  	ts, err := utxo.BlockTouches(b, 105, lookup)
  37  	if err != nil {
  38  		t.Fatalf("touches: %v", err)
  39  	}
  40  	var created, spends int
  41  	for _, tc := range ts {
  42  		if tc.Spent {
  43  			spends++
  44  			if tc.OutPoint != spent {
  45  				t.Fatalf("a spend of %s, expected only %s", tc.OutPoint, spent)
  46  			}
  47  			continue
  48  		}
  49  		created++
  50  		if tc.New.Height != 105 {
  51  			t.Fatalf("created entry at height %d", tc.New.Height)
  52  		}
  53  		if tc.New.Coinbase != (tc.New.OutPoint.Hash == b.Txs[0].TxID()) {
  54  			t.Fatalf("the coinbase flag is wrong for %s", tc.New.OutPoint)
  55  		}
  56  	}
  57  	if spends != 1 || created != len(b.Txs[0].TxOut)+len(b.Txs[1].TxOut) {
  58  		t.Fatalf("%d spends, %d created", spends, created)
  59  	}
  60  	after, err := utxo.ApplyRange(prior, ts)
  61  	if err != nil {
  62  		t.Fatalf("apply: %v", err)
  63  	}
  64  	if _, ok := utxo.Find(after, spent); ok {
  65  		t.Fatal("the spent outpoint survived the range")
  66  	}
  67  	if err := utxo.Validate(after); err != nil {
  68  		t.Fatalf("the resulting set is not sorted: %v", err)
  69  	}
  70  	t.Logf("block 105: %d created, %d spent, %d entries after", created, spends, len(after))
  71  }
  72  
  73  func mustHex(t *testing.T, s string) []byte {
  74  	t.Helper()
  75  	b, err := hex.DecodeString(s)
  76  	if err != nil {
  77  		t.Fatal(err)
  78  	}
  79  	return b
  80  }
  81