bitcoin

package module
v2.0.5 Latest Latest
Warning

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

Go to latest
Published: Aug 3, 2023 License: MIT Imports: 20 Imported by: 22

README

go-bitcoin

A library for working with Bitcoin (BSV) transactions, addresses, keys, encryption, and more.

Release Build Status Report codecov Go
Gitpod Ready-to-Code Mergify Status Sponsor Donate


Table of Contents


Installation

go-bitcoin requires a supported release of Go.

go get -u github.com/bitcoinschema/go-bitcoin/v2

If you want to install the deprecated V1:

go get -u github.com/bitcoinschema/go-bitcoin@v1

Documentation

View the generated documentation

GoDoc

Features
Package Dependencies
Library Deployment

goreleaser for easy binary or library deployment to GitHub and can be installed via: brew install goreleaser.

The .goreleaser.yml file is used to configure goreleaser.

Use make release-snap to create a snapshot version of the release, and finally make release to ship to production.

Makefile Commands

View all makefile commands

make help

List of all current commands:

all                   Runs multiple commands
clean                 Remove previous builds and any test cache data
clean-mods            Remove all the Go mod cache
coverage              Shows the test coverage
diff                  Show the git diff
generate              Runs the go generate command in the base of the repo
godocs                Sync the latest tag with GoDocs
help                  Show this help message
install               Install the application
install-go            Install the application (Using Native Go)
install-releaser      Install the GoReleaser application
lint                  Run the golangci-lint application (install if not found)
release               Full production release (creates release in GitHub)
release               Runs common.release then runs godocs
release-snap          Test the full release (build binaries)
release-test          Full production test release (everything except deploy)
replace-version       Replaces the version in HTML/JS (pre-deploy)
tag                   Generate a new tag and push (tag version=0.0.0)
tag-remove            Remove a tag if found (tag-remove version=0.0.0)
tag-update            Update an existing tag to current commit (tag-update version=0.0.0)
test                  Runs lint and ALL tests
test-ci               Runs all tests via CI (exports coverage)
test-ci-no-race       Runs all tests via CI (no race) (exports coverage)
test-ci-short         Runs unit tests via CI (exports coverage)
test-no-lint          Runs just tests
test-short            Runs vet, lint and tests (excludes integration tests)
test-unit             Runs tests and outputs coverage
uninstall             Uninstall the application (and remove files)
update-linter         Update the golangci-lint package (macOS only)
vet                   Run the Go vet application

Examples & Tests

All unit tests and examples run via GitHub Actions and uses Go version 1.18.x. View the configuration file.

Run all tests (including integration tests)

make test

Run tests (excluding integration tests)

make test-short

Benchmarks

Run the Go benchmarks:

make bench

Code Standards

Read more about this Go project's code standards.


Usage

Checkout all the examples!


Maintainers

MrZ MrZ
MrZ Satchmo

Contributing

View the contributing guidelines and follow the code of conduct.

How can I help?

All kinds of contributions are welcome 🙌! The most basic way to show your support is to star 🌟 the project, or to raise issues 💬. You can also support this project by becoming a sponsor on GitHub 👏 or by making a bitcoin donation to ensure this journey continues indefinitely! 🚀

Stars


License

License

Documentation

Overview

Package bitcoin is a small collection of utility functions for working with Bitcoin (BSV)

If you have any suggestions or comments, please feel free to open an issue on this GitHub repository!

By BitcoinSchema Organization (https://bitcoinschema.org)

Index

Examples

Constants

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

	// SecureSeedLength is the max size of a seed length (most secure)
	SecureSeedLength = 64 // 512 bits

	// DefaultExternalChain is the default external chain (for public use to accept incoming txs)
	// Reference: https://en.bitcoin.it/wiki/BIP_0032#The_default_wallet_layout
	DefaultExternalChain = 0

	// DefaultInternalChain is the default internal chain (for change, generating, other purposes...)
	// Reference: https://en.bitcoin.it/wiki/BIP_0032#The_default_wallet_layout
	DefaultInternalChain = 1
)
View Source
const (

	// DustLimit is the minimum value for a tx that can be spent
	// Note: this is being deprecated in the new node software (TBD)
	DustLimit uint64 = 546
)

Variables

View Source
var ErrBadCharacter = errors.New("bad char")

ErrBadCharacter is returned when a bad character is found

View Source
var ErrChangeAddressRequired = errors.New("change address is required")

ErrChangeAddressRequired is returned when a change address is required to create a tx

View Source
var ErrMissingAddress = errors.New("missing address")

ErrMissingAddress is returned when an address is missing

View Source
var ErrMissingPubKey = errors.New("missing pubkey")

ErrMissingPubKey is returned when a pubkey is missing

View Source
var ErrMissingScript = errors.New("missing script")

ErrMissingScript is returned when a script is missing

View Source
var ErrNotVersion0 = errors.New("not version 0")

ErrNotVersion0 is returned when a string is not version 0

View Source
var ErrPrivateKeyMissing = errors.New("private key is missing")

ErrPrivateKeyMissing is returned when a private key is missing

View Source
var ErrTooLong = errors.New("too long")

ErrTooLong is returned when a string is too long

View Source
var ErrUtxosRequired = errors.New("utxo(s) are required to create a tx")

ErrUtxosRequired is returned when utxos are required to create a tx

View Source
var ErrWifMissing = errors.New("wif is missing")

ErrWifMissing is returned when a wif is missing

Functions

func CalculateFeeForTx

func CalculateFeeForTx(tx *bt.Tx, standardRate, dataRate *bt.Fee) uint64

CalculateFeeForTx will estimate a fee for the given transaction

If tx is nil this will panic Rate(s) can be derived from MinerAPI (default is DefaultDataRate and DefaultStandardRate) If rate is nil it will use default rates (0.5 sat per byte) Reference: https://tncpw.co/c215a75c

Example

ExampleCalculateFeeForTx example using CalculateFeeForTx()

// Get the tx from hex string
rawTx := "0100000001760595866e99c1ce920197844740f5598b34763878696371d41b3a7c0a65b0b7000000006b483045022100e07b7661af4e4b521c012a146b25da2c7b9d606e9ceaae28fa73eb347ef6da6f0220527f0638a89ff11cbe53d5f8c4c2962484a370dcd9463a6330f45d31247c2512412102ea87d1fd77d169bd56a71e700628113d0f8dfe57faa0ba0e55a36f9ce8e10be3ffffffff0364030000000000001976a9147a1980655efbfec416b2b0c663a7b3ac0b6a25d288ac00000000000000001a006a07707265666978310c6578616d706c65206461746102133700000000000000001c006a0770726566697832116d6f7265206578616d706c65206461746100000000"
tx, err := TxFromHex(rawTx)
if err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}

// Calculate the fee using default rates
estimatedFee := CalculateFeeForTx(tx, nil, nil)

fmt.Printf("tx id: %s estimated fee: %d satoshis", tx.TxID(), estimatedFee)
Output:

tx id: e75fa79ee5fbb589201f769c01835e14ca595b7bbfa0e602050a2a90cf28d129 estimated fee: 132 satoshis

func CreatePrivateKey

func CreatePrivateKey() (*bec.PrivateKey, error)

CreatePrivateKey will create a new private key (*bec.PrivateKey)

