wallet/pkg/tron/tron_account.go

73 lines
1.6 KiB
Go
Raw Normal View History

2024-08-31 14:46:20 +00:00
package tron
import (
"fmt"
"strings"
"custodial/pkg/locker"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/decred/dcrd/dcrec/secp256k1/v4"
"github.com/fbsobreira/gotron-sdk/pkg/address"
"github.com/fbsobreira/gotron-sdk/pkg/keys/hd"
"github.com/tyler-smith/go-bip39"
)
const MAX_ACCOUNT_INDEX int = 4294967295
type TronAccount struct {
privateKey *secp256k1.PrivateKey
publicKey *secp256k1.PublicKey
address string
}
func (t *TronAccount) PrivateKey() *secp256k1.PrivateKey {
return t.privateKey
}
func (t *TronAccount) PublicKey() *secp256k1.PublicKey {
return t.publicKey
}
func (t *TronAccount) Address() string {
return t.address
}
var master [32]byte
var ch [32]byte
func InitMaster(mnemonic, passphrase string) {
if master != [32]byte{} {
return
}
seed := bip39.NewSeed(strings.TrimSpace(mnemonic), strings.TrimSpace(passphrase))
master, ch = hd.ComputeMastersFromSeed(seed, []byte("Bitcoin seed"))
}
func InitMasterFromPrivateSettings() {
mnemonic := locker.GetPrivateEnv("BIP39_MNEMONIC")
passphrase := locker.GetPrivateEnv("PASSPHRASE")
if mnemonic == "" {
panic("BIP39_MNEMONIC is not set")
}
InitMaster(mnemonic, passphrase)
}
func DeriveAccount(index int) (*TronAccount, error) {
private, _ := hd.DerivePrivateKeyForPath(
btcec.S256(),
master,
ch,
fmt.Sprintf("44'/195'/0'/0/%d", index),
)
t := TronAccount{}
t.privateKey, t.publicKey = btcec.PrivKeyFromBytes(private[:])
t.address = address.PubkeyToAddress(*t.publicKey.ToECDSA()).String()
return &t, nil
}
func GetSpender() (*TronAccount, error) {
return DeriveAccount(MAX_ACCOUNT_INDEX)
}