p2pkh

package module
v0.0.0-...-02e0af6 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2024 License: GPL-3.0 Imports: 8 Imported by: 0

README

P2PKH Wallet Implementation

This repository contains an implementation of a hierarchical deterministic (HD) Bitcoin wallet based on the BIP44 standard for generating P2PKH (Pay-to-PubKey-Hash) addresses. The wallet supports both Mainnet and Testnet networks, and provides various utility functions for generating keys, addresses, and validating them.

Features

  • Mnemonic-based wallet generation (BIP39)
  • Hierarchical Deterministic (HD) keys (BIP44)
  • Support for Mainnet and Testnet
  • Public and private key derivation
  • Address generation and validation
  • Extended public key (xpub) support
  • Wallet Import Format (WIF) for private keys

Table of Contents

Installation

To use this package, you will need to have Go installed on your system. You can install the package using go get:

go get github.com/ariden83/p2pkh.go

Then, import it in your Go code:

import "github.com/ariden83/p2pkh.go"

Usage

You can create a new wallet by providing a mnemonic, network type, and a derivation path.

Example of creating a new wallet:
package main

import (
    "fmt"
    "github.com/ariden83/p2pkh.go"
)

func main() {
    config := &p2pkh.Config{
        Mnemonic: "romance trash engine during cliff verify tunnel memory vault chief fluid fox",
        Path:     `m/44'/0'/0'/0/0`,  // Mainnet derivation path
        Network:  p2pkh.NetworkMainnet,
    }

    wallet, err := p2pkh.New(config)
    if err != nil {
        fmt.Println("Error creating wallet:", err)
        return
    }

    fmt.Println("Address:", wallet.AddressHex())
    fmt.Println("Public Key:", wallet.PublicKey())
    fmt.Println("Mnemonic:", wallet.Mnemonic())
}

Configuration

Config Struct

The Config struct is used to create a new wallet. It requires the following fields:

  • Mnemonic: A valid BIP39 mnemonic phrase.
  • Path: The derivation path (e.g., m/44'/0'/0'/0/0 for Bitcoin Mainnet).
  • Network: Either NetworkMainnet or NetworkTestnet.
Example:
config := &p2pkh.Config{
    Mnemonic: "romance trash engine during cliff verify tunnel memory vault chief fluid fox",
    Path:     `m/44'/1'/0'/0/0`,  // Testnet derivation path
    Network:  p2pkh.NetworkTestnet,
}

Wallet Methods

The Wallet struct provides the following methods:

  • PublicKey(): Returns the wallet's ECDSA public key.
  • PrivateKey(): Returns the wallet's private key in Wallet Import Format (WIF).
  • Address(): Returns the wallet's P2PKH Bitcoin address (native btcutil format).
  • AddressHex(): Returns the wallet's Bitcoin address in a hexadecimal string format.
  • ValidateAddress(address string): Validates if the provided address belongs to the current network.
  • ExtendedPublicKey(): Returns the extended public key (xpub).
  • Derive(index interface{}): Derives a new wallet based on the provided index from the current wallet.
Example: Retrieving the Private Key
privateKey, err := wallet.PrivateKey()
if err != nil {
fmt.Println("Error retrieving private key:", err)
} else {
fmt.Println("Private Key (WIF):", privateKey)
}
Example: Validating an Address
isValid, err := wallet.ValidateAddress("1QHTz6wMURLy8DT6aeGAVbF2UvtuWZKozr")
if err != nil {
fmt.Println("Error validating address:", err)
} else if isValid {
fmt.Println("Address is valid")
} else {
fmt.Println("Address is invalid")
}

Testing

The package includes a set of unit tests that can be run using the go test command. The tests cover the core functionality of the wallet, including key and address generation, derivation paths, and validation.

To run the tests, simply run:

go test ./...

Example Test

func Test_InvalidMnemonic(t *testing.T) {
config := &p2pkh.Config{
Mnemonic: "invalid mnemonic phrase",
Path:     `m/44'/0'/0'/0`,
Network:  p2pkh.NetworkMainnet,
}

    wallet, err := p2pkh.New(config)
    assert.Nil(t, wallet)
    assert.EqualError(t, err, p2pkh.ErrInvalidMnemonic)
}

Contributing

If you'd like to contribute to this project, feel free to submit a pull request or open an issue on GitHub.

License

This project is licensed under the MIT License.

Documentation

Index

Constants

View Source
const (
	NetworkMainnet Network = "mainnet"
	NetworkTestnet Network = "testnet"

	ErrInvalidMnemonic  = "mnemonic is required"
	ErrUnsupportedNet   = "unsupported network type: choose either 'mainnet' or 'testnet'"
	ErrInvalidPath      = "failed to parse derivation path"
	ErrKeyDerivation    = "failed to derive key"
	ErrIndexNegative    = "index cannot be negative"
	ErrUnsupportedIndex = "unsupported index type"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	Mnemonic string
	Path     string
	Network  Network
}

Config represents the configuration necessary to create a Wallet.

type Network

type Network string

Network represents the type of blockchain network the wallet operates on. It can either be "mainnet" for the production Bitcoin network or "testnet" for the test Bitcoin network, allowing for separate configurations and behaviors for each network.

type Wallet

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

Wallet represents an HD wallet.

func New

func New(config *Config) (*Wallet, error)

New creates a new Wallet from a configuration.

func (*Wallet) Address

func (s *Wallet) Address() *btcutil.AddressPubKey

Address returns the Bitcoin P2PKH address (AddressPubKey) associated with the wallet's public key. This address is in the native format of the btcutil library.

func (*Wallet) AddressHex

func (s *Wallet) AddressHex() string

AddressHex returns the Bitcoin address in its encoded hexadecimal string format. This is a human-readable format used for transactions and sharing the address.

func (*Wallet) Derive

func (s *Wallet) Derive(index interface{}) (*Wallet, error)

Derive derives a new portfolio from an index.

func (*Wallet) ExtendedPublicKey

func (s *Wallet) ExtendedPublicKey() (string, error)

ExtendedPublicKey returns the wallet's extended public key (xpub).

func (*Wallet) Mnemonic

func (s *Wallet) Mnemonic() string

Mnemonic returns the mnemonic phrase used to generate the wallet.

func (*Wallet) Path

func (s *Wallet) Path() string

Path returns the derivation path used to generate the wallet.

func (*Wallet) PrivateKey

func (s *Wallet) PrivateKey() (string, error)

PrivateKey returns the private key associated with the wallet in WIF (Wallet Import Format).

func (*Wallet) PublicKey

func (s *Wallet) PublicKey() *btcec.PublicKey

PublicKey returns the public key (ECDSA) associated with the wallet.

func (*Wallet) ValidateAddress

func (s *Wallet) ValidateAddress(address string) (bool, error)

ValidateAddress checks if the provided address is valid for the current network.

Jump to

Keyboard shortcuts

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