transaction

package
v0.27.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 13, 2026 License: LGPL-3.0 Imports: 23 Imported by: 7

Documentation

Overview

Package transaction provides transaction signing and submission for TRON.

Index

Examples

Constants

View Source
const MaxTotalSignatures = signer.MaxTotalSignatures

MaxTotalSignatures is the most signatures (ECDSA plus TIP-899 pq_auth_sig) a transaction may carry, the node's TOTAL_SIGN_NUM; see signer.MaxTotalSignatures.

Variables

View Source
var (
	ErrNilTransaction      = errors.New("transaction is nil")
	ErrNoContracts         = errors.New("transaction has no contracts")
	ErrNilParameter        = errors.New("contract parameter is nil")
	ErrUnsupportedContract = errors.New("unsupported contract type")
	ErrUnmarshalContract   = errors.New("failed to unmarshal contract parameter")
)
View Source
var (
	// ErrEmptyRawData is returned when a raw data hex string is empty.
	ErrEmptyRawData = errors.New("raw data hex string is empty")
	// ErrInvalidHex is returned when a hex string cannot be decoded.
	ErrInvalidHex = errors.New("invalid hex string")
	// ErrInvalidTxJSON is returned when transaction JSON cannot be parsed.
	ErrInvalidTxJSON = errors.New("invalid transaction JSON")
	// ErrTxIDMismatch is returned when the txID does not match the hash of raw_data.
	ErrTxIDMismatch = errors.New("txID does not match hash of raw_data")
	// ErrNilRawData is returned when a transaction has nil raw_data.
	ErrNilRawData = errors.New("transaction raw_data is nil")
)
View Source
var (
	// ErrBadTransactionParam is returned when invalid params are given to the
	// controller upon execution of a transaction.
	ErrBadTransactionParam = errors.New("transaction has bad parameters")
)

Functions

func EstimateBandwidth added in v0.27.0

func EstimateBandwidth(tx *core.Transaction, pending ...core.PQScheme) (int64, error)

EstimateBandwidth estimates the bandwidth, in bytes, a transaction will consume, using java-tron's rule: the serialized size of the transaction with its ret field cleared, plus 64 bytes (MAX_RESULT_SIZE_IN_TX) for every contract except a ShieldedTransferContract. The input is not modified.

pending lists the post-quantum signatures that are not on tx yet. Each adds pqc.MaxAuthSigSize(scheme) bytes, the size of a pq_auth_sig entry with the scheme's public key and its largest signature. FN-DSA-512 signatures vary in length (617 to 667 bytes), so a pending FN-DSA-512 signature counts at its maximum and the estimate can exceed the real usage by up to 50 bytes per signature; ML-DSA-44 signatures have a fixed size. Pending schemes must be supported, otherwise the error wraps pqc.ErrUnsupportedScheme.

This is an estimate, not a quote. Signatures already on tx (ECDSA in signature, post-quantum in pq_auth_sig) are counted because they are part of the serialized transaction. An ECDSA signature that is not on tx yet is NOT counted, since pending only covers post-quantum signatures: sign with the ECDSA keys first, or add 67 bytes (65 plus the field tag and length) for each one still to come. The account's free bandwidth, staked bandwidth, and the node's own accounting can still differ from this figure. A transaction that creates a new account is charged under the create-account rules, not by this byte count.

func FromJSON added in v0.24.3

func FromJSON(jsonData []byte) (*core.Transaction, error)

FromJSON reconstructs a Transaction from a JSON representation as returned by TRON HTTP API endpoints (e.g., /wallet/createtransaction).

Deserialization uses the raw_data_hex field exclusively for reliable protobuf reconstruction. The raw_data JSON object is ignored because it has encoding differences (hex vs base64 bytes) that make direct JSON-to-proto mapping unreliable.

If a txID is present in the JSON, it is validated against the SHA256 hash of the deserialized raw_data. Signatures are decoded from hex strings (an optional "0x" prefix is accepted) and attached to the transaction; an empty or invalid entry is an error wrapping ErrInvalidTxJSON that names its index but not its value.

TIP-899 post-quantum signatures are read from the pq_auth_sig array. Each entry carries a scheme (the enum name such as "FN_DSA_512" or "ML_DSA_44", or its integer value), and hex-encoded public_key and signature (an optional "0x" prefix is accepted). Unknown schemes, UNKNOWN_PQ_SCHEME, bad hex, and empty keys or signatures are rejected. Key and signature lengths are not checked here; the node is the authority. pq_auth_sig is not part of raw_data, so it does not affect txID validation.

Example:

resp, _ := http.Post("https://api.trongrid.io/wallet/createtransaction", ...)
body, _ := io.ReadAll(resp.Body)
tx, err := transaction.FromJSON(body)

func FromRawDataHex added in v0.24.3

