blockchain_go/proofofwork.go

89 lines
1.5 KiB
Go
Raw Normal View History

2017-08-21 05:50:41 -05:00
package main
import (
"bytes"
"crypto/sha256"
2017-08-21 08:51:17 -05:00
"fmt"
2017-08-21 05:50:41 -05:00
"math"
"math/big"
)
var (
maxNonce = math.MaxInt64
)
const targetBits = 12
2017-08-21 09:06:52 -05:00
// ProofOfWork represents a proof-of-work
type ProofOfWork struct {
block *Block
target big.Int
}
// NewProofOfWork builds and returns a ProofOfWork
func NewProofOfWork(b *Block) *ProofOfWork {
2017-08-21 05:50:41 -05:00
targetBytes := make([]byte, 32)
2017-08-21 09:06:52 -05:00
target := big.Int{}
2017-08-21 05:50:41 -05:00
numOfZeros := targetBits / 4
targetBytes[numOfZeros-1] = 1
target.SetBytes(targetBytes)
2017-08-21 09:06:52 -05:00
pow := &ProofOfWork{b, target}
return pow
2017-08-21 05:50:41 -05:00
}
2017-08-21 09:06:52 -05:00
func (pow *ProofOfWork) prepareData(nonce int) []byte {
2017-08-21 05:50:41 -05:00
data := bytes.Join(
[][]byte{
2017-08-21 09:06:52 -05:00
pow.block.PrevBlockHash,
pow.block.Data,
IntToHex(pow.block.Timestamp),
IntToHex(int64(targetBits)),
IntToHex(int64(nonce)),
2017-08-21 05:50:41 -05:00
},
[]byte{},
)
return data
}
2017-08-21 09:06:52 -05:00
// Run performs a proof-of-work
func (pow *ProofOfWork) Run() (int, []byte) {
2017-08-21 05:50:41 -05:00
var hashInt big.Int
var hash [32]byte
nonce := 0
2017-08-21 09:06:52 -05:00
fmt.Printf("Mining the block containing \"%s\"\n", pow.block.Data)
2017-08-21 05:50:41 -05:00
for nonce < maxNonce {
2017-08-21 09:06:52 -05:00
data := pow.prepareData(nonce)
2017-08-21 05:50:41 -05:00
hash = sha256.Sum256(data)
2017-08-21 08:51:17 -05:00
fmt.Printf("\r%x", hash)
2017-08-21 05:50:41 -05:00
hashInt.SetBytes(hash[:])
2017-08-21 09:06:52 -05:00
if hashInt.Cmp(&pow.target) == -1 {
2017-08-21 05:50:41 -05:00
break
} else {
nonce++
}
}
2017-08-21 08:51:17 -05:00
fmt.Print("\n\n")
2017-08-21 05:50:41 -05:00
return nonce, hash[:]
}
2017-08-21 09:06:52 -05:00
// ConfirmProof confirms that the proof is correct
func (pow *ProofOfWork) ConfirmProof(nonce int) bool {
2017-08-21 05:50:41 -05:00
var hashInt big.Int
2017-08-21 09:06:52 -05:00
data := pow.prepareData(nonce)
2017-08-21 05:50:41 -05:00
hash := sha256.Sum256(data)
hashInt.SetBytes(hash[:])
2017-08-21 09:06:52 -05:00
confirmation := hashInt.Cmp(&pow.target) == -1
2017-08-21 05:50:41 -05:00
return confirmation
}