I've been trying to implement the HashCash algorithm in Go! For those of you who don't know -
HashCash is a method to stop spam. Basically, a header is constructed of some environment variables known both to the client and server (email, timestamp etc.). A random nonce is appended to the end of the header. The client tries to bruteforce a partial hash collision (e.g. where the first x bits are 0) by changing the nonce.
HashCash works because it's not as expensive to find partial hash collisions. When the server receives this header, they verify the information in it (so it can be used only for one session) and compute the resulting hash. If the first x bits are 0, then a good amount of time has been expended on the client's machine, computing the collision (which wouldn't happen on a spambot)
For me, I'm just wanting to write a program which finds the time it takes for a client to find a partial hash collision of x bits.
I wrote this code which will return true/false if the int64 has a hash collision of x bits.
func partialAllZeroes (zeroCount uint8, val int64) (bool, os.Error) {
setBitString := "1111111111111111111111111111111111111111111111111111111111111111"
unsetBitString := "0000000000000000000000000000000000000000000000000000000000000000"
setBitString = setBitString[0:zeroCount-1]
unsetBitString = unsetBitString[0:zeroCount-1]
zeroTest, e := strconv.Btoi64(setBitString, 2) // 64 0bits
zeroes, e := strconv.Btoi64(unsetBitString, 2) // 64 1bits
if e != nil {
return false, e
}
result := val & zeroTest
switch {
case result == zeroes:
return true, nil
case result != zeroes:
return false, nil
}
return false, os.NewError("")
}
My current problem is I'm having alot of type conversion issues. For example, I am only able to operate on the int64 type, because that's what strconv.Btoi64 returns. Another issue that I'm also looking at is that the hash function returns as a byte array, and I have no idea how to convert that into an int64.
Below is my current hash code -
hasher := sha1.New()
baseCollisionString := "BASE COLLISION STRING"
nonce := "12345"
hasher.Write([]byte(strings.Join(baseCollisionString, nonce)))
testCollision := hasher.Sum()
// Somehow I must convert the first x bits of testCollision into an int64 type, so I can use partialAllZeroes with it