hashcheck_test.go raw

   1  package utxostore
   2  
   3  import (
   4  	"crypto/sha256"
   5  	"encoding/binary"
   6  	"testing"
   7  
   8  	"git.smesh.lol/nostrino/pkg/crypto/chainhash"
   9  
  10  	"git.smesh.lol/btcd-lite/internal/utxo"
  11  	"git.smesh.lol/btcd-lite/internal/wire"
  12  )
  13  
  14  func hcOp(i uint32) wire.OutPoint {
  15  	var h [32]byte
  16  	binary.LittleEndian.PutUint32(h[:4], i)
  17  	binary.BigEndian.PutUint32(h[28:], i)
  18  	return wire.OutPoint{Hash: h}
  19  }
  20  
  21  // TestNamesAgainstRawSHA is the measurement the merge question turns on: what
  22  // NameOf and WriteSet each claim a set is called, against double SHA-256 of
  23  // the bytes computed here with the standard library and nothing from this
  24  // package.
  25  func TestNamesAgainstRawSHA(t *testing.T) {
  26  	set := []utxo.Entry{
  27  		{OutPoint: hcOp(5), Value: 5, Height: 0},
  28  		{OutPoint: hcOp(1), Value: 1, Height: 1},
  29  		{OutPoint: hcOp(9), Value: 9, Height: 2, Coinbase: true, ScriptHash: [8]byte{7}},
  30  	}
  31  	raw := make([]byte, 0, len(set)*EntrySize)
  32  	buf := make([]byte, EntrySize)
  33  	for i := range set {
  34  		set[i].Encode(buf)
  35  		raw = append(raw, buf...)
  36  	}
  37  	first := sha256.Sum256(raw)
  38  	second := sha256.Sum256(first[:])
  39  	var want chainhash.Hash
  40  	copy(want[:], second[:])
  41  
  42  	if got := chainhash.DoubleHashH(raw); got != want {
  43  		t.Fatalf("DoubleHashH of the bytes is %s, raw double SHA is %s", got, want)
  44  	}
  45  	if got := NameOf(set); got != want {
  46  		t.Fatalf("NameOf says %s, raw double SHA of the encoded set is %s", got, want)
  47  	}
  48  	dir := t.TempDir()
  49  	if got, err := WriteSet(dir, 3, set); err != nil {
  50  		t.Fatalf("WriteSet: %v", err)
  51  	} else if got != want {
  52  		t.Fatalf("WriteSet says %s, raw double SHA is %s", got, want)
  53  	}
  54  
  55  	// The same set with its entries swapped must have another name: a name
  56  	// that ignores order would make every reordering of a set the same set.
  57  	swapped := []utxo.Entry{set[1], set[0], set[2]}
  58  	if NameOf(swapped) == NameOf(set) {
  59  		t.Fatal("two orderings of one set have one name")
  60  	}
  61  	// One field changed is another name.
  62  	changed := append([]utxo.Entry(nil), set...)
  63  	changed[2].Coinbase = false
  64  	if NameOf(changed) == NameOf(set) {
  65  		t.Fatal("a set and the same set with a changed field have one name")
  66  	}
  67  }
  68