Skip to content

Commit

Permalink
BigIntToHash test
Browse files Browse the repository at this point in the history
  • Loading branch information
david-julien committed Jul 13, 2017
1 parent d942014 commit fd911d0
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
3 changes: 2 additions & 1 deletion blockchain/hash.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,8 @@ func HashToBigInt(h Hash) *big.Int {
return new(big.Int).SetBytes(h[:])
}

// BigIntToHash converts a big integer to a hash
// BigIntToHash converts a big integer to a hash. If the size of the big int
// is larger than the size of hash, the function will return a hash set to 0.
func BigIntToHash(x *big.Int) Hash {
bytes := x.Bytes()

Expand Down
32 changes: 31 additions & 1 deletion blockchain/hash_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,41 @@ package blockchain
import (
"math/big"
"testing"

c "github.com/ubclaunchpad/cumulus/common/constants"
"github.com/ubclaunchpad/cumulus/common/math"
)

func TestBigIntToHash(t *testing.T) {
x := math.BigAdd(math.BigExp(2, 256), c.Big1)
h := BigIntToHash(x)

for i := 0; i < HashLen; i++ {
if h[i] != 0 {
t.Fail()
}
}

h = BigIntToHash(c.Big0)

for i := 0; i < HashLen; i++ {
if h[i] != 0 {
t.Fail()
}
}

h = BigIntToHash(c.MaxUint256)

for i := 0; i < HashLen; i++ {
if h[i] != 255 {
t.Fail()
}
}
}

func TestHashToBigInt(t *testing.T) {
// Max hash value
x := new(big.Int).Sub(new(big.Int).Exp(big.NewInt(int64(2)), big.NewInt(int64(256)), big.NewInt(0)), big.NewInt(1))
x := c.MaxUint256
h := BigIntToHash(x)

if HashToBigInt(h).Cmp(x) != 0 {
Expand Down

0 comments on commit fd911d0

Please sign in to comment.