address

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Dec 11, 2016 License: BSD-3-Clause Imports: 15 Imported by: 0

README

Build Status GoDoc GitHub license

address

Overview

This library is for handling bitcoin address, including generate private keys from wif, sign/vefiry, serializing, BIP32(Hierarchical Deterministic Bitcoin addresses) and BIP39(mnemonic seed).

Requirements

This requires

  • git
  • go 1.3+

Installation

 $ go get github.com/bitgoin/address

Example

(This example omits error handlings for simplicity.)


import "github.com/bitgoin/address"

func main(){
	key, err := address.Generate(BitcoinTest)
	adr := key.PublicKey.Address()
    key2, err := address.FromWIF(wif, BitcoinTest)
	data := []byte("test data")
	sig, err := private.Sign(data)
	err = key.PublicKey.Verify(sig, data)

    seed, err := address.GenerateSeed(address.RecommendedSeedLen)
	master, err := address.NewMasterKey(seed,address.BitcoinTest)
    derivate,err := master.Child(0)
	priv,err:=derivate.PrivKey()
	derivatepub,err:=derivate.Neuter()
	pub,err:=derivatepub.PubKey()

    entropy, err := address.NewEntropy(256)
    mnemonic, err := address.NewMnemonic(entropy)
    seed := address.NewSeed(mnemonic, "Secret Passphrase")

	..
}

Contribution

Improvements to the codebase and pull requests are encouraged.

Documentation

Index

Constants

View Source
const (
	// RecommendedSeedLen is the recommended length in bytes for a seed
	// to a master node.
	RecommendedSeedLen = 32 // 256 bits

	// HardenedKeyStart is the index at which a hardended key starts.  Each
	// extended key has 2^31 normal child keys and 2^31 hardned child keys.
	// Thus the range for normal child keys is [0, 2^31 - 1] and the range
	// for hardened child keys is [2^31, 2^32 - 1].
	HardenedKeyStart = 0x80000000 // 2^31

	// MinSeedBytes is the minimum number of bytes allowed for a seed to
	// a master node.
	MinSeedBytes = 16 // 128 bits

	// MaxSeedBytes is the maximum number of bytes allowed for a seed to
	// a master node.
	MaxSeedBytes = 64 // 512 bits

)

Variables

View Source
var (
	// ErrDeriveHardFromPublic describes an error in which the caller
	// attempted to derive a hardened extended key from a public key.
	ErrDeriveHardFromPublic = errors.New("cannot derive a hardened key " +
		"from a public key")

	// ErrNotPrivExtKey describes an error in which the caller attempted
	// to extract a private key from a public extended key.
	ErrNotPrivExtKey = errors.New("unable to create private keys from a " +
		"public extended key")

	// ErrInvalidChild describes an error in which the child at a specific
	// index is invalid due to the derived key falling outside of the valid
	// range for secp256k1 private keys.  This error indicates the caller
	// should simply ignore the invalid child extended key at this index and
	// increment to the next index.
	ErrInvalidChild = errors.New("the extended key at this index is invalid")

	// ErrUnusableSeed describes an error in which the provided seed is not
	// usable due to the derived key falling outside of the valid range for
	// secp256k1 private keys.  This error indicates the caller must choose
	// another seed.
	ErrUnusableSeed = errors.New("unusable seed")

	// ErrInvalidSeedLen describes an error in which the provided seed or
	// seed length is not in the allowed range.
	ErrInvalidSeedLen = fmt.Errorf("seed length must be between %d and %d "+
		"bits", MinSeedBytes*8, MaxSeedBytes*8)

	// ErrBadChecksum describes an error in which the checksum encoded with
	// a serialized extended key does not match the calculated value.
	ErrBadChecksum = errors.New("bad extended key checksum")

	// ErrInvalidKeyLen describes an error in which the provided serialized
	// key is not the expected length.
	ErrInvalidKeyLen = errors.New("the provided serialized extended key " +
		"length is invalid")
)
View Source
var (
	//BitcoinMain is params for main net.
	BitcoinMain = &Params{
		DumpedPrivateKeyHeader: []byte{128},
		AddressHeader:          0,
		P2SHHeader:             5,
		HDPrivateKeyID:         []byte{0x04, 0x88, 0xad, 0xe4},
		HDPublicKeyID:          []byte{0x04, 0x88, 0xb2, 0x1e},
	}
	//BitcoinTest is params for test net.
	BitcoinTest = &Params{
		DumpedPrivateKeyHeader: []byte{239},
		AddressHeader:          111,
		P2SHHeader:             196,
		HDPrivateKeyID:         []byte{0x04, 0x35, 0x83, 0x94},
		HDPublicKeyID:          []byte{0x04, 0x35, 0x87, 0xcf},
	}
	//MonacoinMain is params for monacoin main net.
	MonacoinMain = &Params{
		DumpedPrivateKeyHeader: []byte{178, 176},
		AddressHeader:          50,
		P2SHHeader:             5,
		HDPrivateKeyID:         []byte{0x04, 0x88, 0xad, 0xe4},
		HDPublicKeyID:          []byte{0x04, 0x88, 0xb2, 0x1e},
	}
)

