walletcore

package module
v0.0.0-...-a0434c8 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2025 License: Apache-2.0, MIT Imports: 28 Imported by: 0

README

wallet-core

wallet-core is a lightweight Go library providing core wallet primitives for Filament Labs projects — including address parsing, cryptographic helpers, persistent key storage, RPC utilities, and a high-level manager that ties everything together.


Features

  • Filecoin & hex address parsing/validation
  • Cryptographic helpers (key management, signing, verifying)
  • Simple on-disk key/value DB wrapper
  • JSON-RPC client abstraction
  • Manager layer that orchestrates storage, crypto, and RPC calls

Repository Layout

address.go      # address parsing, validation, formatting
crypto.go       # crypto helpers: key handling, signing, verifying
db.go           # simple local database wrapper
manager.go      # high-level manager for wallet operations
rpcclient.go    # JSON-RPC client utilities
types.go        # core shared types
go.mod
LICENSE-APACHE
LICENSE-MIT
README.md

Installation

go get github.com/filament-labs/wallet-core@latest

Quick Start

package main

import (
    "fmt"
    walletcore "github.com/filament-labs/wallet-core"
)

func main() {
    // Example: initialize manager (adjust constructor name to match actual source)
    m, err := walletcore.NewManager("./data")
    if err != nil {
        panic(err)
    }
    defer m.Close()

    // Parse an address
    addr, err := walletcore.ParseAddress("f1...")
    if err != nil {
        fmt.Println("invalid address:", err)
        return
    }

    fmt.Println("parsed address:", addr.String())

    // Sign a message
    sig, err := m.SignMessage(addr, []byte("hello wallet-core"))
    if err != nil {
        panic(err)
    }
    fmt.Printf("signature: %x
", sig)
}

Replace function names with the exact ones from the library if they differ.


High-Level API Overview

Address Utilities (address.go)
  • ParseAddress(string) (Address, error)
  • Address.String() — canonical formatting
Crypto Helpers (crypto.go)
  • Key generation & management
  • Sign(message) / Verify(signature)
DB Layer (db.go)
  • File-backed key/value storage for keys and wallet metadata
  • Typically used internally by Manager
RPC Client (rpcclient.go)
  • Lightweight JSON-RPC wrapper
  • Call(method string, params ...any) (any, error)
Manager (manager.go)
  • High-level orchestration
  • Manages:
    • Address + key creation
    • Signing operations
    • RPC interactions
    • Persistence via the DB

Example: JSON-RPC Usage

client := walletcore.NewRPCClient("https://node.example/rpc")

resp, err := client.Call("Wallet.GetBalance", addr.String())
if err != nil {
    panic(err)
}

fmt.Println("balance:", resp)

Contributing

  1. Fork the repo
  2. Create a feature branch: git checkout -b feature/my-feature
  3. Write tests where appropriate
  4. Run linters: go fmt, go vet
  5. Submit a pull request

Security Notes

  • Private keys should be handled and stored carefully.
  • Avoid using raw private keys in production systems — consider hardware wallets or OS-backed keystores.
  • Crypto-related contributions should include tests and clear documentation.

License

This project is dual-licensed under MIT and Apache-2.0.

See the included license files for full details.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrWalletNotFound      = errors.New("wallet not found")
	ErrInvalidMnemonic     = errors.New("invalid mnemonic phrase")
	ErrInvalidPassphrase   = errors.New("invalid passphrase")
	ErrInvalidWalletName   = errors.New("invalid wallet name")
	ErrDuplicateWalletName = errors.New("duplicate wallet name")
	ErrWalletLocked        = errors.New("wallet is locked")
	ErrInsufficientBalance = errors.New("insufficient balance")
	ErrInvalidAddress      = errors.New("invalid address")
	ErrTransactionFailed   = errors.New("transaction failed")
)

Functions

func Decode

func Decode(data []byte, dest any) error

func DecryptData

func DecryptData(encrypted, nonce, key []byte) ([]byte, error)

func DecryptMnemonic

func DecryptMnemonic(encrypted []byte, passphrase string) (string, error)

DecryptMnemonic decrypts an encrypted mnemonic with a passphrase

func DeriveAddressFromPrivateKey

func DeriveAddressFromPrivateKey(privKey *ecdsa.PrivateKey) (map[string]string, error)

DeriveAddressFromPrivateKey derives Filecoin addresses from private key

func Encode

func Encode(value any) ([]byte, error)

func EncryptData

func EncryptData(plaintext, key []byte, encrypted, nonce *[]byte) error

Encrypt data with AES-GCM

func EncryptMnemonic

func EncryptMnemonic(mnemonic, passphrase string) ([]byte, error)

EncryptMnemonic encrypts a mnemonic phrase with a passphrase

func FormatFIL

func FormatFIL(attoFil string) (string, error)

FormatFIL converts an attoFIL string to a human-readable FIL string with 6 decimals.

func GenerateMnemonic

func GenerateMnemonic(bits int) (string, error)

GenerateMnemonic generates a new BIP39 mnemonic phrase

func MnemonicToSeed

func MnemonicToSeed(mnemonic, password string) []byte

MnemonicToSeed converts a mnemonic to a seed

func ParseFIL

func ParseFIL(fil string) (string, error)

ParseFIL converts a human-readable FIL string (e.g. "1.5") to attoFIL string.

func ValidateMnemonic

func ValidateMnemonic(mnemonic string) bool

ValidateMnemonic checks if a mnemonic phrase is valid

Types

type AddressType