Example

ExampleCreatePrivateKey example using CreatePrivateKey()

rawKey, err := CreatePrivateKey()
if err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
} else if len(rawKey.Serialise()) > 0 {
	fmt.Printf("key created successfully!")
}
Output:

key created successfully!

func CreatePrivateKeyString

func CreatePrivateKeyString() (string, error)

CreatePrivateKeyString will create a new private key (hex encoded)

Example

ExampleCreatePrivateKeyString example using CreatePrivateKeyString()

key, err := CreatePrivateKeyString()
if err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
} else if len(key) > 0 {
	fmt.Printf("key created successfully!")
}
Output:

key created successfully!

func CreateTx

func CreateTx(utxos []*Utxo, addresses []*PayToAddress,
	opReturns []OpReturnData, privateKey *bec.PrivateKey) (*bt.Tx, error)

CreateTx will create a basic transaction and return the raw transaction (*transaction.Transaction)

Note: this will NOT create a change output (funds are sent to "addresses") Note: this will NOT handle fee calculation (it's assumed you have already calculated the fee)

Get the raw hex version: tx.ToString() Get the tx id: tx.GetTxID()

Example

ExampleCreateTx example using CreateTx()

// Use a new UTXO
utxo := &Utxo{
	TxID:         "b7b0650a7c3a1bd4716369783876348b59f5404784970192cec1996e86950576",
	Vout:         0,
	ScriptPubKey: "76a9149cbe9f5e72fa286ac8a38052d1d5337aa363ea7f88ac",
	Satoshis:     1000,
}

// Add a pay-to address
payTo := &PayToAddress{
	Address:  "1C8bzHM8XFBHZ2ZZVvFy2NSoAZbwCXAicL",
	Satoshis: 500,
}

// Add some op return data
opReturn1 := OpReturnData{[]byte("prefix1"), []byte("example data"), []byte{0x13, 0x37}}
opReturn2 := OpReturnData{[]byte("prefix2"), []byte("more example data")}

// Private key (from wif)
privateKey, err := WifToPrivateKey("L3VJH2hcRGYYG6YrbWGmsxQC1zyYixA82YjgEyrEUWDs4ALgk8Vu")
if err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}

// Generate the TX
rawTx, err := CreateTx(
	[]*Utxo{utxo},
	[]*PayToAddress{payTo},
	[]OpReturnData{opReturn1, opReturn2},
	privateKey,
)
if err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}

fmt.Printf("rawTx: %s", rawTx.String())
Output:

rawTx: 0100000001760595866e99c1ce920197844740f5598b34763878696371d41b3a7c0a65b0b7000000006b483045022100eea3d606bd1627be6459a9de4860919225db74843d2fc7f4e7caa5e01f42c2d0022017978d9c6a0e934955a70e7dda71d68cb614f7dd89eb7b9d560aea761834ddd4412102ea87d1fd77d169bd56a71e700628113d0f8dfe57faa0ba0e55a36f9ce8e10be3ffffffff03f4010000000000001976a9147a1980655efbfec416b2b0c663a7b3ac0b6a25d288ac00000000000000001a006a07707265666978310c6578616d706c65206461746102133700000000000000001c006a0770726566697832116d6f7265206578616d706c65206461746100000000

func CreateTxUsingWif

func CreateTxUsingWif(utxos []*Utxo, addresses []*PayToAddress,
	opReturns []OpReturnData, wif string) (*bt.Tx, error)

CreateTxUsingWif will create a basic transaction and return the raw transaction (*transaction.Transaction)

Note: this will NOT create a "change" address (it's assumed you have already specified an address) Note: this will NOT handle "fee" calculation (it's assumed you have already calculated the fee)

Get the raw hex version: tx.ToString() Get the tx id: tx.GetTxID()

Example

ExampleCreateTxUsingWif example using CreateTxUsingWif()

// Use a new UTXO
utxo := &Utxo{
	TxID:         "b7b0650a7c3a1bd4716369783876348b59f5404784970192cec1996e86950576",
	Vout:         0,
	ScriptPubKey: "76a9149cbe9f5e72fa286ac8a38052d1d5337aa363ea7f88ac",
	Satoshis:     1000,
}

// Add a pay-to address
payTo := &PayToAddress{
	Address:  "1C8bzHM8XFBHZ2ZZVvFy2NSoAZbwCXAicL",
	Satoshis: 500,
}

// Add some op return data
opReturn1 := OpReturnData{[]byte("prefix1"), []byte("example data"), []byte{0x13, 0x37}}
opReturn2 := OpReturnData{[]byte("prefix2"), []byte("more example data")}

// Generate the TX
rawTx, err := CreateTxUsingWif(
	[]*Utxo{utxo},
	[]*PayToAddress{payTo},
	[]OpReturnData{opReturn1, opReturn2},
	"L3VJH2hcRGYYG6YrbWGmsxQC1zyYixA82YjgEyrEUWDs4ALgk8Vu",
)
if err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}

fmt.Printf("rawTx: %s", rawTx.String())
Output:

rawTx: 0100000001760595866e99c1ce920197844740f5598b34763878696371d41b3a7c0a65b0b7000000006b483045022100eea3d606bd1627be6459a9de4860919225db74843d2fc7f4e7caa5e01f42c2d0022017978d9c6a0e934955a70e7dda71d68cb614f7dd89eb7b9d560aea761834ddd4412102ea87d1fd77d169bd56a71e700628113d0f8dfe57faa0ba0e55a36f9ce8e10be3ffffffff03f4010000000000001976a9147a1980655efbfec416b2b0c663a7b3ac0b6a25d288ac00000000000000001a006a07707265666978310c6578616d706c65206461746102133700000000000000001c006a0770726566697832116d6f7265206578616d706c65206461746100000000

func CreateTxWithChange

func CreateTxWithChange(utxos []*Utxo, payToAddresses []*PayToAddress, opReturns []OpReturnData,
	changeAddress string, standardRate, dataRate *bt.Fee,
	privateKey *bec.PrivateKey) (*bt.Tx, error)

CreateTxWithChange will automatically create the change output and calculate fees

Use this if you don't want to figure out fees/change for a tx USE AT YOUR OWN RISK - this will modify a "pay-to" output to accomplish auto-fees

Example

ExampleCreateTxWithChange example using CreateTxWithChange()

// Use a new UTXO
utxo := &Utxo{
	TxID:         "b7b0650a7c3a1bd4716369783876348b59f5404784970192cec1996e86950576",
	Vout:         0,
	ScriptPubKey: "76a9149cbe9f5e72fa286ac8a38052d1d5337aa363ea7f88ac",
	Satoshis:     1000,
}

// Add a pay-to address
payTo := &PayToAddress{
	Address:  "1C8bzHM8XFBHZ2ZZVvFy2NSoAZbwCXAicL",
	Satoshis: 500,
}

// Add some op return data
opReturn1 := OpReturnData{[]byte("prefix1"), []byte("example data"), []byte{0x13, 0x37}}
opReturn2 := OpReturnData{[]byte("prefix2"), []byte("more example data")}

// Get private key from wif
privateKey, err := WifToPrivateKey("L3VJH2hcRGYYG6YrbWGmsxQC1zyYixA82YjgEyrEUWDs4ALgk8Vu")
if err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}