Functions

func Address

func Address(redeem []byte, header byte) string

Address returns ripeme160(sha256(redeem)) (address of redeem script).

func AddressBytes

func AddressBytes(redeem []byte) []byte

AddressBytes returns ripeme160(sha256(redeem)) (address of redeem script).

func DecodeAddress

func DecodeAddress(addr string) ([]byte, error)

DecodeAddress converts bitcoin address to hex form.

func GenerateSeed

func GenerateSeed(length uint8) ([]byte, error)

GenerateSeed returns a cryptographically secure random seed that can be used as the input for the NewMaster function to generate a new master node.

The length is in bytes and it must be between 16 and 64 (128 to 512 bits). The recommended length is 32 (256 bits) as defined by the RecommendedSeedLen constant.

func IsMnemonicValid

func IsMnemonicValid(mnemonic string) bool

IsMnemonicValid attempts to verify that the provided mnemonic is valid. Validity is determined by both the number of words being appropriate, and that all the words in the mnemonic are present in the word list.

func MnemonicToByteArray

func MnemonicToByteArray(mnemonic string) ([]byte, error)

MnemonicToByteArray takes a mnemonic string and turns it into a byte array suitable for creating another mnemonic. An error is returned if the mnemonic is invalid. FIXME This does not work for all values in the test vectors. Namely Vectors 0, 4, and 8. This is not really important because BIP39 doesnt really define a conversion from string to bytes.

func NewEntropy

func NewEntropy(bitSize int) ([]byte, error)

NewEntropy will create random entropy bytes so long as the requested size bitSize is an appropriate size.

func NewMnemonic

func NewMnemonic(entropy []byte) (string, error)

NewMnemonic will return a string consisting of the mnemonic words for the given entropy. If the provide entropy is invalid, an error will be returned.

func NewSeed

func NewSeed(mnemonic string, password string) []byte

NewSeed creates a hashed seed output given a provided string and password. No checking is performed to validate that the string provided is a valid mnemonic.

func NewSeedWithErrorChecking

func NewSeedWithErrorChecking(mnemonic string, password string) ([]byte, error)

NewSeedWithErrorChecking creates a hashed seed output given the mnemonic string and a password. An error is returned if the mnemonic is not convertible to a byte array.

Types

type ExtendedKey

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

ExtendedKey houses all the information needed to support a hierarchical deterministic extended key. See the package overview documentation for more details on how to use extended keys.

func NewKeyFromString

func NewKeyFromString(key string, param *Params) (*ExtendedKey, error)

NewKeyFromString returns a new extended key instance from a base58-encoded extended key.

func NewMaster

func NewMaster(seed []byte, param *Params) (*ExtendedKey, error)

NewMaster creates a new master node for use in creating a hierarchical deterministic key chain. The seed must be between 128 and 512 bits and should be generated by a cryptographically secure random generation source.

NOTE: There is an extremely small chance (< 1 in 2^127) the provided seed will derive to an unusable secret key. The ErrUnusable error will be returned if this should occur, so the caller must check for it and generate a new seed accordingly.

func (*ExtendedKey) Child

func (k *ExtendedKey) Child(i uint32) (*ExtendedKey, error)

Child returns a derived child extended key at the given index. When this extended key is a private extended key (as determined by the IsPrivate function), a private extended key will be derived. Otherwise, the derived extended key will be also be a public extended key.

When the index is greater to or equal than the HardenedKeyStart constant, the derived extended key will be a hardened extended key. It is only possible to derive a hardended extended key from a private extended key. Consequently, this function will return ErrDeriveHardFromPublic if a hardened child extended key is requested from a public extended key.

