前言

可以查询Github地址 Ethereum_GolangStudy

image.png


以太坊账户篇

初始化钱包和内容

通过npm,安装本地以太坊测试节点

npm install -g ganache-cli

使用助记词生成地址余额

ganache-cli -m "much repair shock carbon improve miss forget sock include bullet interest solution"

默认本地这个eth生成的本地测试账户,eth余额是100个。


查询账户余额
    // 连接到本地测试节点
    client, err := ethclient.Dial("http://127.0.0.1:8545")
    if err != nil {
        logrus.Error("client error:", err)
    }
    // (0) 0xE280029a7867BA5C9154434886c241775ea87e53 (100 ETH)
    account := common.HexToAddress("0xE280029a7867BA5C9154434886c241775ea87e53")
    // 获取区块好并返回余额地址
    balance, _ := client.BalanceAt(context.Background(), account, nil)
    logrus.Info("区块地址余额:", balance)

http://127.0.0.1:8545 是本地测试节点的接口地址


创建新的钱包
    privateKey, _ := crypto.GenerateKey()
    // 转化为字节
    privateKeyByte := crypto.FromECDSA(privateKey)
    // 转化为16进制 私钥
    logrus.Info("ethereum private :", hexutil.Encode(privateKeyByte))
    // 转化为16进制
    publicKey := privateKey.Public()
    publicKeyECDSA, _ := publicKey.(*ecdsa.PublicKey)
    publicKeyByte := crypto.FromECDSAPub(publicKeyECDSA)
    logrus.Info("ethereum public :", hexutil.Encode(publicKeyByte))
    // 转化为公共地址
    address := crypto.PubkeyToAddress(*publicKeyECDSA).Hex()
    logrus.Info("ethereum public address :", address)
    /*
        hash := sha3.NewLegacyKeccak256()
        hash.Write(publicKeyBytes[1:])
        fmt.Println(hexutil.Encode(hash.Sum(nil)[12:])) // 0x96216849c49358b10257cb55b28ea603c874b05e
    */

思路:

使用crypto.GenerateKey()生成私钥,-> 而后将其转为16进制的私钥地址

而后我们需要这个钱包的公共地址,这里有两种方法,目前介绍第一种:

私钥中获取公钥api->进行响应编码->而后使用hex的内置方法获取公钥。

其中ECDSA指的是内置的加密算法。


获取密钥库
    // // 生成本地密钥文件
    // ks := keystore.NewKeyStore("./goethereumbook/EthereumAccount/KeyStore", keystore.StandardScryptN, keystore.StandardScryptP)
    // password := "StarYuhen"
    // account, _ := ks.NewAccount(password)
    // logrus.Info("address:", account.Address.Hex())

    // 读取本地密钥文件
    file := "./goethereumbook/EthereumAccount/KeyStore/UTC--2022-10-02T06-59-17.491272600Z--0b80d82d8ebe0587ead2da9c18eef4262b2f3200"
    ks := keystore.NewKeyStore("./goethereumbook/EthereumAccount/tmp", keystore.StandardScryptN, keystore.StandardScryptP)
    // 读取本地文件,储存格式是json,也可以读取后用json库进行序列化之类的
    jsonByte, _ := ioutil.ReadFile(file)
    password := "StarYuhen"
    // 导入密钥
    account, _ := ks.Import(jsonByte, password, password)
    logrus.Info("address:", account.Address.Hex())

NewKeyStore生成本地密钥文件,而导入则是使用Impont进行密钥导入。

最后修改:2023 年 03 月 26 日
如果觉得我的文章对你有用,请随意赞赏