// Generate the TX
var rawTx *bt.Tx
rawTx, err = CreateTxWithChange(
	[]*Utxo{utxo},
	[]*PayToAddress{payTo},
	[]OpReturnData{opReturn1, opReturn2},
	"1KQG5AY9GrPt3b5xrFqVh2C3YEhzSdu4kc",
	nil,
	nil,
	privateKey,
)
if err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}

fmt.Printf("rawTx: %s", rawTx.String())
Output:

rawTx: 0100000001760595866e99c1ce920197844740f5598b34763878696371d41b3a7c0a65b0b7000000006b483045022100c1dc4a4c5f26a404ff3618013dc63777d0790d0b0ea3371c67ee3f1bb5126c3e02206be8c841918215337f9b6a6a6040bd058596f2bab5c8b8cb27f849b1474b9e4c412102ea87d1fd77d169bd56a71e700628113d0f8dfe57faa0ba0e55a36f9ce8e10be3ffffffff04f4010000000000001976a9147a1980655efbfec416b2b0c663a7b3ac0b6a25d288ac5f010000000000001976a914c9d8699bdea34b131e737447b50a8b1af0b040bf88ac00000000000000001a006a07707265666978310c6578616d706c65206461746102133700000000000000001c006a0770726566697832116d6f7265206578616d706c65206461746100000000

func CreateTxWithChangeUsingWif

func CreateTxWithChangeUsingWif(utxos []*Utxo, payToAddresses []*PayToAddress, opReturns []OpReturnData,
	changeAddress string, standardRate, dataRate *bt.Fee, wif string) (*bt.Tx, error)

CreateTxWithChangeUsingWif will automatically create the change output and calculate fees

Use this if you don't want to figure out fees/change for a tx USE AT YOUR OWN RISK - this will modify a "pay-to" output to accomplish auto-fees

Example

ExampleCreateTxWithChangeUsingWif example using CreateTxWithChangeUsingWif()

// Use a new UTXO
utxo := &Utxo{
	TxID:         "b7b0650a7c3a1bd4716369783876348b59f5404784970192cec1996e86950576",
	Vout:         0,
	ScriptPubKey: "76a9149cbe9f5e72fa286ac8a38052d1d5337aa363ea7f88ac",
	Satoshis:     1000,
}

// Add a pay-to address
payTo := &PayToAddress{
	Address:  "1C8bzHM8XFBHZ2ZZVvFy2NSoAZbwCXAicL",
	Satoshis: 500,
}

// Add some op return data
opReturn1 := OpReturnData{[]byte("prefix1"), []byte("example data"), []byte{0x13, 0x37}}
opReturn2 := OpReturnData{[]byte("prefix2"), []byte("more example data")}

// Generate the TX
rawTx, err := CreateTxWithChangeUsingWif(
	[]*Utxo{utxo},
	[]*PayToAddress{payTo},
	[]OpReturnData{opReturn1, opReturn2},
	"1KQG5AY9GrPt3b5xrFqVh2C3YEhzSdu4kc",
	nil,
	nil,
	"L3VJH2hcRGYYG6YrbWGmsxQC1zyYixA82YjgEyrEUWDs4ALgk8Vu",
)
if err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}

fmt.Printf("rawTx: %s", rawTx.String())
Output:

rawTx: 0100000001760595866e99c1ce920197844740f5598b34763878696371d41b3a7c0a65b0b7000000006b483045022100c1dc4a4c5f26a404ff3618013dc63777d0790d0b0ea3371c67ee3f1bb5126c3e02206be8c841918215337f9b6a6a6040bd058596f2bab5c8b8cb27f849b1474b9e4c412102ea87d1fd77d169bd56a71e700628113d0f8dfe57faa0ba0e55a36f9ce8e10be3ffffffff04f4010000000000001976a9147a1980655efbfec416b2b0c663a7b3ac0b6a25d288ac5f010000000000001976a914c9d8699bdea34b131e737447b50a8b1af0b040bf88ac00000000000000001a006a07707265666978310c6578616d706c65206461746102133700000000000000001c006a0770726566697832116d6f7265206578616d706c65206461746100000000

func CreateWif added in v2.0.2

func CreateWif() (*wif.WIF, error)

CreateWif will create a new WIF (*wif.WIF)

Example

ExampleCreateWif example using CreateWif()

wifKey, err := CreateWif()
if err != nil {
	fmt.Println(err)
	return
}
fmt.Println("WIF Key Generated Length:", len(wifKey.String()))
Output:

WIF Key Generated Length: 51

func CreateWifString added in v2.0.2

func CreateWifString() (string, error)

CreateWifString will create a new WIF (string)

Example

ExampleCreateWifString example using CreateWifString()

wifKey, err := CreateWifString()
if err != nil {
	fmt.Println(err)
	return
}
fmt.Println("WIF Key Generated Length:", len(wifKey))
Output:

WIF Key Generated Length: 51

func DecryptWithPrivateKey

func DecryptWithPrivateKey(privateKey *bec.PrivateKey, data string) (string, error)

DecryptWithPrivateKey is a wrapper to decrypt the previously encrypted information, given a corresponding private key

Example

ExampleDecryptWithPrivateKey example using DecryptWithPrivateKey()

// Start with a private key
privateKey, err := PrivateKeyFromString("bb66a48a9f6dd7b8fb469a6f08a75c25770591dc509c72129b2aaeca77a5269e")
if err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}

// Decrypt the encrypted text
var decryptedText string
decryptedText, err = DecryptWithPrivateKey(privateKey, "4fab3e3534e101cef1ec936628894a2c02ca00206b60babbfa6cc"+
	"ac9a8078d55a50a32b5e15b1a3c9a3607499066bc4eb70721f4002005cdc7638c7e6c051be80cc83092ed5af5a9a015e24c3ed4af289d59"+
	"c0c65cb608aa8f07c9318e6e52a18e60dbcf7a5889304f4bfc01cad735a5f2279f06eb5da5ed7454320da87becbdcd889708fcab")
if err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}

fmt.Printf("decrypted text: %s", decryptedText)
Output:

decrypted text: test-data

func DecryptWithPrivateKeyString

func DecryptWithPrivateKeyString(privateKey, data string) (string, error)

DecryptWithPrivateKeyString is a convenience wrapper for DecryptWithPrivateKey()

Example

ExampleDecryptWithPrivateKeyString example using DecryptWithPrivateKeyString()

// Decrypt the encrypted text
decryptedText, err := DecryptWithPrivateKeyString(
	"bb66a48a9f6dd7b8fb469a6f08a75c25770591dc509c72129b2aaeca77a5269e",
	"4fab3e3534e101cef1ec936628894a2c02ca00206b60babbfa6cc"+
		"ac9a8078d55a50a32b5e15b1a3c9a3607499066bc4eb70721f4002005cdc7638c7e6c051be80cc83092ed5af5a9a015e24c3ed4af289d59"+
		"c0c65cb608aa8f07c9318e6e52a18e60dbcf7a5889304f4bfc01cad735a5f2279f06eb5da5ed7454320da87becbdcd889708fcab",
)
if err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}

fmt.Printf("decrypted text: %s", decryptedText)
Output:

decrypted text: test-data

func DefaultStandardFee