type AddressType string
const (
	AddressTypeF1  AddressType = "f1"
	AddressTypeF4  AddressType = "f4"
	AddressTypeEth AddressType = "0x"
)
const (
	AddressTypeF1  AddressType = "f1"
	AddressTypeF4  AddressType = "f4"
	AddressTypeEth AddressType = "0x"
)

func (AddressType) Valid

func (t AddressType) Valid() bool

type Balance

type Balance struct {
	Address   string    `json:"address"`
	Balance   string    `json:"balance"` // in attoFIL
	Nonce     uint64    `json:"nonce"`
	Timestamp time.Time `json:"timestamp"`
}

Balance represents wallet balance information

type GasEstimate

type GasEstimate struct {
	GasLimit   int64
	GasFeeCap  string
	GasPremium string
}

GasEstimate represents gas estimation for a transaction

type Manager

type Manager interface {
	LoadWallets(ctx context.Context) ([]Wallet, error)
	CreateWallet(ctx context.Context, walletName, keystorePassphrase string) (*Wallet, error)
	RecoverWallet(ctx context.Context, seedPhrase, walletName, password string) (*Wallet, error)
	DeleteWallet(walletID string) error
}

func NewManager

func NewManager(dataDir string, opts ...ManagerOption) (Manager, error)

NewManager initializes a Manager with Badger DB and optional configurations

type ManagerOption

type ManagerOption func(*manager) error

func WithOptions

func WithOptions(url, token string) ManagerOption

WithRPC allows setting a custom RPC endpoint and optional token

type RPCClient

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

RPCClient wraps Filecoin RPC API interactions with clean lifecycle management.

func NewRPCClient

func NewRPCClient(config RPCConfig) (*RPCClient, error)

NewRPCClient creates a new RPC client with validated config and authenticated connection.

func (*RPCClient) Close

func (c *RPCClient) Close()

Close safely closes the RPC connection.

func (*RPCClient) EstimateGas

func (c *RPCClient) EstimateGas(ctx context.Context, msg *types.Message) (*GasEstimate, error)

EstimateGas computes gas parameters for a message.

func (*RPCClient) GetBalance

func (c *RPCClient) GetBalance(ctx context.Context, addr address.Address) (*Balance, error)

GetBalance returns the current balance and nonce for an address.

func (*RPCClient) GetChainHead

func (c *RPCClient) GetChainHead(ctx context.Context) (int64, error)

GetChainHead returns the current chain height.

func (*RPCClient) GetNonce

func (c *RPCClient) GetNonce(ctx context.Context, addr address.Address) (uint64, error)

GetNonce fetches the current nonce for the given address.

func (*RPCClient) GetTransaction

func (c *RPCClient) GetTransaction(ctx context.Context, cidStr string) (*Transaction, error)

GetTransaction retrieves full transaction details by CID.

func (*RPCClient) GetTransactions

func (c *RPCClient) GetTransactions(ctx context.Context, addr address.Address, limit int) ([]*Transaction, error)

GetTransactions returns up to `limit` recent transactions involving the address.

func (*RPCClient) SendMessage

func (c *RPCClient) SendMessage(ctx context.Context, signedMsg *types.SignedMessage) (string, error)

SendMessage pushes a signed message to the mempool and returns its CID.

func (*RPCClient) WaitForMessage

func (c *RPCClient) WaitForMessage(ctx context.Context, cidStr string, confidence uint64) (*types.MessageReceipt, error)

WaitForMessage waits for a message to be included in a tipset with given confidence.

type RPCConfig

type RPCConfig struct {
	Endpoint string
	Token    string
	Timeout  time.Duration
}

RPCConfig contains RPC endpoint configuration

type SendOptions

type SendOptions struct {
	From       address.Address
	To         address.Address
	Value      string // in attoFIL
	GasLimit   *int64
	GasFeeCap  *string
	GasPremium *string
	Method     uint64
	Params     []byte
}

SendOptions contains options for sending transactions

type Transaction

type Transaction struct {
	Cid        string    `json:"cid"`
	From       string    `json:"from"`
	To         string    `json:"to"`
	Value      string    `json:"value"`
	GasFeeCap  string    `json:"gas_fee_cap"`
	GasPremium string    `json:"gas_premium"`
	GasLimit   int64     `json:"gas_limit"`
	Nonce      uint64    `json:"nonce"`
	Method     uint64    `json:"method"`
	Params     []byte    `json:"params,omitempty"`
	Timestamp  time.Time `json:"timestamp"`
	Height     int64     `json:"height"`
	Status     string    `json:"status"` // "pending", "confirmed", "failed"
}

Transaction represents a Filecoin transaction

type Wallet

type Wallet struct {
	ID        string            `json:"id"`
	IsDefault bool              `json:"is_default"`
	Name      string            `json:"name"`
	Mnemonic  string            `json:"-"`
	KeyJSON   []byte            `json:"key_json"`
	Addrs     map[string]string `json:"addresses"`
	Meta      map[string]string `json:"metadata"`
	CreatedAt time.Time         `json:"created_at"`
	UpdatedAt time.Time         `json:"updated_at"`
	// contains filtered or unexported fields
}

Wallet represents a Filecoin wallet with encrypted storage

type WalletStore

type WalletStore interface {
	// Save stores a wallet securely
	Save(wallet *Wallet) error

	// Get retrieves a wallet by ID
	Get(id string) (*Wallet, error)

	// List returns all wallets
	List() ([]*Wallet, error)

	// Delete removes a wallet
	Delete(id string) error

	// Update modifies an existing wallet
	Update(wallet *Wallet) error
}

WalletStore defines the interface for wallet persistence

Jump to

Keyboard shortcuts

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