build_test.go raw

   1  package utxobuild_test
   2  
   3  import (
   4  	"os"
   5  	"testing"
   6  
   7  	"git.smesh.lol/nostrino/pkg/crypto/chainhash"
   8  
   9  	utxostore "git.smesh.lol/btcd-lite/internal/utxo/store"
  10  	"git.smesh.lol/btcd-lite/internal/utxobuild"
  11  )
  12  
  13  // bodies is the fixture chain, as a block source.
  14  type bodies map[uint32][]byte
  15  
  16  func (b bodies) Block(height uint32) ([]byte, error) {
  17  	raw, ok := b[height]
  18  	if !ok {
  19  		return nil, os.ErrNotExist
  20  	}
  21  	return raw, nil
  22  }
  23  
  24  // TestBuildOverBodiesWithSpends builds a checkpoint chain over bodies that
  25  // create outputs and bodies that spend them, with spends falling in later
  26  // ranges than the creations.
  27  //
  28  // It is the builder's whole path over a chain where the two paths have
  29  // something to disagree about. A chain of creations only cannot fail this way,
  30  // and one round was lost to a fixture that spent nothing while claiming to.
  31  func TestBuildOverBodiesWithSpends(t *testing.T) {
  32  	raw, spends := chainOfBodies(40)
  33  	src := bodies{}
  34  	for h := uint32(0); h < uint32(len(raw)); h++ {
  35  		src[h] = raw[h]
  36  	}
  37  	for h := range spends {
  38  		if h < 40 && (h+1)%10 != 0 {
  39  			t.Logf("a spend at %d, which is inside a checkpoint range", h)
  40  		}
  41  	}
  42  	dir := t.TempDir()
  43  	utxobuild.Debug(func(height uint32, entries int, name chainhash.Hash) {
  44  		if height == 19 || height == 9 {
  45  			t.Logf("walk at %d: %d entries %s", height, entries, name)
  46  		}
  47  	}, func(to uint32, merged, walked chainhash.Hash) {
  48  		t.Logf("checkpoint %d: merged %s walked %s", to, merged, walked)
  49  	})
  50  	defer utxobuild.Debug(nil, nil)
  51  	res, err := utxobuild.Build(utxobuild.Config{
  52  		Dir: dir, Interval: 10, From: 0, To: 40, Blocks: src, Logf: t.Logf,
  53  	})
  54  	if err != nil {
  55  		t.Fatalf("build: %v", err)
  56  	}
  57  	if res.Name == (chainhash.Hash{}) {
  58  		t.Fatal("the build returned no name")
  59  	}
  60  	// The last snapshot is the one before the range's end, because the end is
  61  	// exclusive: 40 is not covered, 30 is.
  62  	if res.Height != 40 {
  63  		t.Fatalf("the walk ended at %d", res.Height)
  64  	}
  65  	want, err := utxostore.SetName(dir, 30)
  66  	if err != nil {
  67  		t.Fatal(err)
  68  	}
  69  	if want != res.Name {
  70  		t.Fatalf("the build reported %s, its file at 30 is %s", res.Name, want)
  71  	}
  72  }
  73