func DefaultStandardFee() *bt.Fee

DefaultStandardFee returns the default standard fees offered by most miners. this function is not public anymore in go-bt

func EncryptShared

func EncryptShared(user1PrivateKey *bec.PrivateKey, user2PubKey *bec.PublicKey, data []byte) (
	*bec.PrivateKey, *bec.PublicKey, []byte, error)

EncryptShared will encrypt data and provide shared keys for decryption

func EncryptSharedString

func EncryptSharedString(user1PrivateKey *bec.PrivateKey, user2PubKey *bec.PublicKey, data string) (
	*bec.PrivateKey, *bec.PublicKey, string, error)

EncryptSharedString will encrypt a string to a hex encoded encrypted payload, and provide shared keys for decryption

func EncryptWithPrivateKey

func EncryptWithPrivateKey(privateKey *bec.PrivateKey, data string) (string, error)

EncryptWithPrivateKey will encrypt the data using a given private key

Example

ExampleEncryptWithPrivateKey example using EncryptWithPrivateKey()

// Create a valid private key
privateKey, err := CreatePrivateKey()
if err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}

// Encrypt the text
var encryptedText string
encryptedText, err = EncryptWithPrivateKey(privateKey, "encrypt my message")
if err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}
// Can't show the real example, as the value changes each time
// fmt.Printf("encrypted text length: %d %s", len(encryptedText), encryptedText)
fmt.Printf("encrypted text length: %d %s", len(encryptedText), "40dd6dbad36cdfb7b1bf85a87887ac3202ca0020b6"+
	"03e6c1fbc30b9a586f06d72eb2fc5117d0f2e4c3193788ebd79c6eb095d88e00209c4ba9a883f631566dfe17d0b2dc83ee456b71927b5b"+
	"5dc6e5a8074d929f3d78c22a4bb7c5f8ffdb0895adf035b2e36fdb5504d3c3b99f3d03a9767eff1b93af14cc586efbf5e81e6fec839c55"+
	"13ab2d644bf3e56d6ddc92e2985c18dab3c6a9")
Output:

encrypted text length: 300 40dd6dbad36cdfb7b1bf85a87887ac3202ca0020b603e6c1fbc30b9a586f06d72eb2fc5117d0f2e4c3193788ebd79c6eb095d88e00209c4ba9a883f631566dfe17d0b2dc83ee456b71927b5b5dc6e5a8074d929f3d78c22a4bb7c5f8ffdb0895adf035b2e36fdb5504d3c3b99f3d03a9767eff1b93af14cc586efbf5e81e6fec839c5513ab2d644bf3e56d6ddc92e2985c18dab3c6a9

func EncryptWithPrivateKeyString

func EncryptWithPrivateKeyString(privateKey, data string) (string, error)

EncryptWithPrivateKeyString is a convenience wrapper for EncryptWithPrivateKey()

Example

ExampleEncryptWithPrivateKeyString example using EncryptWithPrivateKeyString()

// Create a valid private key
privateKey, err := CreatePrivateKeyString()
if err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}

// Encrypt the text
var encryptedText string
encryptedText, err = EncryptWithPrivateKeyString(privateKey, "encrypt my message")
if err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}
// Can't show the real example, as the value changes each time
// fmt.Printf("encrypted text length: %d %s", len(encryptedText), encryptedText)
fmt.Printf("encrypted text length: %d %s", len(encryptedText), "40dd6dbad36cdfb7b1bf85a87887ac3202ca0020b6"+
	"03e6c1fbc30b9a586f06d72eb2fc5117d0f2e4c3193788ebd79c6eb095d88e00209c4ba9a883f631566dfe17d0b2dc83ee456b71927b5b"+
	"5dc6e5a8074d929f3d78c22a4bb7c5f8ffdb0895adf035b2e36fdb5504d3c3b99f3d03a9767eff1b93af14cc586efbf5e81e6fec839c55"+
	"13ab2d644bf3e56d6ddc92e2985c18dab3c6a9")
Output:

encrypted text length: 300 40dd6dbad36cdfb7b1bf85a87887ac3202ca0020b603e6c1fbc30b9a586f06d72eb2fc5117d0f2e4c3193788ebd79c6eb095d88e00209c4ba9a883f631566dfe17d0b2dc83ee456b71927b5b5dc6e5a8074d929f3d78c22a4bb7c5f8ffdb0895adf035b2e36fdb5504d3c3b99f3d03a9767eff1b93af14cc586efbf5e81e6fec839c5513ab2d644bf3e56d6ddc92e2985c18dab3c6a9

func GenerateHDKey

func GenerateHDKey(seedLength uint8) (hdKey *bip32.ExtendedKey, err error)

GenerateHDKey will create a new master node for use in creating a hierarchical deterministic keychain

Example

ExampleGenerateHDKey example using GenerateHDKey()

hdKey, err := GenerateHDKey(SecureSeedLength)
if err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}
// Cannot show the private/public key since they change each time
fmt.Printf("created HD key successfully! (length: %d)", len(hdKey.String()))
Output:

created HD key successfully! (length: 111)

func GenerateHDKeyFromString

func GenerateHDKeyFromString(xPriv string) (hdKey *bip32.ExtendedKey, err error)

GenerateHDKeyFromString will create a new master node for use in creating a hierarchical deterministic keychain from an xPrivKey string

Example

ExampleGenerateHDKeyFromString example using GenerateHDKeyFromString()

hdKey, err := GenerateHDKeyFromString("xprv9s21ZrQH143K3PZSwbEeXEYq74EbnfMngzAiMCZcfjzyRpUvt2vQJnaHRTZjeuEmLXeN6BzYRoFsEckfobxE9XaRzeLGfQoxzPzTRyRb6oE")
if err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}

fmt.Printf("hd key generated from: %s", hdKey.String())
Output:

hd key generated from: xprv9s21ZrQH143K3PZSwbEeXEYq74EbnfMngzAiMCZcfjzyRpUvt2vQJnaHRTZjeuEmLXeN6BzYRoFsEckfobxE9XaRzeLGfQoxzPzTRyRb6oE

func GenerateHDKeyPair

func GenerateHDKeyPair(seedLength uint8) (xPrivateKey, xPublicKey string, err error)

GenerateHDKeyPair will generate a new xPub HD master node (xPrivateKey & xPublicKey)

Example

ExampleGenerateHDKeyPair example using GenerateHDKeyPair()

xPrivateKey, xPublicKey, err := GenerateHDKeyPair(SecureSeedLength)
if err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}

// Cannot show the private/public key since they change each time
fmt.Printf("created HD key successfully! (xPrivateKey length: %d) (xPublicKey length: %d)", len(xPrivateKey), len(xPublicKey))
Output:

created HD key successfully! (xPrivateKey length: 111) (xPublicKey length: 111)

func GenerateSharedKeyPair

func GenerateSharedKeyPair(privateKey *bec.PrivateKey,
	pubKey *bec.PublicKey) (*bec.PrivateKey, *bec.PublicKey)

GenerateSharedKeyPair creates shared keys that can be used to encrypt/decrypt data that can be decrypted by yourself (privateKey) and also the owner of the given public key

func GetAddressFromHDKey

func GetAddressFromHDKey(hdKey *bip32.ExtendedKey) (*bscript.Address, error)