A hardened extended key is useful since, as previously mentioned, it requires a parent private extended key to derive. In other words, normal child extended public keys can be derived from a parent public extended key (no knowledge of the parent private key) whereas hardened extended keys may not be.

NOTE: There is an extremely small chance (< 1 in 2^127) the specific child index does not derive to a usable child. The ErrInvalidChild error will be returned if this should occur, and the caller is expected to ignore the invalid child and simply increment to the next index.

func (*ExtendedKey) IsPrivate

func (k *ExtendedKey) IsPrivate() bool

IsPrivate returns whether or not the extended key is a private extended key.

A private extended key can be used to derive both hardened and non-hardened child private and public extended keys. A public extended key can only be used to derive non-hardened child public extended keys.

func (*ExtendedKey) Neuter

func (k *ExtendedKey) Neuter() (*ExtendedKey, error)

Neuter returns a new extended public key from this extended private key. The same extended key will be returned unaltered if it is already an extended public key.

As the name implies, an extended public key does not have access to the private key, so it is not capable of signing transactions or deriving child extended private keys. However, it is capable of deriving further child extended public keys.

func (*ExtendedKey) ParentFingerprint

func (k *ExtendedKey) ParentFingerprint() uint32

ParentFingerprint returns a fingerprint of the parent extended key from which this one was derived.

func (*ExtendedKey) PrivKey

func (k *ExtendedKey) PrivKey() (*PrivateKey, error)

PrivKey converts the extended key to a btcec private key and returns it. As you might imagine this is only possible if the extended key is a private extended key (as determined by the IsPrivate function). The ErrNotPrivExtKey error will be returned if this function is called on a public extended key.

func (*ExtendedKey) PubKey

func (k *ExtendedKey) PubKey() (*PublicKey, error)

PubKey converts the extended key to a btcec public key and returns it.

func (*ExtendedKey) String

func (k *ExtendedKey) String() string

String returns the extended key as a human-readable base58-encoded string.

func (*ExtendedKey) Zero

func (k *ExtendedKey) Zero()

Zero manually clears all fields and bytes in the extended key. This can be used to explicitly clear key material from memory for enhanced security against memory scraping. This function only clears this particular key and not any children that have already been derived.

type Params

type Params struct {
	DumpedPrivateKeyHeader []byte
	AddressHeader          byte
	P2SHHeader             byte
	HDPrivateKeyID         []byte
	HDPublicKeyID          []byte
}

Params is parameters of the coin.

type PrivateKey

type PrivateKey struct {
	*btcec.PrivateKey
	PublicKey *PublicKey
}

PrivateKey represents private key for bitcoin

func FromWIF

func FromWIF(wif string, param *Params) (*PrivateKey, error)

FromWIF gets PublicKey and PrivateKey from private key of WIF format.

func Generate

func Generate(param *Params) (*PrivateKey, error)

Generate generates random PublicKey and PrivateKey.

func NewPrivateKey

func NewPrivateKey(pb []byte, param *Params) *PrivateKey

NewPrivateKey creates and returns PrivateKey from bytes.

func (*PrivateKey) Sign

func (priv *PrivateKey) Sign(hash []byte) ([]byte, error)

Sign sign data.

func (*PrivateKey) WIFAddress

func (priv *PrivateKey) WIFAddress() string

WIFAddress returns WIF format string from PrivateKey

type PublicKey

type PublicKey struct {
	*btcec.PublicKey
	// contains filtered or unexported fields
}

PublicKey represents public key for bitcoin

func NewPublicKey

func NewPublicKey(pubKeyByte []byte, param *Params) (*PublicKey, error)

NewPublicKey returns PublicKey struct using public key hex string.

func (*PublicKey) Address

func (pub *PublicKey) Address() string

Address returns bitcoin address from PublicKey

func (*PublicKey) AddressBytes

func (pub *PublicKey) AddressBytes() []byte

AddressBytes returns bitcoin address bytes from PublicKey

func (*PublicKey) Serialize

func (pub *PublicKey) Serialize() []byte

Serialize serializes public key depending on isCompressed.

func (*PublicKey) Verify

func (pub *PublicKey) Verify(signature []byte, data []byte) error

Verify verifies signature is valid or not.

Directories

Path Synopsis
Package base58 implements a human-friendly base58 encoding.
Package base58 implements a human-friendly base58 encoding.
Package btcec implements support for the elliptic curves needed for bitcoin.
Package btcec implements support for the elliptic curves needed for bitcoin.

Jump to

Keyboard shortcuts

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