eth

package
v0.0.0-...-0fc9412 Latest Latest
Warning

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

Go to latest
Published: Jan 15, 2026 License: MIT Imports: 29 Imported by: 0

README

eth

The eth package centralizes Ethereum-related cryptographic helpers, currently focusing on two main areas:

  1. EIP-712 Typed Data (Message) Signing and Verification
  2. Secure Random Nonce Generation

1. EIP-712 Support

The package provides reliable EIP-712 signing tools:

  • Typed data hashing (domain separation and message struct hashing).
  • Signature generation and verification following EIP-712 and EIP-191 standards.
  • Utility functions for domain separator computation, message hashing, and final typed data hashes.
Key Exposed Types & Functions
  • EIP712Domain
  • NonceMessage
  • ComputeDomainSeparator(domain EIP712Domain) → [32]byte
  • ComputeMessageHash(msg NonceMessage) → [32]byte
  • ComputeEIP712Hash(domainSep, messageHash [32]byte) → [32]byte
  • SignEIP712Hash(privKey, domain, msg) → ([]byte, error)
  • VerifySignature(domain, msg, sig, signerPubKey) → (bool, error)

These utility methods allow signing arbitrary typed messages and verifying them against an expected signer.

2. Secure Random Nonce Generation

The package also supports generating secure random nonces:

  • Nonce function to create a random, alphanumeric nonce of specified length (between 8 and 128).

For example:

nonce, err := eth.Nonce(32)
if err != nil {
  ...
}

Usage Summary

  1. Import “github.com/ethereum/go-ethereum/crypto” (and other appropriate dependencies if not already included in your project).
  2. Construct an EIP712Domain with your DApp name, version, chain ID, and verifying contract.
  3. Generate a random nonce or create your own NonceMessage.
  4. Use SignEIP712Hash to sign the message with your private key.
  5. On the receiving end, call VerifySignature for verification.

For more examples, refer to the included tests (eip712_test.go) to see EIP-712 usage end-to-end.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidSignerType is returned when the key is not a valid eth.Signer
	ErrInvalidSignerType = errors.New("key is not of type eth.Signer")

	// ErrInvalidKeyType is returned when the key is not of the expected type
	ErrInvalidKeyType = errors.New("key is not of valid type")

	// ErrInvalidSigningString is returned when the signing string is invalid
	ErrInvalidSigningString = errors.New("invalid signing string")
)
View Source
var (
	DEFAULT_INTERVAL        = 10 * time.Millisecond
	DEFAULT_START_BLOCK     = uint64(1)
	DEFAULT_EXISTING_BLOCKS = DEFAULT_START_BLOCK + 1
)
View Source
var DEFAULT_FUNDING_AMOUNT = big.NewInt(0).SetUint64(1000000000000000000) // 1 ETH

DEFAULT_FUNDING_AMOUNT is the default amount of Ether assigned to each test account (1 ETH).

View Source
var SimulatedChainID = big.NewInt(1337)

SimulatedChainID is the chain ID used by the simulated environment, default is 1337.

Functions

func ComputeDomainSeparator

func ComputeDomainSeparator(domain EIP712Domain) [32]byte

ComputeDomainSeparator hashes the domain fields into a 32-byte domain separator.

func ComputeEIP712Hash

func ComputeEIP712Hash(domainSeparator, messageHash [32]byte) [32]byte

ComputeEIP712Hash creates the final EIP-191–style message hash: keccak256(0x19, 0x01, domainSeparator, messageHash).

func ComputeMessageHash

func ComputeMessageHash(msg NonceMessage) [32]byte

ComputeMessageHash builds a 32-byte hash of the NonceMessage struct using EIP-712 encoding.

func DeployAndFundERC20

func DeployAndFundERC20(
	ctx context.Context,
	be LocalBackend,
	name, symbol string,
	decimal uint8,
	funding map[common.Address]*big.Int,
	supply *big.Int,
) (common.Address, *test_erc20.TestERC20, error)

func DeployERC20

func DeployERC20(
	ctx context.Context,
	be LocalBackend,
	name, symbol string,
	decimals uint8,
	supply *big.Int,
) (common.Address, *test_erc20.TestERC20, error)

func FundERC20

func FundERC20(
	ctx context.Context,
	be LocalBackend,
	tokenContract *test_erc20.TestERC20,
	funding map[common.Address]*big.Int,
) error

func GenerateKeyPair

func GenerateKeyPair() (*ecdsa.PrivateKey, *ecdsa.PublicKey, error)

GenerateKeyPair creates a new private/public keypair for demonstration or testing.

func Nonce

func Nonce(length int) ([]byte, error)

RandomNonce returns a secure random byte slice of the specified length. The output includes only characters A-Z, a-z, and 0-9.

func RegisterES256Signer