GetAddressFromHDKey is a helper function to get the Address associated with a given hdKey

Expects hdKey to not be nil (otherwise will panic)

Example

ExampleGetAddressFromHDKey example using GetAddressFromHDKey()

hdKey, err := GenerateHDKeyFromString("xprv9s21ZrQH143K3PZSwbEeXEYq74EbnfMngzAiMCZcfjzyRpUvt2vQJnaHRTZjeuEmLXeN6BzYRoFsEckfobxE9XaRzeLGfQoxzPzTRyRb6oE")
if err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}

var address *bscript.Address
if address, err = GetAddressFromHDKey(hdKey); err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}

fmt.Printf("address: %s", address.AddressString)
Output:

address: 18G2YRH3nRKRx8pnqVFUM5nAJhTZJ3YA4W

func GetAddressFromPrivateKey

func GetAddressFromPrivateKey(privateKey *bec.PrivateKey, compressed bool) (string, error)

GetAddressFromPrivateKey takes a bec private key and returns a Bitcoin address

Example

ExampleGetAddressFromPrivateKey example using GetAddressFromPrivateKey()

address, err := GetAddressFromPrivateKeyString("54035dd4c7dda99ac473905a3d82f7864322b49bab1ff441cc457183b9bd8abd", true)
if err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}
fmt.Printf("address found: %s", address)
Output:

address found: 1DfGxKmgL3ETwUdNnXLBueEvNpjcDGcKgK

func GetAddressFromPrivateKeyString

func GetAddressFromPrivateKeyString(privateKey string, compressed bool) (string, error)

GetAddressFromPrivateKeyString takes a private key string and returns a Bitcoin address

func GetAddressFromPubKey

func GetAddressFromPubKey(publicKey *bec.PublicKey, compressed bool) (*bscript.Address, error)

GetAddressFromPubKey gets a bscript.Address from a bec.PublicKey

Example

ExampleGetAddressFromPubKey example using GetAddressFromPubKey()

rawAddress, err := GetAddressFromPubKey(testGetPublicKeyFromPrivateKey("54035dd4c7dda99ac473905a3d82f7864322b49bab1ff441cc457183b9bd8abd"), true)
if err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}
fmt.Printf("address found: %s", rawAddress.AddressString)
Output:

address found: 1DfGxKmgL3ETwUdNnXLBueEvNpjcDGcKgK

func GetAddressFromPubKeyString

func GetAddressFromPubKeyString(pubKey string, compressed bool) (*bscript.Address, error)

GetAddressFromPubKeyString is a convenience function to use a hex string pubKey

Example

ExampleGetAddressFromPubKeyString example using GetAddressFromPubKeyString()

rawAddress, err := GetAddressFromPubKeyString("03ce8a73eb5e4d45966d719ac3ceb431cd0ee203e6395357a167b9abebc4baeacf", true)
if err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}
fmt.Printf("address found: %s", rawAddress.AddressString)
Output:

address found: 17HeHWVDqDqexLJ31aG4qtVMoX8pKMGSuJ

func GetAddressFromScript

func GetAddressFromScript(script string) (string, error)

GetAddressFromScript will take an output script and extract a standard bitcoin address

Example

ExampleGetAddressFromScript example using GetAddressFromScript()

address, err := GetAddressFromScript("76a914b424110292f4ea2ac92beb9e83cf5e6f0fa2996388ac")
if err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}
fmt.Printf("address found: %s", address)
Output:

address found: 1HRVqUGDzpZSMVuNSZxJVaB9xjneEShfA7

func GetAddressStringFromHDKey

func GetAddressStringFromHDKey(hdKey *bip32.ExtendedKey) (string, error)

GetAddressStringFromHDKey is a helper function to get the Address (string) associated with a given hdKey

Expects hdKey to not be nil (otherwise will panic)

Example

ExampleGetAddressStringFromHDKey example using GetAddressStringFromHDKey()

hdKey, err := GenerateHDKeyFromString("xprv9s21ZrQH143K3PZSwbEeXEYq74EbnfMngzAiMCZcfjzyRpUvt2vQJnaHRTZjeuEmLXeN6BzYRoFsEckfobxE9XaRzeLGfQoxzPzTRyRb6oE")
if err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}

var address string
if address, err = GetAddressStringFromHDKey(hdKey); err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}

fmt.Printf("address: %s", address)
Output:

address: 18G2YRH3nRKRx8pnqVFUM5nAJhTZJ3YA4W

func GetAddressesForPath

func GetAddressesForPath(hdKey *bip32.ExtendedKey, num uint32) (addresses []string, err error)

GetAddressesForPath will get the corresponding addresses for the PublicKeys at the given path m/0/x Returns 2 keys, first is internal and second is external

Example

ExampleGetAddressesForPath example using GetAddressesForPath()

hdKey, err := GenerateHDKeyFromString("xprv9s21ZrQH143K3PZSwbEeXEYq74EbnfMngzAiMCZcfjzyRpUvt2vQJnaHRTZjeuEmLXeN6BzYRoFsEckfobxE9XaRzeLGfQoxzPzTRyRb6oE")
if err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}

var addresses []string
addresses, err = GetAddressesForPath(hdKey, 5)
if err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}
fmt.Printf("found [%d] addresses! Address 1: %s Address 2: %s", len(addresses), addresses[0], addresses[1])
Output:

found [2] addresses! Address 1: 1JHGJTqsiFHo4yQYJ1WbTvbxYMZC7nZKYb Address 2: 1DTHBcGeJFRmS26S11tt2EddhSkFM8tmze

func GetExtendedPublicKey

func GetExtendedPublicKey(hdKey *bip32.ExtendedKey) (string, error)

GetExtendedPublicKey will get the extended public key (xPub)

Example

ExampleGetExtendedPublicKey example using GetExtendedPublicKey()

hdKey, err := GenerateHDKeyFromString("xprv9s21ZrQH143K3PZSwbEeXEYq74EbnfMngzAiMCZcfjzyRpUvt2vQJnaHRTZjeuEmLXeN6BzYRoFsEckfobxE9XaRzeLGfQoxzPzTRyRb6oE")
if err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}

var xPub string
xPub, err = GetExtendedPublicKey(hdKey)
if err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}
fmt.Printf("xPub: %s", xPub)
Output:

xPub: xpub661MyMwAqRbcFsdv3cmetNVZf656C85e4D6K9ayEE5XxJcp5RaEeratmGmg7ggt3ZShibYcsusYPom69yDG9hf3UE1i4LrXJbuA9d7hPujt

func GetHDKeyByPath

func GetHDKeyByPath(hdKey *bip32.ExtendedKey, chain, num uint32) (*bip32.ExtendedKey, error)

GetHDKeyByPath gets the corresponding HD key from a chain/num path Reference: https://en.bitcoin.it/wiki/BIP_0032#The_default_wallet_layout

Example

ExampleGetHDKeyByPath example using GetHDKeyByPath()

hdKey, err := GenerateHDKey(SecureSeedLength)
if err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}

// Get a child key
var childKey *bip32.ExtendedKey
childKey, err = GetHDKeyByPath(hdKey, 0, 1)
if err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}
fmt.Printf("hd key (%d) found at path %d/%d", len(childKey.String()), 0, 1)
Output:

