本文主要内容来自
以下是demo演示:
package main
import (
"crypto/ecdsa"
"crypto/sha256"
"encoding/hex"
"fmt"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/ethereum/go-ethereum/crypto"
"github.com/fbsobreira/gotron-sdk/pkg/account"
"github.com/fbsobreira/gotron-sdk/pkg/client"
"github.com/fbsobreira/gotron-sdk/pkg/keys"
"github.com/fbsobreira/gotron-sdk/pkg/store"
"github.com/tyler-smith/go-bip39"
"google.golang.org/grpc"
"google.golang.org/protobuf/proto"
)
var (
// 填写你自己用来转账的私钥
tornPrivate = ""
// 填写你自己用来转账的钱包地址
tornAddr = ""
grpcLink = "grpc.nile.trongrid.io:50051"
)
func main() {
mnemonic, err := generateMnemonic()
if err != nil {
fmt.Println("助记词生成错误:", err)
return
}
fmt.Println("Generated Mnemonic:", mnemonic)
acc := account.Creation{
Mnemonic: mnemonic,
Passphrase: "",
}
private, err := generatePrivateKeyFromMnemonic(acc)
if err != nil {
fmt.Println("私钥生成失败:", err.Error())
}
fmt.Println("Private Key (hex):", private.D.Text(16))
addr, _ := store.AddressFromAccountName(acc.Name)
fmt.Printf("Tron Address: %s\n", addr)
// 转账
amount := int64(10 * 1000000) // 10 TRX
sendTransaction(tornAddr, addr, amount)
}
// 生成 12 个助记词
func generateMnemonic() (string, error) {
// 使用128位的熵生成助记词(对应12个单词),你也可以选择256位的熵(对应24个单词)
entropy, err := bip39.NewEntropy(128)
if err != nil {
return "", err
}
// 生成助记词
mnemonic, err := bip39.NewMnemonic(entropy)
if err != nil {
return "", err
}
return mnemonic, nil
}
// 通过助记词生成私钥
func generatePrivateKeyFromMnemonic(acc account.Creation) (*ecdsa.PrivateKey, error) {
private, _ := keys.FromMnemonicSeedAndPassphrase(acc.Mnemonic, acc.MnemonicPassphrase, 0)
return private.ToECDSA(), nil
}
// 发起转账
func sendTransaction(fromAddress, toAddress string, amount int64) {
privateKeyBytes, _ := hex.DecodeString(tornPrivate)
c := client.NewGrpcClient(grpcLink)
if err := c.Start(grpc.WithInsecure()); err != nil {
fmt.Println("rpc 链接异常")
}
tx, err := c.Transfer(fromAddress, toAddress, amount)
if err != nil {
fmt.Println("交易发送失败")
}
rawData, err := proto.Marshal(tx.Transaction.GetRawData())
if err != nil {
fmt.Println("交易发送失败")
}
h256h := sha256.New()
h256h.Write(rawData)
hash := h256h.Sum(nil)
// btcec.PrivKeyFromBytes only returns a secret key and public key
sk, _ := btcec.PrivKeyFromBytes(privateKeyBytes)
signature, err := crypto.Sign(hash, sk.ToECDSA())
if err != nil {
fmt.Println("签名失败")
}
tx.Transaction.Signature = append(tx.Transaction.Signature, signature)
result, err := c.Broadcast(tx.Transaction)
if err != nil {
fmt.Println("交易失败")
}
fmt.Println("交易返回:", result)
}
踩坑情况:
最早用chat写的demo,demo一直跑不起来,要不给的包找不到,要不是一些加密错误。chat说:如果涉及到2021年9月之后发生的事件或更新的数据,我可能无法提供准确的信息。
然后就是官方文档,官方github只提供了java-tron的库。go-torn的库已经被移除了,猜测是社区包比较完善的原因。
社区包这边没有一个完善的文档,好在代码还是比较清晰直接看代码,简单的demo调用,验证完全没有问题。