difficulty_test.go raw

   1  package blockchain
   2  
   3  import (
   4  	"github.com/p9c/p9/pkg/bits"
   5  	"math/big"
   6  	"testing"
   7  )
   8  
   9  // TestBigToCompact ensures BigToCompact converts big integers to the expected compact representation.
  10  func TestBigToCompact(t *testing.T) {
  11  	tests := []struct {
  12  		in  int64
  13  		out uint32
  14  	}{
  15  		{0, 0},
  16  		{-1, 25231360},
  17  	}
  18  	for x, test := range tests {
  19  		n := big.NewInt(test.in)
  20  		r := bits.BigToCompact(n)
  21  		if r != test.out {
  22  			t.Errorf("TestBigToCompact test #%d failed: got %d want %d\n",
  23  				x, r, test.out,
  24  			)
  25  			return
  26  		}
  27  	}
  28  }
  29  
  30  // TestCompactToBig ensures CompactToBig converts numbers using the compact representation to the expected big intergers.
  31  func TestCompactToBig(t *testing.T) {
  32  	tests := []struct {
  33  		in  uint32
  34  		out int64
  35  	}{
  36  		{10000000, 0},
  37  	}
  38  	for x, test := range tests {
  39  		n := bits.CompactToBig(test.in)
  40  		want := big.NewInt(test.out)
  41  		if n.Cmp(want) != 0 {
  42  			t.Errorf("TestCompactToBig test #%d failed: got %d want %d\n",
  43  				x, n.Int64(), want.Int64(),
  44  			)
  45  			return
  46  		}
  47  	}
  48  }
  49  
  50  // TestCalcWork ensures CalcWork calculates the expected work value from values in compact representation.
  51  func TestCalcWork(t *testing.T) {
  52  	tests := []struct {
  53  		in  uint32
  54  		out int64
  55  	}{
  56  		{10000000, 0},
  57  	}
  58  	for x, test := range tests {
  59  		bits := test.in
  60  		r := CalcWork(bits, 0, 2)
  61  		if r.Int64() != test.out {
  62  			t.Errorf("TestCalcWork test #%d failed: got %v want %d\n",
  63  				x, r.Int64(), test.out,
  64  			)
  65  			return
  66  		}
  67  	}
  68  }
  69