const targetBits = 12
func (pow *ProofOfWork) Proof() (int, []byte) {
var hashInt big.Int
var hash [32]byte
n := 0
fmt.Printf("Mining : \"%s\"\n", pow.block.Data)
for n < maxNonce {
data := pow.prepareData(n)
hash = sha256.Sum256(data)
fmt.Printf("\r%x", hash)
hashInt.SetBytes(hash[:])
if hashInt.Cmp(pow.target) == -1 {
break
} else {
n++
}
}
fmt.Printf("\n\n")
return n, hash[:]
}
func CreateBlock(Data []byte, prevBlockHash []byte) *Block {
block := &Block{
time.Now().Unix(),
[]byte(Data),
prevBlockHash,
[]byte{},
0,
}
pow := NewProofOfWork(block)
nonce, hash := pow.Proof()
block.Hash = hash[:]
block.Nonce = nonce
return block
}
func (pow *ProofOfWork) Validate() bool {
var hashInt big.Int
data := pow.prepareData(pow.block.Nonce)
hash := sha256.Sum256(data)
hashInt.SetBytes(hash[:])
isValid := hashInt.Cmp(pow.target) == -1
return isValid
}