1 Star 0 Fork 10

沧海辽望/blockchain_go_console

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
wallet.go 2.03 KB
一键复制 编辑 原始数据 按行查看 历史
duke.du 提交于 2018-11-20 15:18 . init
package main
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"log"
"crypto/sha256"
"golang.org/x/crypto/ripemd160"
"./base58"
"bytes"
)
//定义一个秘钥对结构, KeyPair
type Wallet struct {
PrivateKey *ecdsa.PrivateKey
//PubKey ecdsa.PublicKey
PubKey []byte //为了传输方便,在对端可以还原
}
func NewWallet() *Wallet {
privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
log.Panic(err)
}
pubKeyRaw := privateKey.PublicKey
//真正传递的形式
pubKey := append(pubKeyRaw.X.Bytes(), pubKeyRaw.Y.Bytes()...)
return &Wallet{PrivateKey: privateKey, PubKey: pubKey}
}
func (w *Wallet) GetAddress() string {
ripHashValue := HashPubKey(w.PubKey)
address := HashToAddress(ripHashValue)
return address
}
func HashToAddress(pubkeHash []byte) string {
version := byte(00)
payload := append([]byte{version}, pubkeHash...)
checkSum := checksum(payload)
payload = append(payload, checkSum...)
address := base58.Encode(payload)
return address
}
func AddressToHash(address string) []byte {
decodeInfo := base58.Decode(address)
pubkeyHash := decodeInfo[1:len(decodeInfo)-4]
return pubkeyHash
}
func IsValidAddress(address string) bool {
//1. 解码base58
decodeInfo := base58.Decode(address)
//2. 截取前21字节和 后四个字节
payload := decodeInfo[0: len(decodeInfo)-4]
checksum1 := decodeInfo[len(decodeInfo)-4:]
//3. 对前21字节进行checksum计算
firstHash := sha256.Sum256(payload)
secondHash := sha256.Sum256(firstHash[:])
checksum2 := secondHash[0:4]
//4. 比较生成cheksum1和截取cheksum2
return bytes.Equal(checksum1, checksum2)
}
func HashPubKey(pubkey []byte) []byte {
hash := sha256.Sum256(pubkey)
rip160Hasher := ripemd160.New()
_, err := rip160Hasher.Write(hash[:])
if err != nil {
log.Panic(err)
}
ripHashValue := rip160Hasher.Sum(nil)
return ripHashValue
}
func checksum(payload []byte) []byte {
firsHash := sha256.Sum256(payload)
sencondHash := sha256.Sum256(firsHash[:])
checkSum := sencondHash[0:4]
return checkSum
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/lz1289/blockchain_go_console.git
git@gitee.com:lz1289/blockchain_go_console.git
lz1289
blockchain_go_console
blockchain_go_console
master

搜索帮助