This commit is contained in:
THONG NGO 2021-08-26 13:26:04 +07:00 committed by GitHub
commit d5672f065f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 38 additions and 19 deletions

View File

@ -22,38 +22,31 @@ func Base58Encode(input []byte) []byte {
result = append(result, b58Alphabet[mod.Int64()])
}
ReverseBytes(result)
for b := range input {
if b == 0x00 {
result = append([]byte{b58Alphabet[0]}, result...)
} else {
break
}
// https://en.bitcoin.it/wiki/Base58Check_encoding#Version_bytes
if input[0] == 0x00 {
result = append(result, b58Alphabet[0])
}
ReverseBytes(result)
return result
}
// Base58Decode decodes Base58-encoded data
func Base58Decode(input []byte) []byte {
result := big.NewInt(0)
zeroBytes := 0
for b := range input {
if b == 0x00 {
zeroBytes++
}
}
payload := input[zeroBytes:]
for _, b := range payload {
for _, b := range input {
charIndex := bytes.IndexByte(b58Alphabet, b)
result.Mul(result, big.NewInt(58))
result.Add(result, big.NewInt(int64(charIndex)))
}
decoded := result.Bytes()
decoded = append(bytes.Repeat([]byte{byte(0x00)}, zeroBytes), decoded...)
if input[0] == b58Alphabet[0] {
decoded = append([]byte{0x00}, decoded...)
}
return decoded
}

24
base58_test.go Normal file
View File

@ -0,0 +1,24 @@
package main
import (
"encoding/hex"
"log"
"strings"
"testing"
"github.com/stretchr/testify/assert"
)
func TestBase58(t *testing.T) {
rawHash := "00010966776006953D5567439E5E39F86A0D273BEED61967F6"
hash, err := hex.DecodeString(rawHash)
if err != nil {
log.Fatal(err)
}
encoded := Base58Encode(hash)
assert.Equal(t, "16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM", string(encoded))
decoded := Base58Decode([]byte("16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM"))
assert.Equal(t, strings.ToLower("00010966776006953D5567439E5E39F86A0D273BEED61967F6"), hex.EncodeToString(decoded))
}

View File

@ -56,7 +56,9 @@ func (pow *ProofOfWork) Run() (int, []byte) {
data := pow.prepareData(nonce)
hash = sha256.Sum256(data)
fmt.Printf("\r%x", hash)
if math.Remainder(float64(nonce), 100000) == 0 {
fmt.Printf("\r%x", hash)
}
hashInt.SetBytes(hash[:])
if hashInt.Cmp(pow.target) == -1 {

View File

@ -162,7 +162,7 @@ func (tx *Transaction) Verify(prevTXs map[string]Transaction) bool {
dataToVerify := fmt.Sprintf("%x\n", txCopy)
rawPubKey := ecdsa.PublicKey{curve, &x, &y}
rawPubKey := ecdsa.PublicKey{Curve: curve, X: &x, Y: &y}
if ecdsa.Verify(&rawPubKey, []byte(dataToVerify), &r, &s) == false {
return false
}