Skip to content

Instantly share code, notes, and snippets.

@sknv
Created January 24, 2021 13:09
Show Gist options
  • Select an option

  • Save sknv/13ecd3c4b68b10b9728d9746be6bd4c6 to your computer and use it in GitHub Desktop.

Select an option

Save sknv/13ecd3c4b68b10b9728d9746be6bd4c6 to your computer and use it in GitHub Desktop.
package main
import (
"crypto/ecdsa"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"fmt"
"math/big"
"github.com/btcsuite/btcd/btcec"
"github.com/btcsuite/btcutil/base58"
"golang.org/x/crypto/sha3"
)
/*
Tron Address Algorithm
https://developers.tron.network/docs/account
*/
func main() {
var address, privateKey string
// Use the ECDSA crypto library to generate the Tron Address
address, privateKey = generateAddress()
fmt.Printf("address: %s, private key: %s\n", address, privateKey)
// Using a hex of a private key extract the Tron Address
address = addressFromPrivateKey("F43EBCC94E6C257EDBE559183D1A8778B2D5A08040902C0F0A77A3343A1D0EA5") // TWVRXXN5tsggjUCDmqbJ4KxPdJKQiynaG6
fmt.Println(address)
address = addressFromPrivateKey("a24c37ec71cfc4046f617b5011f932c994c863e20ad3b8a20b21a4de943279dd") // TXA74MA1z4669rLBKmJB16AvHxppTLJCdT
fmt.Println(address)
address = addressFromPrivateKey("e36ace9ad7486f6149790e2a95a2a53fe57454b7a083093a0049457baebbabcf") // TKfSBdtyTikWF5XCRdxqNktif3UShzS4ke
fmt.Println(address)
}
func generateAddress() (address, privateKey string) {
// #1: generate a new key using the ECDSA library
key, _ := ecdsa.GenerateKey(btcec.S256(), rand.Reader)
priv := key.D.Bytes()
pubX := key.X.Bytes()
pubY := key.Y.Bytes()
pub := append(pubX, pubY...)
return addressFromPublicKey(pub), hex.EncodeToString(priv)
}
func addressFromPrivateKey(privateKeyHex string) string {
// #1: build the Private Key and extract the Public Key
keyBytes, _ := hex.DecodeString(privateKeyHex)
var key ecdsa.PrivateKey
key.PublicKey.Curve = btcec.S256()
key.D = new(big.Int).SetBytes(keyBytes)
key.PublicKey.X, key.PublicKey.Y = key.PublicKey.Curve.ScalarBaseMult(keyBytes)
pub := append(key.X.Bytes(), key.Y.Bytes()...)
return addressFromPublicKey(pub)
}
func addressFromPublicKey(publicKey []byte) string {
// #2
hash := sha3.NewLegacyKeccak256()
hash.Write(publicKey)
hashed := hash.Sum(nil)
last20 := hashed[len(hashed)-20:]
// #3
addr41 := append([]byte{0x41}, last20...)
// #4
hash2561 := sha256.Sum256(addr41)
hash2562 := sha256.Sum256(hash2561[:])
checksum := hash2562[:4]
// #5 and #6
rawAddr := append(addr41, checksum...)
tronAddr := base58.Encode(rawAddr)
return tronAddr
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment