golang 实现 ETH 交易离线签名(冷签)

栏目: Go · 发布时间: 6年前

内容简介:其中其中签名有两种算法第二种不需要提供

构造交易

import (
    "github.com/ethereum/go-ethereum/core/types"
    "github.com/ethereum/go-ethereum/common"
    "github.com/ethereum/go-ethereum/rlp"
    "github.com/ethereum/go-ethereum/crypto"
    "github.com/ethereum/go-ethereum/common/hexutil"
)
const (
    GAS_LIMIT         = 21000
    GAS_PRICE         = 500000000000
)
tx := types.NewTransaction(nonce, common.HexToAddress(toAddress), value, GAS_LIMIT, big.NewInt(GAS_PRICE), nil)

签名交易

其中 StringToPrivateKey 是获取私钥的方法,在下边会有介绍

func SignTransaction(tx *types.Transaction, privateKeyStr string) (string, error) {
    privateKey, err := StringToPrivateKey(privateKeyStr)
    if err != nil {
        return "", err
    }
    signTx, err := types.SignTx(tx, types.NewEIP155Signer(big.NewInt(4)), privateKey)
    //signTx, err := types.SignTx(tx, types.HomesteadSigner{}, privateKey)
    if err != nil {
        return "", nil
    }

    b, err := rlp.EncodeToBytes(signTx)
    if err != nil {
        return "", err
    }
    return hex.EncodeToString(b), nil
}

其中签名有两种算法

  • types.NewEIP155Signer(big.NewInt(chainId))
  • types.HomesteadSigner{}

第二种不需要提供 chainId 但是据说不稳定, types.NewEIP155Signer(big.NewInt(4) 4 是 rinkeby 测试网络,1是主网

私钥的获取 *ecdsa.PrivateKey

  1. 从明文的私钥字符串转换成该类型
func StringToPrivateKey(privateKeyStr string) (*ecdsa.PrivateKey, error) {
    privateKeyByte, err := hexutil.Decode(privateKeyStr)
    if err != nil {
        return nil, err
    }
    privateKey, err := crypto.ToECDSA(privateKeyByte)
    if err != nil {
        return nil, err
    }
    return privateKey, nil
}
  1. keystore + password 解析出私钥
func KeystoreToPrivateKey(keystoreContent []byte, password string) (*ecdsa.PrivateKey, error) {
    unlockedKey, err := keystore.DecryptKey(keystoreContent, password)
    if err != nil {
        return nil, err
    }
    return unlockedKey.PrivateKey, nil
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Rework

Rework

Jason Fried、David Heinemeier Hansson / Crown Business / 2010-3-9 / USD 22.00

"Jason Fried and David Hansson follow their own advice in REWORK, laying bare the surprising philosophies at the core of 37signals' success and inspiring us to put them into practice. There's no jarg......一起来看看 《Rework》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

SHA 加密
SHA 加密

SHA 加密工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具