diff --git a/blockchain/hash.go b/blockchain/hash.go index 467c1a5..7ff3814 100644 --- a/blockchain/hash.go +++ b/blockchain/hash.go @@ -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() diff --git a/blockchain/hash_test.go b/blockchain/hash_test.go index 1df4247..a4320e9 100644 --- a/blockchain/hash_test.go +++ b/blockchain/hash_test.go @@ -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 {