func FromRawDataHex(rawDataHex string, signatures ...[]byte) (*core.Transaction, error)

FromRawDataHex reconstructs a Transaction from a hex-encoded raw_data protobuf. This is the format commonly returned by TRON HTTP APIs in the raw_data_hex field.

The hex string may optionally have a "0x" prefix, which is stripped before decoding. Any provided signatures are attached to the resulting transaction, preserving their order.

The signatures are ECDSA signatures only. raw_data_hex does not cover TIP-899 pq_auth_sig entries; use FromJSON to carry those.

Example:

tx, err := transaction.FromRawDataHex(apiResponse.RawDataHex)
if err != nil { ... }
tx, err = transaction.SignTransaction(tx, privateKey)

func OwnerAndPermission added in v0.27.0

func OwnerAndPermission(tx *core.Transaction) (owner address.Address, permissionID int32, contractType core.Transaction_Contract_ContractType, err error)

OwnerAndPermission returns the owner_address, permission_id and type of tx's single contract: the account and permission the node checks the signatures against, and the type to check with client.PermissionAllows. It fails closed unless tx has exactly one contract whose parameter matches its type and has a valid owner_address (so a ShieldedTransferContract is an error). The address is a copy.

func SignTransaction added in v0.24.1

func SignTransaction(tx *core.Transaction, key *btcec.PrivateKey) (*core.Transaction, error)

SignTransaction signs a transaction using a btcec private key.

func SignTransactionECDSA added in v0.24.1

func SignTransactionECDSA(tx *core.Transaction, key *ecdsa.PrivateKey) (*core.Transaction, error)

SignTransactionECDSA signs a transaction using an ECDSA private key.

It fails with an error wrapping signer.ErrTooManySignatures when tx already carries MaxTotalSignatures signatures.

func SignTransactionPQ added in v0.27.0

func SignTransactionPQ(tx *core.Transaction, key pqc.PrivateKey) (*core.Transaction, error)

SignTransactionPQ signs a transaction with a TIP-899 post-quantum key, appending a pq_auth_sig entry and leaving the ECDSA signatures alone. It delegates to signer.SignTransactionPQ, which documents the checks and errors.

Signing does not ask the node whether the scheme is enabled. Use txcore.Send, which does, or call txcore.CheckPQSchemes before broadcasting.

Experimental: TIP-899 is a draft and is live only on the Nile testnet.

func ToJSON added in v0.24.3

func ToJSON(tx *core.Transaction) ([]byte, error)

ToJSON serializes a Transaction to a JSON envelope containing txID, raw_data_hex, raw_data, and signature fields. Transactions carrying TIP-899 post-quantum signatures also get a pq_auth_sig array of {"scheme", "public_key", "signature"} objects, with the scheme printed by enum name and the bytes as lowercase hex; the field is omitted when there are none. An entry FromJSON would reject (nil, an unknown or zero scheme, an empty public key or signature) is an error, so the output round-trips.

The txID is computed as the SHA256 hash of the protobuf-encoded raw_data. The raw_data_hex field contains the canonical protobuf serialization and is suitable for use with FromJSON or FromRawDataHex. Signatures are encoded as lowercase hex strings.

Note: the raw_data JSON object uses protojson encoding, which differs from the TRON HTTP API format (protojson uses base64 for bytes and @type for Any fields, while TRON uses hex strings and type_url/value). The raw_data field is included for human readability; use raw_data_hex for programmatic deserialization.

Example (PqAuthSig)

Hand a PQ-signed transaction to another tool as JSON and read it back. The pq_auth_sig entries survive the round trip.

package main

import (
	"crypto/rand"
	"fmt"
	"log"

	"github.com/fbsobreira/gotron-sdk/pkg/client/transaction"
	"github.com/fbsobreira/gotron-sdk/pkg/pqc"
	"github.com/fbsobreira/gotron-sdk/pkg/proto/core"
	"github.com/fbsobreira/gotron-sdk/pkg/signer"
	"google.golang.org/protobuf/types/known/anypb"
)

func main() {
	key, err := pqc.GenerateKey(core.PQScheme_ML_DSA_44, rand.Reader)
	if err != nil {
		log.Fatal(err)
	}
	defer key.Destroy()

	addr := key.Public().Address()
	param, err := anypb.New(&core.TransferContract{OwnerAddress: addr, ToAddress: addr, Amount: 1_000_000})
	if err != nil {
		log.Fatal(err)
	}
	tx := &core.Transaction{RawData: &core.TransactionRaw{
		RefBlockBytes: []byte{0x01, 0x02},
		RefBlockHash:  []byte{0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a},
		Expiration:    1_700_000_060_000,
		Timestamp:     1_700_000_000_000,
		Contract: []*core.Transaction_Contract{{
			Type:      core.Transaction_Contract_TransferContract,
			Parameter: param,
		}},
	}}
	if _, err := signer.SignTransactionPQ(tx, key); err != nil {
		log.Fatal(err)
	}

	data, err := transaction.ToJSON(tx)
	if err != nil {
		log.Fatal(err)
	}
	back, err := transaction.FromJSON(data)
	if err != nil {
		log.Fatal(err)
	}

	got := back.GetPqAuthSig()
	fmt.Println("pq_auth_sig entries:", len(got))
	fmt.Println("scheme:", got[0].GetScheme())
	fmt.Println("same signature:", string(got[0].GetSignature()) == string(tx.GetPqAuthSig()[0].GetSignature()))

}
Output:
pq_auth_sig entries: 1
scheme: ML_DSA_44
same signature: true

