github.com/piotrnar/gocoin@v0.0.0-20240512203912-faa0448c5e96/lib/btc/target_test.go (about)

     1  package btc
     2  
     3  import (
     4  //	"fmt"
     5  	"testing"
     6  	"math"
     7  	"math/big"
     8  )
     9  
    10  type onevec struct {
    11  	b uint32
    12  	e string
    13  	d float64
    14  }
    15  
    16  var testvecs = []onevec {
    17  	{b:0x1b0404cb, e:"00000000000404CB000000000000000000000000000000000000000000000000"},
    18  	{b:0x1d00ffff, e:"00000000FFFF0000000000000000000000000000000000000000000000000000"},
    19  	{b:436330132, d:8974296.01488785},
    20  	{b:436543292, d:3275464.59},
    21  	{b:436591499, d:2864140.51},
    22  	{b:436841986, d:1733207.51},
    23  	{b:437155514, d:1159929.50},
    24  	{b:436789733, d:1888786.71},
    25  	{b:453031340, d:92347.59},
    26  	{b:453281356, d:14484.16},
    27  	{b:470771548, d:16.62},
    28  	{b:486604799, d:1.00},
    29  }
    30  
    31  func TestTarget(t *testing.T) {
    32  	for i := range testvecs {
    33  		x := SetCompact(testvecs[i].b)
    34  		d := GetDifficulty(testvecs[i].b)
    35  
    36  		c := GetCompact(x)
    37  		//fmt.Printf("%d. %d/%d -> %.8f / %.8f\n", i, testvecs[i].b, c, d, testvecs[i].d)
    38  		if testvecs[i].b != c {
    39  			t.Error("Set/GetCompact mismatch at alement", i)
    40  		}
    41  
    42  		if testvecs[i].e!="" {
    43  			y, _ := new(big.Int).SetString(testvecs[i].e, 16)
    44  			if x.Cmp(y) != 0 {
    45  				t.Error("Target mismatch at alement", i)
    46  			}
    47  		}
    48  
    49  		if testvecs[i].d!=0 && math.Abs(d-testvecs[i].d) > 0.1 {
    50  			t.Error("Difficulty mismatch at alement", i)
    51  		}
    52  	}
    53  }