zoukankan      html  css  js  c++  java
  • go 实现波场(TRX)地址转换

    package main

    import (
        "bytes"
        "crypto/sha256"
        "encoding/hex"
        "math/big"
    )

    // ToHexAddress T ---->  41
    func ToHexAddress(address string) string {
        return hex.EncodeToString(base58Decode([]byte(address)))
    }

    // FromHexAddress 41 ---- > T
    func FromHexAddress(hexAddress string) (string, error) {
        addrByte, err := hex.DecodeString(hexAddress)
        if err != nil {
            return "", err
        }

        sha := sha256.New()
        sha.Write(addrByte)
        shaStr := sha.Sum(nil)

        sha2 := sha256.New()
        sha2.Write(shaStr)
        shaStr2 := sha2.Sum(nil)

        addrByte = append(addrByte, shaStr2[:4]...)

        return string(base58Encode(addrByte)), nil
    }

    var base58Alphabets = []byte("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")

    // base58Encode 编码
    func base58Encode(input []byte) []byte {
        x := big.NewInt(0).SetBytes(input)
        base := big.NewInt(58)
        zero := big.NewInt(0)
        mod := &big.Int{}
        var result []byte
        for x.Cmp(zero) != 0 {
            x.DivMod(x, base, mod)
            result = append(result, base58Alphabets[mod.Int64()])
        }
        reverseBytes(result)
        return result
    }

    // base58Decode 解码
    func base58Decode(input []byte) []byte {
        result := big.NewInt(0)
        for _, b := range input {
            charIndex := bytes.IndexByte(base58Alphabets, b)
            result.Mul(result, big.NewInt(58))
            result.Add(result, big.NewInt(int64(charIndex)))
        }
        decoded := result.Bytes()
        if input[0] == base58Alphabets[0] {
            decoded = append([]byte{0x00}, decoded...)
        }
        return decoded[:len(decoded)-4]
    }

    // reverseBytes 翻转字节
    func reverseBytes(data []byte) {
        for i, j := 0, len(data)-1; i < j; i, j = i+1, j-1 {
            data[i], data[j] = data[j], data[i]
        }
    }

    func main() {
        hexAddr := ToHexAddress("TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t") // 将地址转换为 hexString
        fmt.Println("HexAddr:", hexAddr)

        addr, _ := FromHexAddress("41a614f803b6fd780986a42c78ec9c7f77e6ded13c") // 将 hexString 转换为地址
        fmt.Println("Addr:", addr)
    }

    输出结果:

  • 相关阅读:
    【剑指offer】二叉搜索树与双向链表
    【剑指offer】复杂链表的复制
    【剑指offer】二叉树中和为某一值的路径
    2018.12.30 Intellij IDEA设置main方法自动补全
    2018.12.29 Spring FrameWork各个版本下载
    2018.12.26 Mac下的Eclipse在编辑Spring配置文件xml时自动提示类class包名配置
    2018.12.25 Spring中JDBCTemplate模版API学习
    2018.12.24 Spring中的aop演示(也就是运用aop技术实现代理模式)
    2018.12.22 Spring学习02
    2018.12.24 Ubuntu18.0.4 主题参考
  • 原文地址:https://www.cnblogs.com/wf-l5201314/p/14293581.html
Copyright © 2011-2022 走看看