hd key (111) found at path 0/1

func GetHDKeyChild

func GetHDKeyChild(hdKey *bip32.ExtendedKey, num uint32) (*bip32.ExtendedKey, error)

GetHDKeyChild gets the child hd key for a given num Note: For a hardened child, start at 0x80000000. (For reference, 0x8000000 = 0')

Expects hdKey to not be nil (otherwise will panic)

Example

ExampleGetHDKeyChild example using GetHDKeyChild()

hdKey, err := GenerateHDKey(SecureSeedLength)
if err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}

// Get a child key
var childKey *bip32.ExtendedKey
childKey, err = GetHDKeyChild(hdKey, 0)
if err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}
fmt.Printf("hd key (%d) found at path %d", len(childKey.String()), 0)
Output:

hd key (111) found at path 0

func GetHDKeyFromExtendedPublicKey

func GetHDKeyFromExtendedPublicKey(xPublicKey string) (*bip32.ExtendedKey, error)

GetHDKeyFromExtendedPublicKey will get the hd key from an existing extended public key (xPub)

Example

ExampleGetHDKeyFromExtendedPublicKey example using GetHDKeyFromExtendedPublicKey()

// Start with an existing xPub
xPub := "xpub661MyMwAqRbcH3WGvLjupmr43L1GVH3MP2WQWvdreDraBeFJy64Xxv4LLX9ZVWWz3ZjZkMuZtSsc9qH9JZR74bR4PWkmtEvP423r6DJR8kA"

// Convert to a HD key
key, err := GetHDKeyFromExtendedPublicKey(xPub)
if err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}

fmt.Printf("key: %s", key.String())
Output:

key: xpub661MyMwAqRbcH3WGvLjupmr43L1GVH3MP2WQWvdreDraBeFJy64Xxv4LLX9ZVWWz3ZjZkMuZtSsc9qH9JZR74bR4PWkmtEvP423r6DJR8kA

func GetPrivateKeyByPath

func GetPrivateKeyByPath(hdKey *bip32.ExtendedKey, chain, num uint32) (*bec.PrivateKey, error)

GetPrivateKeyByPath gets the key for a given derivation path (chain/num)

Expects hdKey to not be nil (otherwise will panic)

Example

ExampleGetPrivateKeyByPath example using GetPrivateKeyByPath()

hdKey, err := GenerateHDKey(SecureSeedLength)
if err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}

// Get a private key at the path
var privateKey *bec.PrivateKey
privateKey, err = GetPrivateKeyByPath(hdKey, 0, 1)
if err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}
fmt.Printf("private key (%d) found at path %d/%d", len(privateKey.Serialise()), 0, 1)
Output:

private key (32) found at path 0/1

func GetPrivateKeyFromHDKey

func GetPrivateKeyFromHDKey(hdKey *bip32.ExtendedKey) (*bec.PrivateKey, error)

GetPrivateKeyFromHDKey is a helper function to get the Private Key associated with a given hdKey

Expects hdKey to not be nil (otherwise will panic)

Example

ExampleGetPrivateKeyFromHDKey example using GetPrivateKeyFromHDKey()

hdKey, err := GenerateHDKeyFromString("xprv9s21ZrQH143K3PZSwbEeXEYq74EbnfMngzAiMCZcfjzyRpUvt2vQJnaHRTZjeuEmLXeN6BzYRoFsEckfobxE9XaRzeLGfQoxzPzTRyRb6oE")
if err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}

var privateKey *bec.PrivateKey
if privateKey, err = GetPrivateKeyFromHDKey(hdKey); err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}

fmt.Printf("private key: %s", hex.EncodeToString(privateKey.Serialise()))
Output:

private key: 0ccf07f2cbe10dbe6f6034b7efbf62fc83cac3d44f49d67aa22ac8893d294e7a

func GetPrivateKeyStringFromHDKey

func GetPrivateKeyStringFromHDKey(hdKey *bip32.ExtendedKey) (string, error)

GetPrivateKeyStringFromHDKey is a helper function to get the Private Key (string) associated with a given hdKey

Expects hdKey to not be nil (otherwise will panic)

Example

ExampleGetPrivateKeyStringFromHDKey example using GetPrivateKeyStringFromHDKey()

hdKey, err := GenerateHDKeyFromString("xprv9s21ZrQH143K3PZSwbEeXEYq74EbnfMngzAiMCZcfjzyRpUvt2vQJnaHRTZjeuEmLXeN6BzYRoFsEckfobxE9XaRzeLGfQoxzPzTRyRb6oE")
if err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}

var privateKey string
if privateKey, err = GetPrivateKeyStringFromHDKey(hdKey); err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}

fmt.Printf("private key: %s", privateKey)
Output:

private key: 0ccf07f2cbe10dbe6f6034b7efbf62fc83cac3d44f49d67aa22ac8893d294e7a

func GetPublicKeyFromHDKey

func GetPublicKeyFromHDKey(hdKey *bip32.ExtendedKey) (*bec.PublicKey, error)

GetPublicKeyFromHDKey is a helper function to get the Public Key associated with a given hdKey

Expects hdKey to not be nil (otherwise will panic)

Example

ExampleGetPublicKeyFromHDKey example using GetPublicKeyFromHDKey()

hdKey, err := GenerateHDKeyFromString("xprv9s21ZrQH143K3PZSwbEeXEYq74EbnfMngzAiMCZcfjzyRpUvt2vQJnaHRTZjeuEmLXeN6BzYRoFsEckfobxE9XaRzeLGfQoxzPzTRyRb6oE")
if err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}

var publicKey *bec.PublicKey
if publicKey, err = GetPublicKeyFromHDKey(hdKey); err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}

fmt.Printf("public key: %s", hex.EncodeToString(publicKey.SerialiseCompressed()))
Output:

public key: 03a25f6c10eedcd41eebac22c6bbc5278690fa1aab3afc2bbe8f2277c85e5c5def

func GetPublicKeysForPath

func GetPublicKeysForPath(hdKey *bip32.ExtendedKey, num uint32) (pubKeys []*bec.PublicKey, err error)

GetPublicKeysForPath gets the PublicKeys for a given derivation path Uses the standard m/0/0 (external) and m/0/1 (internal) paths Reference: https://en.bitcoin.it/wiki/BIP_0032#The_default_wallet_layout

Example

ExampleGetPublicKeysForPath example using GetPublicKeysForPath()

hdKey, err := GenerateHDKeyFromString("xprv9s21ZrQH143K3PZSwbEeXEYq74EbnfMngzAiMCZcfjzyRpUvt2vQJnaHRTZjeuEmLXeN6BzYRoFsEckfobxE9XaRzeLGfQoxzPzTRyRb6oE")
if err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}

var publicKeys []*bec.PublicKey
publicKeys, err = GetPublicKeysForPath(hdKey, 5)
if err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}

fmt.Printf("found [%d] keys! Key 1: %s Key 2: %s", len(publicKeys), hex.EncodeToString(publicKeys[0].SerialiseCompressed()), hex.EncodeToString(publicKeys[1].SerialiseCompressed()))
Output:

found [2] keys! Key 1: 03f87ac38fb0cfca12988b51a2f1cd3e85bb4aeb1b05f549682190ac8205a67d30 Key 2: 02e78303aeef1acce1347c6493fadc1914e6d85ef3189a8856afb3accd53fbd9c5