func RegisterES256Signer()

RegisterES256Signer registers the ES256Signer as a JWT signing method

func SignEIP712Hash

func SignEIP712Hash(privKey *ecdsa.PrivateKey, domain EIP712Domain, msg NonceMessage) ([]byte, error)

SignEIP712Hash produces an EIP-712 signature using the provided private key, domain, and message.

func VerifySignature

func VerifySignature(domain EIP712Domain, msg NonceMessage, sig []byte, signerPubKey *ecdsa.PublicKey) (bool, error)

VerifySignature checks whether the provided signature corresponds to the given public key and message data.

Types

type Address

type Address common.Address

Address represents a common.Address stored as a hexadecimal string with a 0x prefix.

func NewAddressFromPubkey

func NewAddressFromPubkey(pub ecdsa.PublicKey) Address

func (*Address) Scan

func (a *Address) Scan(src interface{}) error

Scan implements the sql.Scanner interface. It expects a hexadecimal string (with a 0x prefix) and converts it into an Address.

func (Address) String

func (a Address) String() string

func (Address) Value

func (a Address) Value() (driver.Value, error)

Value implements the driver.Valuer interface. It returns the hexadecimal string representation (with 0x prefix) of the address.

type AssetConfig

type AssetConfig struct {
	Name     string
	Symbol   string
	Decimals uint8
	Supply   *big.Int
	Funding  *big.Int
}

type Deployer

type Deployer interface {
	Deploy(ctx context.Context, backend LocalBackend) (common.Address, *types.Transaction, error)
}

Deployer is a shortcut for deploying new contracts. The contract is assumed to be configured by the implementor.

type DeploymentResult

type DeploymentResult struct {
	Address     common.Address
	Transaction *types.Transaction
}

type EIP712Domain

type EIP712Domain struct {
	Name              string   // e.g. "My DApp"
	Version           string   // e.g. "1"
	ChainID           *big.Int // e.g. big.NewInt(1) for mainnet
	VerifyingContract common.Address
}

EIP712Domain represents a minimal EIP-712 domain struct.

type EIP712SignatureData

type EIP712SignatureData struct {
	Domain  EIP712Domain
	Message NonceMessage
}

EIP712SignatureData encapsulates the domain and message for typed hashing and signature.

type ES256Signer

type ES256Signer struct{}

ES256Signer implements jwt.SigningMethod for ES256 using an eth.Signer

func (*ES256Signer) Alg

func (m *ES256Signer) Alg() string

Alg returns the algorithm identifier

func (*ES256Signer) Sign

func (m *ES256Signer) Sign(signingString string, key interface{}) ([]byte, error)

Sign implements the Sign method from jwt.SigningMethod Using eth.Signer to create a signature

func (*ES256Signer) Verify

func (m *ES256Signer) Verify(signingString string, signature []byte, key interface{}) error

Verify implements the Verify method from jwt.SigningMethod For verification, we directly use the public key to verify the signature

type Hash

type Hash common.Hash

Hash represents a common.Hash stored as a hexadecimal string with a 0x prefix.

func (*Hash) Scan

func (h *Hash) Scan(src interface{}) error

Scan implements the sql.Scanner interface. It expects a hexadecimal string (with a 0x prefix) and converts it into a Hash.

func (Hash) String

func (h Hash) String() string

func (Hash) Value

func (h Hash) Value() (driver.Value, error)

Value implements the driver.Valuer interface. It returns the hexadecimal string representation (with 0x prefix) of the hash.

type LocalBackend

type LocalBackend interface {
	Backend

	Deployer() *SimulatedAccount
}

type LocalSigner

type LocalSigner struct {
	// contains filtered or unexported fields
}

func NewLocalSigner

func NewLocalSigner(privateKey *ecdsa.PrivateKey) LocalSigner

func (LocalSigner) Address

func (s LocalSigner) Address() Address

func (LocalSigner) PublicKey

func (s LocalSigner) PublicKey() *ecdsa.PublicKey

func (LocalSigner) Sign

func (s LocalSigner) Sign(msg []byte) (Signature, error)

type NodeBackend

type NodeBackend struct {
	*ethclient.Client
}

func NewNodeBackend

func NewNodeBackend(rpcUrl url.URL) (*NodeBackend, error)

func (*NodeBackend) WaitMined

func (b *NodeBackend) WaitMined(ctx context.Context, tx *types.Transaction) (*types.Receipt, error)

WaitMined waits for tx to be mined on the blockchain. It stops waiting when the context is canceled.

func (*NodeBackend) WaitMinedPeriod

func (n *NodeBackend) WaitMinedPeriod() time.Duration

type NonceMessage

type NonceMessage []byte

NonceMessage stores the data you want to sign, in this case a simple nonce as either a string or byte array.