func ToRawDataHex added in v0.24.3

func ToRawDataHex(tx *core.Transaction) (string, error)

ToRawDataHex returns the hex-encoded protobuf serialization of the transaction's raw_data. The output is lowercase hex without a "0x" prefix, matching the format used by TRON HTTP APIs.

func WithPermissionID added in v0.24.3

func WithPermissionID(id int32) func(*Controller)

WithPermissionID sets the permission ID for multi-signature transactions. PermissionID = 0 is the owner permission (default), PermissionID = 2 is commonly used for active permissions in multi-sig setups.

When co-signing a transaction that already carries signatures, the ID must match the one it was signed with; ExecuteTransaction refuses to change it with an error wrapping ErrBadTransactionParam.

func WithSigner added in v0.27.0

func WithSigner(s signer.Signer) func(*Controller)

WithSigner sets the signer used by ExecuteTransaction. It is the preferred way to choose a signer; when set it takes precedence over Behavior.SigningImpl and the keystore and account passed to NewController, which are then ignored for signing. A nil signer is ignored.

If s signs with a TIP-899 post-quantum key (it implements txcore.PQSchemeSigner, as signer.NewPQSigner does), ExecuteTransaction first asks the node whether the scheme is enabled and fails with an error wrapping txcore.ErrPQSchemeDisabled if it is not, without signing or broadcasting. This check also runs in DryRun mode.

A typed-nil Signer (a nil pointer wrapped in a non-nil interface) is the caller's bug and is not filtered; only a nil interface is ignored.

Types

type ContractData added in v0.25.2

type ContractData struct {
	Type   string         // e.g. "TransferContract", "TriggerSmartContract"
	Fields map[string]any // decoded fields with base58 addresses and converted amounts
}

ContractData holds decoded contract parameters with human-readable values.

func DecodeContractData added in v0.25.2

func DecodeContractData(tx *core.Transaction) (*ContractData, error)

DecodeContractData decodes the first contract parameter from a transaction into a ContractData struct with base58 addresses and human-readable amounts.

type Controller

type Controller struct {
	Behavior behavior
	Result   *api.Return
	Receipt  *core.TransactionInfo
	// contains filtered or unexported fields
}

Controller drives the transaction signing process.

The preferred way to choose how a transaction is signed is the WithSigner option, which accepts any signer.Signer (keystore, private key, Ledger, or a TIP-899 post-quantum signer). Without it the Controller falls back to Behavior.SigningImpl and the keystore and account given to NewController.

func NewController

func NewController(
	client *client.GrpcClient,
	senderKs *keystore.KeyStore,
	senderAcct *keystore.Account,
	tx *core.Transaction,
	options ...func(*Controller),
) *Controller

NewController initializes a Controller, caller can control behavior via options

func (*Controller) ExecuteTransaction

func (C *Controller) ExecuteTransaction() error

ExecuteTransaction is the single entrypoint to execute a plain transaction. Each step in transaction creation, execution probably includes a mutation Each becomes a no-op if executionError occurred in any previous step

func (*Controller) GetRawData

func (C *Controller) GetRawData() ([]byte, error)

GetRawData Byes from Transaction

func (*Controller) GetResultError

func (C *Controller) GetResultError() error

GetResultError return result error

func (*Controller) Transaction added in v0.27.0

func (C *Controller) Transaction() *core.Transaction

Transaction returns the Controller's transaction. After ExecuteTransaction it is the signed transaction, carrying its ECDSA signature or TIP-899 pq_auth_sig, which in DryRun mode is the only output since nothing is broadcast and Result and Receipt stay nil. The returned value is the Controller's own instance, not a copy.

func (*Controller) TransactionHash

func (C *Controller) TransactionHash() (string, error)

TransactionHash extract hash from TX

type SignerImpl

type SignerImpl int

SignerImpl identifies the signing backend used for transactions.

const (
	// Software signs transactions using an in-process private key.
	Software SignerImpl = iota
	// Ledger signs transactions using a connected Ledger hardware wallet.
	Ledger
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL