wallet

package
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Mar 17, 2025 License: MIT Imports: 25 Imported by: 0

README

Cryptocurrency Wallet Implementation

Go Version

A cryptocurrency wallet implementation supporting Bitcoin (BTC) and Monero (XMR) in Go. Features BIP32/44 compliant HD wallet functionality for Bitcoin and RPC-based wallet operations for Monero.

Features

Bitcoin Support
  • BIP32/44 compliant HD wallet implementation
  • Support for both mainnet and testnet networks
  • Multiple public API endpoint failover system
  • Local Bitcoin node connectivity with public node fallback
  • Deterministic address generation and validation
  • Thread-safe wallet operations
  • Base58 encoding/decoding
  • Address balance checking
  • Extensive API endpoint list with automatic failover
Monero Support
  • RPC-based wallet implementation
  • Balance querying capabilities
  • Subaddress generation
  • Transaction confirmation tracking
  • Integration with go-monero-rpc-client
Core Features
  • AES-256-GCM encrypted wallet storage
  • Secure key derivation using HMAC-SHA512
  • Basic error handling
  • Thread-safe operations with mutex protection
  • Automatic API endpoint selection and failover

Installation

go get github.com/opd-ai/paywall/wallet

Usage Examples

Bitcoin HD Wallet
// Create a new Bitcoin HD wallet
seed := make([]byte, 32)
rand.Read(seed)
btcWallet, err := wallet.NewBTCHDWallet(seed, false) // false for mainnet
if err != nil {
    log.Fatal(err)
}

// Generate new address
address, err := btcWallet.GetAddress()
if err != nil {
    log.Fatal(err)
}

// Check balance
balance, err := btcWallet.GetAddressBalance(address)
if err != nil {
    log.Fatal(err)
}
Monero Wallet
// Create a new Monero wallet
config := wallet.MoneroConfig{
    RPCURL:      "http://localhost:18081",
    RPCUser:     "user",
    RPCPassword: "password",
}

xmrWallet, err := wallet.NewMoneroWallet(config)
if err != nil {
    log.Fatal(err)
}

// Generate new address
address, err := xmrWallet.GetAddress()
if err != nil {
    log.Fatal(err)
}
Secure Storage
// Generate encryption key
key, err := wallet.GenerateEncryptionKey()
if err != nil {
    log.Fatal(err)
}

// Configure storage
config := wallet.StorageConfig{
    DataDir:       "/path/to/wallets",
    EncryptionKey: key,
}

// Save wallet
err = btcWallet.SaveToFile(config)
if err != nil {
    log.Fatal(err)
}

// Load wallet
loadedWallet, err := wallet.LoadFromFile(config)
if err != nil {
    log.Fatal(err)
}

Project Structure

wallet/
├── address.go       # Bitcoin address handling and validation
├── base58.go        # Base58 encoding/decoding implementation
├── btc_hd_wallet.go # Bitcoin HD wallet implementation
├── hd_wallet.go     # Wallet interface definitions
├── storage.go       # Encrypted storage implementation
└── xmr_hd_wallet.go # Monero wallet implementation

Security Features

Key Management
  • Master key generation using HMAC-SHA512
  • BIP32/44 compliant key derivation
  • AES-256-GCM encryption for stored data
  • Secure random number generation for encryption keys
Network Security
  • Multiple API endpoints with automatic failover
  • Local node priority with public node fallback
  • Support for both HTTP and HTTPS endpoints
  • Basic endpoint validation
Storage Security
  • AES-256-GCM encrypted wallet data
  • Random nonce generation for encryption
  • Basic file permissions management

Development Requirements

  • Go 1.19 or higher
  • Access to Bitcoin/Monero nodes for testing
  • Network connectivity for API access

Testing

go test ./wallet/... -v

Testing requirements:

  • Internet connectivity for API tests
  • Local or remote node access for wallet operations
  • Testnet access for integration tests

Contributing

  1. Fork the repository
  2. Create your feature branch
  3. Write tests for new functionality
  4. Commit your changes
  5. Push to the branch
  6. Submit a pull request

License

This project is available under the MIT License.

Disclaimer

This implementation is provided for educational purposes. Production use requires thorough security review and testing.

Documentation

Overview

Package wallet provides Bitcoin wallet functionality including address generation and encoding

Package wallet implements Bitcoin HD (Hierarchical Deterministic) wallet functionality according to BIP32, BIP44, and BIP49 specifications.

wallet/wallet.go

Package wallet implements secure storage functionality for HD wallets.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Base58Decode

