I need to sign an offline transaction in golang. I have the following, which is a slight modification of this answer to a similar question:
import "github.com/ethereum/go-ethereum/core/types"
import "github.com/ethereum/go-ethereum/common"
import "github.com/ethereum/go-ethereum/crypto"
type GethTxn struct {
To string `json:"to"`
From string `json:"from"`
Gas string `json:"gas"`
GasPrice string `json:"gasPrice"`
Value string `json:"value"`
Data string `json:"input"`
}
func SignTxn(from string, _to string, data []byte, nonce uint64, value int64, gas *big.Int, gasPrice *big.Int, privkey *ecdsa.PrivateKey) (*GethTxn, error) {
var parsed_tx = new(GethTxn)
var amount = big.NewInt(value)
var bytesto [20]byte
_bytesto, _ := hex.DecodeString(_to[2:])
copy(bytesto[:], _bytesto)
to := common.Address([20]byte(bytesto))
signer := types.NewEIP155Signer(nil)
tx := types.NewTransaction(nonce, to, amount, gas, gasPrice, data)
signature, _ := crypto.Sign(tx.SigHash(signer).Bytes(), privkey)
signed_tx, _ := tx.WithSignature(signer, signature)
json_tx, _ := signed_tx.MarshalJSON()
_ = json.Unmarshal(json_tx, parsed_tx)
parsed_tx.From = from
fmt.Println("data", parsed_tx.Data)
return parsed_tx, nil
}
What I want is the raw transaction payload, but what I get is incorrect. I believe I want parsed_data.Data
, but I'm not sure. What I'm looking for is a Go analog to the following JS function:
var Tx = require('ethereumjs-tx');
var privateKey = new Buffer(pkey, 'hex')
var tx = new Tx(txn);
tx.sign(privateKey);
var serializedTx = tx.serialize().toString('hex')
Where serializedTx
is a string (the payload I want).
I'm a Golang noob so I suspect I'm just misusing geth, but any help would be very much appreciated. I have spent quite a long time on this problem.