生成地址代码如下
func (w Wallet) GetAddress() []byte { pubKeyHash := HashPubKey(w.PublicKey) versionedPayload := append([]byte{version}, pubKeyHash...) checksum := checksum(versionedPayload) fullPayload := append(versionedPayload, checksum...) address := Base58Encode(fullPayload) return address } func HashPubKey(pubKey []byte) []byte { publicSHA256 := sha256.Sum256(pubKey) RIPEMD160Hasher := ripemd160.New() _, err := RIPEMD160Hasher.Write(publicSHA256[:]) publicRIPEMD160 := RIPEMD160Hasher.Sum(nil) return publicRIPEMD160 } func checksum(payload []byte) []byte { firstSHA := sha256.Sum256(payload) secondSHA := sha256.Sum256(firstSHA[:]) return secondSHA[:addressChecksumLen] }
地址是否正确代码
addressChecksumLen:=4 func ValidateAddress(address string) bool { pubKeyHash := Base58Decode([]byte(address)) actualChecksum := pubKeyHash[len(pubKeyHash)-addressChecksumLen:] version := pubKeyHash[0] pubKeyHash = pubKeyHash[1 : len(pubKeyHash)-addressChecksumLen] targetChecksum := checksum(append([]byte{version}, pubKeyHash...)) return bytes.Compare(actualChecksum, targetChecksum) == 0 }
Base58Decode是对比特币地址进行解码,然后取后四位校验位actualChecksum,利用去掉校验位的pubKeyHash再次算出校验位与地址的校验位做出对比,即可验证地址的正确性。 其中用到的函数有:
func checksum(payload []byte) [] //利用两次shah256求校验位 byte { firstSHA := sha256.Sum256(payload) secondSHA := sha256.Sum256(firstSHA[:]) return secondSHA[:addressChecksumLen] }
这是解码的函数,已经有不少现有的代码支持,故不作讲解
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 { 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...) return decoded }
以上就是go语言实战之实现比特币地址校验步骤的详细内容,更多关于go语言比特币地址校验的资料请关注其它相关文章!