func Base58Decode(input string) ([]byte, error)

Base58Decode converts a base58-encoded string back into bytes.

Parameters:

  • input: Base58-encoded string to decode

Returns:

  • []byte: Decoded bytes
  • error: Invalid character error if input contains characters outside base58 alphabet

Error cases:

  • Returns error if input contains invalid base58 characters
  • Never returns error for empty input (returns empty byte slice)

Features:

  • Preserves leading zeros (encoded as '1' characters)
  • Validates all input characters
  • Handles arbitrary-length inputs via big.Int

Example:

decoded, err := Base58Decode("12f9b")
// decoded = []byte{0, 60, 23, 110}

Related: Base58Encode for reverse operation

func Base58Encode

func Base58Encode(input []byte) string

Base58Encode converts a byte slice into a base58-encoded string using Bitcoin's alphabet.

Parameters:

  • input: Raw bytes to encode

Returns:

  • string: Base58-encoded representation of the input

Features:

  • Preserves leading zeros in the input
  • Uses Bitcoin's specific base58 alphabet
  • Handles arbitrary-length inputs via big.Int

Example:

bytes := []byte{0, 60, 23, 110}
encoded := Base58Encode(bytes) // "12f9b"

Related: Base58Decode for reverse operation

func GenerateEncryptionKey

func GenerateEncryptionKey() ([]byte, error)

GenerateEncryptionKey creates a cryptographically secure 32-byte key suitable for AES-256 encryption.

Returns:

  • []byte: 32-byte random encryption key
  • error: If secure random number generation fails

Security:

  • Uses crypto/rand for secure random number generation
  • Generates sufficient entropy for AES-256

Usage:

key, err := GenerateEncryptionKey()
config := StorageConfig{
    DataDir: "/path/to/storage",
    EncryptionKey: key,
}

func IsBitcoinAddress

func IsBitcoinAddress(address string) (bool, string)

IsBitcoinAddress checks if a string is a valid Bitcoin address and returns whether it's a mainnet or testnet address, or "invalid" if the address is not valid.

Types

type Address

type Address string

Address represents a Bitcoin address and wraps a `string` to implement the btcutil.Address interface. It provides methods to encode the address, retrieve the raw bytes of the address, and check if the address is valid for a specific Bitcoin network (mainnet or testnet).

func (Address) EncodeAddress

func (a Address) EncodeAddress() string

EncodeAddress returns the string encoding of the payment address associated with the Address value. See the comment on String for how this method differs from String.

func (Address) IsForNet

func (a Address) IsForNet(params *chaincfg.Params) bool

IsForNet returns whether or not the address is associated with the passed bitcoin network.

func (Address) ScriptAddress

func (a Address) ScriptAddress() []byte

ScriptAddress returns the raw bytes of the address to be used when inserting the address into a txout's script.

func (Address) String

func (a Address) String() string

String returns the string encoding of the transaction output destination. Please note that String differs subtly from EncodeAddress: String will return the value as a string without any conversion, while EncodeAddress may convert destination types (for example, converting pubkeys to P2PKH addresses) before encoding as a payment address string.

type BTCHDWallet

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

BTCHDWallet represents a hierarchical deterministic Bitcoin wallet implementing BIP32 and BIP44 standards.

func LoadFromFile

func LoadFromFile(config StorageConfig) (*BTCHDWallet, error)

LoadFromFile loads and decrypts a wallet from a file.

Parameters:

  • config: StorageConfig containing storage location and encryption key

Returns:

  • *HDWallet: Decrypted wallet instance
  • error: If decryption fails, file is corrupt, or file operations fail

Security:

  • Validates data integrity using AES-GCM authentication
  • Verifies minimum data length requirements
  • Returns errors for any decryption failures

Related: SaveToFile

func NewBTCHDWallet

func NewBTCHDWallet(seed []byte, testnet bool) (*BTCHDWallet, error)

NewHDWallet creates a new HD wallet from a seed.

Parameters:

  • seed: Random seed bytes (must be 16-64 bytes)
  • testnet: Boolean flag for testnet/mainnet network selection

Returns:

  • *HDWallet: Initialized wallet instance
  • error: If seed length is invalid

Security:

  • Seed must be generated with sufficient entropy
  • Seed should be backed up securely

Related: DeriveNextAddress, GetAddress

func (*BTCHDWallet) Currency

func (w *BTCHDWallet) Currency() string

Currency implements HDWallet interface

func (*BTCHDWallet) DeriveNextAddress

func (w *BTCHDWallet) DeriveNextAddress() (string, error)