type Signature

type Signature struct {
	R []byte
	S []byte
	V byte
}

func NewSignature

func NewSignature(R, S []byte, V byte) Signature

func NewSignatureFromBytes

func NewSignatureFromBytes(sig []byte) Signature

func (Signature) Equal

func (s1 Signature) Equal(s2 Signature) bool

func (Signature) MarshalJSON

func (s Signature) MarshalJSON() ([]byte, error)

func (Signature) Raw

func (sig Signature) Raw() (concatenatedSignature []byte)

func (Signature) RecoverPublicKey

func (sig Signature) RecoverPublicKey(msg []byte) (*ecdsa.PublicKey, error)

func (Signature) String

func (sig Signature) String() string

func (*Signature) UnmarshalJSON

func (s *Signature) UnmarshalJSON(b []byte) error

type Signer

type Signer interface {
	Sign(msg []byte) (Signature, error)
	PublicKey() *ecdsa.PublicKey
	Address() Address
}

type SimulatedAccount

type SimulatedAccount struct {
	PrivateKey    *ecdsa.PrivateKey
	CommonAddress common.Address
	TransactOpts  *bind.TransactOpts

	Signer signer.LocalSigner
}

func NewSimulatedAccount

func NewSimulatedAccount(chainID *big.Int) (SimulatedAccount, error)

func NewSimulatedAccountWithPrivateKey

func NewSimulatedAccountWithPrivateKey(privateKey *ecdsa.PrivateKey, chainID *big.Int) (SimulatedAccount, error)

type SimulatedAsset

type SimulatedAsset struct {
	Symbol   string
	ChainID  uint64
	Address  common.Address
	Decimals uint8
}

func NewSimulatedAsset

func NewSimulatedAsset(symbol string, chainID uint64, address common.Address, decimals uint8) SimulatedAsset

type SimulatedBackend

type SimulatedBackend struct {
	*simulated.Backend
	simulated.Client
	// contains filtered or unexported fields
}

SimulatedBackend wraps the simulated backend, client, accounts, and deployer.

func NewSimulatedBackend

func NewSimulatedBackend(config SimulatedBackendConfig) (*SimulatedBackend, error)

NewSimulatedBackend creates a new SimulatedBackend instance with 10 accounts funded by the default allocation. If supplied interval is not `nil`, then starts a goroutine that commits new blocks with the interval.

func (*SimulatedBackend) Account

func (sb *SimulatedBackend) Account(id int) (*SimulatedAccount, error)

Account returns a pointer to the SimulatedAccount at the given id or an error if the id is out of range.

func (*SimulatedBackend) ChainID

func (sb *SimulatedBackend) ChainID(ctx context.Context) (*big.Int, error)

ChainID returns the chain ID used by the SimulatedBackend.

func (*SimulatedBackend) Deployer

func (sb *SimulatedBackend) Deployer() *SimulatedAccount

Deployer returns a pointer to the deployer account used by the SimulatedBackend.

func (*SimulatedBackend) PrepareTx

func (sb *SimulatedBackend) PrepareTx(t *testing.T, callTx *ethereum.CallMsg, account *SimulatedAccount) (*types.Transaction, error)

PrepareTx prepares a transaction using a provided testing object, call message, and the given SimulatedAccount.

func (*SimulatedBackend) WaitMined

func (sb *SimulatedBackend) WaitMined(ctx context.Context, tx *types.Transaction) (*types.Receipt, error)

WaitMined waits for the specified transaction to be mined or until the context is canceled.

func (*SimulatedBackend) WaitMinedPeriod

func (sb *SimulatedBackend) WaitMinedPeriod() time.Duration

WaitMinedPeriod is the time interval to wait between block commits when simulating transactions.

type SimulatedBackendConfig

type SimulatedBackendConfig struct {
	Interval *time.Duration
}

type SimulatedEnvironment

type SimulatedEnvironment struct {
	Backend LocalBackend
	// contains filtered or unexported fields
}

func NewSimulatedEnvironment

func NewSimulatedEnvironment(ctx context.Context, config SimulatedEnvironmentConfig) (sim SimulatedEnvironment, err error)

func (*SimulatedEnvironment) Accounts

func (env *SimulatedEnvironment) Accounts() []SimulatedAccount

func (*SimulatedEnvironment) DeployContract

func (env *SimulatedEnvironment) DeployContract(deployer Deployer) (DeploymentResult, error)

func (*SimulatedEnvironment) DeployToken

func (env *SimulatedEnvironment) DeployToken(ctx context.Context, asset AssetConfig) (SimulatedAsset, error)

type SimulatedEnvironmentConfig

type SimulatedEnvironmentConfig struct {
	BackendConfig any
	Users         uint8
}

Jump to

Keyboard shortcuts

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