-
Notifications
You must be signed in to change notification settings - Fork 13
/
wallet.go
97 lines (78 loc) · 2.25 KB
/
wallet.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package main
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/sha256"
"fmt"
"log"
"golang.org/x/crypto/ripemd160"
)
const version = byte(0x00)
const addressChecksumLen = 4
// Wallet stores private and public keys
type Wallet struct {
PrivateKey []byte
PublicKey []byte
}
// NewWallet creates and returns a Wallet
func NewWallet() *Wallet {
private, public := newKeyPair()
wallet := Wallet{private, public}
return &wallet
}
// GetAddress returns wallet address
func (w Wallet) GetAddress() (address string) {
/* See https://en.bitcoin.it/wiki/Technical_background_of_Bitcoin_addresses */
/* Convert the public key to bytes */
pub_bytes := w.PublicKey
/* SHA256 Hash */
fmt.Println("2 - Perform SHA-256 hashing on the public key")
sha256_h := sha256.New()
sha256_h.Reset()
sha256_h.Write(pub_bytes)
pub_hash_1 := sha256_h.Sum(nil)
fmt.Println(byteString(pub_hash_1))
fmt.Println("=======================")
/* RIPEMD-160 Hash */
fmt.Println("3 - Perform RIPEMD-160 hashing on the result of SHA-256")
ripemd160_h := ripemd160.New()
ripemd160_h.Reset()
ripemd160_h.Write(pub_hash_1)
pub_hash_2 := ripemd160_h.Sum(nil)
fmt.Println(byteString(pub_hash_2))
fmt.Println("=======================")
/* Convert hash bytes to base58 check encoded sequence */
address = b58checkencode(0x00, pub_hash_2)
return address
}
// HashPubKey hashes public key
func HashPubKey(pubKey []byte) []byte {
publicSHA256 := sha256.Sum256(pubKey)
RIPEMD160Hasher := ripemd160.New()
_, err := RIPEMD160Hasher.Write(publicSHA256[:])
if err != nil {
log.Panic(err)
}
publicRIPEMD160 := RIPEMD160Hasher.Sum(nil)
return publicRIPEMD160
}
const privKeyBytesLen = 32
func newKeyPair() ([]byte, []byte) {
curve := elliptic.P256()
private, err := ecdsa.GenerateKey(curve, rand.Reader)
if err != nil {
log.Panic(err)
}
d := private.D.Bytes()
b := make([]byte, 0, privKeyBytesLen)
priKet := paddedAppend(privKeyBytesLen, b, d)
pubKey := append(private.PublicKey.X.Bytes(), private.PublicKey.Y.Bytes()...)
return priKet, pubKey
}
// ToWIF converts a Bitcoin private key to a Wallet Import Format string.
func ToWIF(priv []byte) (wif string) {
/* Convert bytes to base-58 check encoded string with version 0x80 */
wif = b58checkencode(0x80, priv)
return wif
}