func PrivateAndPublicKeys

func PrivateAndPublicKeys(privateKey string) (*bec.PrivateKey, *bec.PublicKey, error)

PrivateAndPublicKeys will return both the private and public key in one method Expects a hex encoded privateKey

Example

ExamplePrivateAndPublicKeys example using PrivateAndPublicKeys()

privateKey, publicKey, err := PrivateAndPublicKeys("54035dd4c7dda99ac473905a3d82f7864322b49bab1ff441cc457183b9bd8abd")
if err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}
fmt.Printf("private key: %s public key: %s", hex.EncodeToString(privateKey.Serialise()), hex.EncodeToString(publicKey.SerialiseCompressed()))
Output:

private key: 54035dd4c7dda99ac473905a3d82f7864322b49bab1ff441cc457183b9bd8abd public key: 031b8c93100d35bd448f4646cc4678f278351b439b52b303ea31ec9edb5475e73f

func PrivateKeyFromString

func PrivateKeyFromString(privateKey string) (*bec.PrivateKey, error)

PrivateKeyFromString turns a private key (hex encoded string) into an bec.PrivateKey

Example

ExamplePrivateKeyFromString example using PrivateKeyFromString()

key, err := PrivateKeyFromString("54035dd4c7dda99ac473905a3d82f7864322b49bab1ff441cc457183b9bd8abd")
if err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}
fmt.Printf("key converted: %s", hex.EncodeToString(key.Serialise()))
Output:

key converted: 54035dd4c7dda99ac473905a3d82f7864322b49bab1ff441cc457183b9bd8abd

func PrivateKeyToWif

func PrivateKeyToWif(privateKey string) (*wif.WIF, error)

PrivateKeyToWif will convert a private key to a WIF (*wif.WIF)

Example

ExamplePrivateKeyToWif example using PrivateKeyToWif()

privateWif, err := PrivateKeyToWif("54035dd4c7dda99ac473905a3d82f7864322b49bab1ff441cc457183b9bd8abd")
if err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}
fmt.Printf("converted wif: %s", privateWif.String())
Output:

converted wif: 5JTHas7yTFMBLqgFogxZFf8Vc5uKEbkE7yQAQ2g3xPHo2sNG1Ei

func PrivateKeyToWifString

func PrivateKeyToWifString(privateKey string) (string, error)

PrivateKeyToWifString will convert a private key to a WIF (string)

Example

ExamplePrivateKeyToWifString example using PrivateKeyToWifString()

privateWif, err := PrivateKeyToWifString("54035dd4c7dda99ac473905a3d82f7864322b49bab1ff441cc457183b9bd8abd")
if err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}
fmt.Printf("converted wif: %s", privateWif)
Output:

converted wif: 5JTHas7yTFMBLqgFogxZFf8Vc5uKEbkE7yQAQ2g3xPHo2sNG1Ei

func PubKeyFromPrivateKey

func PubKeyFromPrivateKey(privateKey *bec.PrivateKey, compressed bool) string

PubKeyFromPrivateKey will derive a pubKey (hex encoded) from a given private key

Example

ExamplePubKeyFromPrivateKey example using PubKeyFromPrivateKey()

privateKey, err := PrivateKeyFromString("54035dd4c7dda99ac473905a3d82f7864322b49bab1ff441cc457183b9bd8abd")
if err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}

pubKey := PubKeyFromPrivateKey(privateKey, true)
fmt.Printf("pubkey generated: %s", pubKey)
Output:

pubkey generated: 031b8c93100d35bd448f4646cc4678f278351b439b52b303ea31ec9edb5475e73f

func PubKeyFromPrivateKeyString

func PubKeyFromPrivateKeyString(privateKey string, compressed bool) (string, error)

PubKeyFromPrivateKeyString will derive a pubKey (hex encoded) from a given private key

Example

ExamplePubKeyFromPrivateKeyString example using PubKeyFromPrivateKeyString()

pubKey, err := PubKeyFromPrivateKeyString("54035dd4c7dda99ac473905a3d82f7864322b49bab1ff441cc457183b9bd8abd", true)
if err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}
fmt.Printf("pubkey generated: %s", pubKey)
Output:

pubkey generated: 031b8c93100d35bd448f4646cc4678f278351b439b52b303ea31ec9edb5475e73f

func PubKeyFromSignature

func PubKeyFromSignature(sig, data string) (pubKey *bec.PublicKey, wasCompressed bool, err error)

PubKeyFromSignature gets a publickey for a signature and tells you whether is was compressed

func PubKeyFromString

func PubKeyFromString(pubKey string) (*bec.PublicKey, error)

PubKeyFromString will convert a pubKey (string) into a pubkey (*bec.PublicKey)

Example

ExamplePubKeyFromString example using PubKeyFromString()

pubKey, err := PubKeyFromString("031b8c93100d35bd448f4646cc4678f278351b439b52b303ea31ec9edb5475e73f")
if err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}
fmt.Printf("pubkey from string: %s", hex.EncodeToString(pubKey.SerialiseCompressed()))
Output:

pubkey from string: 031b8c93100d35bd448f4646cc4678f278351b439b52b303ea31ec9edb5475e73f

func ScriptFromAddress

func ScriptFromAddress(address string) (string, error)

ScriptFromAddress will create an output P2PKH script from an address string

Example

ExampleScriptFromAddress example using ScriptFromAddress()

script, err := ScriptFromAddress("1HRVqUGDzpZSMVuNSZxJVaB9xjneEShfA7")
if err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}
fmt.Printf("script generated: %s", script)
Output:

script generated: 76a914b424110292f4ea2ac92beb9e83cf5e6f0fa2996388ac

func SignMessage

func SignMessage(privateKey string, message string, sigRefCompressedKey bool) (string, error)

SignMessage signs a string with the provided private key using Bitcoin Signed Message encoding sigRefCompressedKey bool determines whether the signature will reference a compressed or uncompresed key Spec: https://docs.moneybutton.com/docs/bsv-message.html

Example

ExampleSignMessage example using SignMessage()

signature, err := SignMessage("ef0b8bad0be285099534277fde328f8f19b3be9cadcd4c08e6ac0b5f863745ac", "This is a test message", false)
if err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}
fmt.Printf("signature created: %s", signature)
Output:

signature created: G+zZagsyz7ioC/ZOa5EwsaKice0vs2BvZ0ljgkFHxD3vGsMlGeD4sXHEcfbI4h8lP29VitSBdf4A+nHXih7svf4=

func TxFromHex

func TxFromHex(rawHex string) (*bt.Tx, error)

TxFromHex will return a libsv.tx from a raw hex string

Example

ExampleTxFromHex example using TxFromHex()

tx, err := TxFromHex("01000000012adda020db81f2155ebba69e7c841275517ebf91674268c32ff2f5c7e2853b2c010000006b483045022100872051ef0b6c47714130c12a067db4f38b988bfc22fe270731c2146f5229386b02207abf68bbf092ec03e2c616defcc4c868ad1fc3cdbffb34bcedfab391a1274f3e412102affe8c91d0a61235a3d07b1903476a2e2f7a90451b2ed592fea9937696a07077ffffffff02ed1a0000000000001976a91491b3753cf827f139d2dc654ce36f05331138ddb588acc9670300000000001976a914da036233873cc6489ff65a0185e207d243b5154888ac00000000")
if err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}
fmt.Printf("txID: %s", tx.TxID())
Output:

txID: 64cd12102af20195d54a107e0ee5989ac5db3491893a0b9d42e24354732a22a5

func ValidA58

func ValidA58(a58 []byte) (bool, error)

ValidA58 validates a base58 encoded bitcoin address. An address is valid if it can be decoded into a 25 byte address, the version number is 0, and the checksum validates. Return value ok will be true for valid addresses. If ok is false, the address is invalid and the error value may indicate why.

Example

ExampleValidA58 example using ValidA58()

valid, err := ValidA58([]byte("1KCEAmVS6FFggtc7W9as7sEENvjt7DqMi2"))
if err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
} else if !valid {
	fmt.Printf("address is not valid: %s", "1KCEAmVS6FFggtc7W9as7sEENvjt7DqMi2")
	return
} else {
	fmt.Printf("address is valid!")
}
Output:

address is valid!

func VerifyMessage

func VerifyMessage(address, sig, data string) error

VerifyMessage verifies a string and address against the provided signature and assumes Bitcoin Signed Message encoding. The key referenced by the signature must relate to the address provided. Do not provide an address from an uncompressed key along with a signature from a compressed key

Error will occur if verify fails or verification is not successful (no bool) Spec: https://docs.moneybutton.com/docs/bsv-message.html

Example

ExampleVerifyMessage example using VerifyMessage()

if err := VerifyMessage(
	"1FiyJnrgwBc3Ff83V1yRWAkmXBdGrDQnXQ",
	"IBDscOd/Ov4yrd/YXantqajSAnW4fudpfr2KQy5GNo9pZybF12uNaal4KI822UpQLS/UJD+UK2SnNMn6Z3E4na8=",
	"Testing!",
); err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}
fmt.Printf("verification passed")
Output:

verification passed

func VerifyMessageDER

func VerifyMessageDER(hash [32]byte, pubKey string, signature string) (verified bool, err error)

VerifyMessageDER will take a message string, a public key string and a signature string (in strict DER format) and verify that the message was signed by the public key.

Copyright (c) 2019 Bitcoin Association License: https://github.com/bitcoin-sv/merchantapi-reference/blob/master/LICENSE

Source: https://github.com/bitcoin-sv/merchantapi-reference/blob/master/handler/global.go

Example

ExampleVerifyMessageDER example using VerifyMessageDER()

message := []byte(`{"apiVersion":"0.1.0","timestamp":"2020-10-08T14:25:31.539Z","expiryTime":"2020-10-08T14:35:31.539Z","minerId":"` + testDERPubKey + `","currentHighestBlockHash":"0000000000000000021af4ee1f179a64e530bf818ef67acd09cae24a89124519","currentHighestBlockHeight":656007,"minerReputation":null,"fees":[{"id":1,"feeType":"standard","miningFee":{"satoshis":500,"bytes":1000},"relayFee":{"satoshis":250,"bytes":1000}},{"id":2,"feeType":"data","miningFee":{"satoshis":500,"bytes":1000},"relayFee":{"satoshis":250,"bytes":1000}}]}`)

verified, err := VerifyMessageDER(sha256.Sum256(message), testDERPubKey, testDERSignature)
if err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
} else if !verified {
	fmt.Printf("verification failed")
	return
}
fmt.Printf("verification passed")
Output:

verification passed

func WifFromString added in v2.0.2

func WifFromString(wifKey string) (*wif.WIF, error)

WifFromString will convert a WIF (string) to a WIF (*wif.WIF)

Example

ExampleWifFromString example using WifFromString()

// Create a Private Key
privateKey, err := CreatePrivateKeyString()
if err != nil {
	fmt.Println(err)
	return
}
fmt.Println("Private Key Generated Length:", len(privateKey))

// Create a WIF
var wifKey *wif.WIF
wifKey, err = PrivateKeyToWif(privateKey)
if err != nil {
	fmt.Println(err)
	return
}
fmt.Println("WIF Key Generated Length:", len(wifKey.String()))

// Decode WIF
var decodedWif *wif.WIF
decodedWif, err = WifFromString(wifKey.String())
if err != nil {
	fmt.Println(err)
	return
}
fmt.Println("WIF Key Decoded Length:", len(decodedWif.String()))
Output:

Private Key Generated Length: 64
WIF Key Generated Length: 51
WIF Key Decoded Length: 51

func WifToPrivateKey

func WifToPrivateKey(wifKey string) (*bec.PrivateKey, error)

WifToPrivateKey will convert a WIF to a private key (*bec.PrivateKey)

Example

ExampleWifToPrivateKey example using WifToPrivateKey()

privateKey, err := WifToPrivateKey("5JTHas7yTFMBLqgFogxZFf8Vc5uKEbkE7yQAQ2g3xPHo2sNG1Ei")
if err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}
fmt.Printf("private key: %s", hex.EncodeToString(privateKey.Serialise()))
Output:

private key: 54035dd4c7dda99ac473905a3d82f7864322b49bab1ff441cc457183b9bd8abd

func WifToPrivateKeyString

func WifToPrivateKeyString(wif string) (string, error)

WifToPrivateKeyString will convert a WIF to private key (string)

Example

ExampleWifToPrivateKeyString example using WifToPrivateKeyString()

privateKey, err := WifToPrivateKeyString("5JTHas7yTFMBLqgFogxZFf8Vc5uKEbkE7yQAQ2g3xPHo2sNG1Ei")
if err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}
fmt.Printf("private key: %s", privateKey)
Output:

private key: 54035dd4c7dda99ac473905a3d82f7864322b49bab1ff441cc457183b9bd8abd

Types

type A25

type A25 [25]byte

A25 is a type for a 25 byte (not base58 encoded) bitcoin address.

func (*A25) ComputeChecksum

func (a *A25) ComputeChecksum() (c [4]byte)

ComputeChecksum returns a four byte checksum computed from the first 21 bytes of the address. The embedded checksum is not updated.

func (*A25) EmbeddedChecksum

func (a *A25) EmbeddedChecksum() (c [4]byte)

EmbeddedChecksum returns the 4 checksum bytes of an A25 address

func (*A25) Set58

func (a *A25) Set58(s []byte) error

Set58 takes a base58 encoded address and decodes it into the receiver. Errors are returned if the argument is not valid base58 or if the decoded value does not fit in the 25 byte address. The address is not otherwise checked for validity.

func (*A25) Version

func (a *A25) Version() byte

Version returns the version byte of an A25 address

type OpReturnData

type OpReturnData [][]byte

OpReturnData is the op return data to include in the tx

type PayToAddress

type PayToAddress struct {
	Address  string `json:"address"`
	Satoshis uint64 `json:"satoshis"`
}

PayToAddress is the pay-to-address

type Utxo

type Utxo struct {
	Satoshis     uint64 `json:"satoshis"`
	ScriptPubKey string `json:"string"`
	TxID         string `json:"tx_id"`
	Vout         uint32 `json:"vout"`
}

Utxo is an unspent transaction output

Jump to

Keyboard shortcuts

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