DeriveNextAddress derives the next Bitcoin address using BIP44 path m/44'/0'/0'/0/index

Returns:

  • string: Base58Check encoded Bitcoin address
  • error: If key derivation or address generation fails

Path components:

  • 44' : BIP44 purpose
  • 0' : Bitcoin coin type
  • 0' : Account 0
  • 0 : External chain
  • i : Address index

Related: GetAddress, pubKeyToAddress

func (*BTCHDWallet) GetAddress

func (w *BTCHDWallet) GetAddress() (string, error)

GetAddress returns the next available Bitcoin address.

Returns:

  • string: Base58Check encoded Bitcoin address
  • error: If address derivation fails

Notes:

  • Increments internal address counter
  • Thread-safe for single wallet instance

Related: DeriveNextAddress

func (*BTCHDWallet) GetAddressBalance

func (w *BTCHDWallet) GetAddressBalance(address string) (float64, error)

GetAddressBalance implements paywall.CryptoClient Returns the balance for a specific Bitcoin address.

Parameters:

  • address: Bitcoin address to check

Returns:

  • float64: Current balance in BTC
  • error: If address is invalid or query fails

Related: GetTransactionConfirmations

func (*BTCHDWallet) GetTransactionConfirmations

func (w *BTCHDWallet) GetTransactionConfirmations(txID string) (int, error)

GetTransactionConfirmations implements paywall.CryptoClient. Returns the number of confirmations for a specific transaction.

Parameters:

  • txID: Bitcoin transaction ID

Returns:

  • int: Number of confirmations
  • error: If transaction is not found or query fails

Related: GetAddressBalance

func (*BTCHDWallet) RecoverNextIndex

func (w *BTCHDWallet) RecoverNextIndex() error

func (*BTCHDWallet) SaveToFile

func (w *BTCHDWallet) SaveToFile(config StorageConfig) error

SaveToFile encrypts and saves the wallet to a file.

Parameters:

  • config: StorageConfig containing storage location and encryption key

Returns:

  • error: If encryption fails or file operations fail

Security:

  • Uses AES-256-GCM for encryption
  • Generates random nonce for each save
  • Sets restrictive file permissions (0600)

Related: LoadFromFile

type HDWallet

type HDWallet interface {
	DeriveNextAddress() (string, error)
	GetAddress() (string, error)
	Currency() string
	GetAddressBalance(address string) (float64, error)
	GetTransactionConfirmations(txID string) (int, error)
}

HDWallet defines the interface for cryptocurrency wallets

type MoneroConfig

type MoneroConfig struct {
	RPCURL      string
	RPCUser     string
	RPCPassword string
}

MoneroConfig holds Monero wallet RPC connection details

type MoneroHDWallet

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

MoneroHDWallet implements the HDWallet interface for Monero using RPC

func NewMoneroWallet

func NewMoneroWallet(config MoneroConfig) (*MoneroHDWallet, error)

NewMoneroWallet creates a new Monero wallet instance

func (*MoneroHDWallet) Currency

func (w *MoneroHDWallet) Currency() string

Currency implements HDWallet interface

func (*MoneroHDWallet) DeriveNextAddress

func (w *MoneroHDWallet) DeriveNextAddress() (string, error)

DeriveNextAddress implements HDWallet interface by creating a new subaddress

func (*MoneroHDWallet) GetAddress

func (w *MoneroHDWallet) GetAddress() (string, error)

GetAddress implements HDWallet interface by deriving next address

func (*MoneroHDWallet) GetAddressBalance

func (w *MoneroHDWallet) GetAddressBalance(address string) (float64, error)

GetAddressBalance implements paywall.CryptoClient by getting balance for specific address

func (*MoneroHDWallet) GetTransactionConfirmations

func (w *MoneroHDWallet) GetTransactionConfirmations(txID string) (int, error)

GetTransactionConfirmations implements paywall.CryptoClient.

type StorageConfig

type StorageConfig struct {
	DataDir       string
	EncryptionKey []byte // 32-byte key for AES-256
}

StorageConfig defines configuration parameters for wallet storage operations.

Fields:

  • DataDir: Directory path where wallet files will be stored
  • EncryptionKey: 32-byte key used for AES-256 encryption

Security:

  • DataDir should have appropriate filesystem permissions
  • EncryptionKey must be securely generated and stored

type WalletType

type WalletType string

WalletType identifies the cryptocurrency wallet implementation

const (
	Bitcoin WalletType = "BTC"
	Monero  WalletType = "XMR"
)

Jump to

Keyboard shortcuts

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