2017-09-07 02:18:12 -05:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2017-09-07 04:42:38 -05:00
|
|
|
"bytes"
|
2017-09-07 02:18:12 -05:00
|
|
|
"crypto/elliptic"
|
|
|
|
"crypto/rand"
|
|
|
|
"crypto/sha256"
|
2017-09-07 04:42:38 -05:00
|
|
|
"encoding/gob"
|
|
|
|
"io/ioutil"
|
2017-09-07 02:18:12 -05:00
|
|
|
"log"
|
|
|
|
|
|
|
|
"golang.org/x/crypto/ripemd160"
|
|
|
|
)
|
|
|
|
|
|
|
|
const version = byte(0x00)
|
2017-09-07 04:42:38 -05:00
|
|
|
const walletFile = "wallet.dat"
|
2017-09-07 02:18:12 -05:00
|
|
|
|
|
|
|
// Wallet ...
|
|
|
|
type Wallet struct {
|
|
|
|
PrivateKey []byte
|
|
|
|
PublicKey []byte
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetAddress returns wallet address
|
|
|
|
func (w Wallet) GetAddress() []byte {
|
|
|
|
publicSHA256 := sha256.Sum256(w.PublicKey)
|
|
|
|
|
|
|
|
RIPEMD160Hasher := ripemd160.New()
|
|
|
|
_, err := RIPEMD160Hasher.Write(publicSHA256[:])
|
|
|
|
if err != nil {
|
|
|
|
log.Panic(err)
|
|
|
|
}
|
|
|
|
publicRIPEMD160 := RIPEMD160Hasher.Sum(nil)
|
|
|
|
|
|
|
|
versionedPayload := append([]byte{version}, publicRIPEMD160...)
|
|
|
|
checksum := checksum(versionedPayload)
|
|
|
|
|
|
|
|
fullPayload := append(versionedPayload, checksum...)
|
|
|
|
address := Base58Encode(fullPayload)
|
|
|
|
|
|
|
|
return address
|
|
|
|
}
|
|
|
|
|
2017-09-07 04:33:17 -05:00
|
|
|
// SaveToFile saves the wallet to a file
|
|
|
|
func (w Wallet) SaveToFile() {
|
2017-09-07 04:42:38 -05:00
|
|
|
var content bytes.Buffer
|
2017-09-07 04:33:17 -05:00
|
|
|
|
2017-09-07 04:42:38 -05:00
|
|
|
encoder := gob.NewEncoder(&content)
|
|
|
|
err := encoder.Encode(w)
|
|
|
|
if err != nil {
|
|
|
|
log.Panic(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
err = ioutil.WriteFile(walletFile, content.Bytes(), 0644)
|
|
|
|
if err != nil {
|
|
|
|
log.Panic(err)
|
|
|
|
}
|
2017-09-07 04:33:17 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
// NewWallet creates and returns a Wallet
|
2017-09-07 02:18:12 -05:00
|
|
|
func NewWallet() *Wallet {
|
|
|
|
private, public := newKeyPair()
|
|
|
|
wallet := Wallet{private, public}
|
|
|
|
|
|
|
|
return &wallet
|
|
|
|
}
|
|
|
|
|
|
|
|
func newKeyPair() ([]byte, []byte) {
|
|
|
|
curve := elliptic.P256()
|
|
|
|
private, x, y, err := elliptic.GenerateKey(curve, rand.Reader)
|
|
|
|
if err != nil {
|
|
|
|
log.Panic(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
public := append(x.Bytes(), y.Bytes()...)
|
|
|
|
|
|
|
|
return private, public
|
|
|
|
}
|
|
|
|
|
|
|
|
// Checksum ...
|
|
|
|
func checksum(payload []byte) []byte {
|
|
|
|
firstSHA := sha256.Sum256(payload)
|
|
|
|
secondSHA := sha256.Sum256(firstSHA[:])
|
|
|
|
|
|
|
|
return secondSHA[:4]
|
|
|
|
}
|