bitcoin

package module
v0.3.20 Latest Latest
Warning

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

Go to latest
Published: Dec 14, 2021 License: MIT Imports: 18 Imported by: 7

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

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
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)
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 vet, 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-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.15.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
Satchmo MrZ

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

This section is empty.

Functions

func CalculateFeeForTx added in v0.0.23

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.GetTxID(), estimatedFee)
Output:

tx id: e75fa79ee5fbb589201f769c01835e14ca595b7bbfa0e602050a2a90cf28d129 estimated fee: 132 satoshis

func CreatePrivateKey added in v0.0.6

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

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

Example

ExampleCreatePrivateKey example using CreatePrivateKey()

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

key created successfully!

func CreatePrivateKeyString added in v0.0.6

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 added in v0.0.16

func CreateTx(utxos []*Utxo, addresses []*PayToAddress,
	opReturns []OpReturnData, privateKey *bsvec.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.ToString())
Output:

rawTx: 0100000001760595866e99c1ce920197844740f5598b34763878696371d41b3a7c0a65b0b7000000006b483045022100eea3d606bd1627be6459a9de4860919225db74843d2fc7f4e7caa5e01f42c2d0022017978d9c6a0e934955a70e7dda71d68cb614f7dd89eb7b9d560aea761834ddd4412102ea87d1fd77d169bd56a71e700628113d0f8dfe57faa0ba0e55a36f9ce8e10be3ffffffff03f4010000000000001976a9147a1980655efbfec416b2b0c663a7b3ac0b6a25d288ac00000000000000001a006a07707265666978310c6578616d706c65206461746102133700000000000000001c006a0770726566697832116d6f7265206578616d706c65206461746100000000

func CreateTxUsingWif added in v0.0.27

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.ToString())
Output:

rawTx: 0100000001760595866e99c1ce920197844740f5598b34763878696371d41b3a7c0a65b0b7000000006b483045022100eea3d606bd1627be6459a9de4860919225db74843d2fc7f4e7caa5e01f42c2d0022017978d9c6a0e934955a70e7dda71d68cb614f7dd89eb7b9d560aea761834ddd4412102ea87d1fd77d169bd56a71e700628113d0f8dfe57faa0ba0e55a36f9ce8e10be3ffffffff03f4010000000000001976a9147a1980655efbfec416b2b0c663a7b3ac0b6a25d288ac00000000000000001a006a07707265666978310c6578616d706c65206461746102133700000000000000001c006a0770726566697832116d6f7265206578616d706c65206461746100000000

func CreateTxWithChange added in v0.0.25

func CreateTxWithChange(utxos []*Utxo, payToAddresses []*PayToAddress, opReturns []OpReturnData,
	changeAddress string, standardRate, dataRate *bt.Fee,
	privateKey *bsvec.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.ToString())
Output:

rawTx: 0100000001760595866e99c1ce920197844740f5598b34763878696371d41b3a7c0a65b0b7000000006b483045022100c1dc4a4c5f26a404ff3618013dc63777d0790d0b0ea3371c67ee3f1bb5126c3e02206be8c841918215337f9b6a6a6040bd058596f2bab5c8b8cb27f849b1474b9e4c412102ea87d1fd77d169bd56a71e700628113d0f8dfe57faa0ba0e55a36f9ce8e10be3ffffffff04f4010000000000001976a9147a1980655efbfec416b2b0c663a7b3ac0b6a25d288ac5f010000000000001976a914c9d8699bdea34b131e737447b50a8b1af0b040bf88ac00000000000000001a006a07707265666978310c6578616d706c65206461746102133700000000000000001c006a0770726566697832116d6f7265206578616d706c65206461746100000000

func CreateTxWithChangeUsingWif added in v0.0.27

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.ToString())
Output:

rawTx: 0100000001760595866e99c1ce920197844740f5598b34763878696371d41b3a7c0a65b0b7000000006b483045022100c1dc4a4c5f26a404ff3618013dc63777d0790d0b0ea3371c67ee3f1bb5126c3e02206be8c841918215337f9b6a6a6040bd058596f2bab5c8b8cb27f849b1474b9e4c412102ea87d1fd77d169bd56a71e700628113d0f8dfe57faa0ba0e55a36f9ce8e10be3ffffffff04f4010000000000001976a9147a1980655efbfec416b2b0c663a7b3ac0b6a25d288ac5f010000000000001976a914c9d8699bdea34b131e737447b50a8b1af0b040bf88ac00000000000000001a006a07707265666978310c6578616d706c65206461746102133700000000000000001c006a0770726566697832116d6f7265206578616d706c65206461746100000000

func DecryptWithPrivateKey added in v0.0.27

func DecryptWithPrivateKey(privateKey *bsvec.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 added in v0.0.27

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 EncryptShared added in v0.2.9

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

EncryptShared will encrypt data and provide shared keys for decryption

func EncryptSharedString added in v0.2.11

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

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

func EncryptWithPrivateKey added in v0.0.27

func EncryptWithPrivateKey(privateKey *bsvec.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 added in v0.0.27

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 added in v0.0.14

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

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

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 added in v0.0.20

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

GenerateHDKeyFromString will create a new master node for use in creating a hierarchical deterministic key chain 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 added in v0.0.14

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 added in v0.0.27

func GenerateSharedKeyPair(privateKey *bsvec.PrivateKey,
	pubKey *bsvec.PublicKey) (*bsvec.PrivateKey, *bsvec.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 added in v0.0.20

func GetAddressFromHDKey(hdKey *hdkeychain.ExtendedKey) (*bsvutil.LegacyAddressPubKeyHash, 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 *bsvutil.LegacyAddressPubKeyHash
if address, err = GetAddressFromHDKey(hdKey); err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}

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

address: 18G2YRH3nRKRx8pnqVFUM5nAJhTZJ3YA4W

func GetAddressFromPrivateKey added in v0.0.21

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

GetAddressFromPrivateKey takes a bsvec 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 added in v0.2.28

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

GetAddressFromPrivateKeyString takes a private key string and returns a Bitcoin address

func GetAddressFromPubKey added in v0.0.21

func GetAddressFromPubKey(publicKey *bsvec.PublicKey, compressed bool) (*bsvutil.LegacyAddressPubKeyHash, error)

GetAddressFromPubKey gets a bsvutil.LegacyAddressPubKeyHash from a bsvec.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.EncodeAddress())
Output:

address found: 1DfGxKmgL3ETwUdNnXLBueEvNpjcDGcKgK

func GetAddressFromPubKeyString added in v0.0.21

func GetAddressFromPubKeyString(pubKey string, compressed bool) (*bsvutil.LegacyAddressPubKeyHash, 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.EncodeAddress())
Output:

address found: 17HeHWVDqDqexLJ31aG4qtVMoX8pKMGSuJ

func GetAddressFromScript added in v0.0.21

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 added in v0.0.27

func GetAddressStringFromHDKey(hdKey *hdkeychain.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 added in v0.0.21

func GetAddressesForPath(hdKey *hdkeychain.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 added in v0.0.27

func GetExtendedPublicKey(hdKey *hdkeychain.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 added in v0.0.15

func GetHDKeyByPath(hdKey *hdkeychain.ExtendedKey, chain, num uint32) (*hdkeychain.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 *hdkeychain.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 added in v0.0.20

func GetHDKeyChild(hdKey *hdkeychain.ExtendedKey, num uint32) (*hdkeychain.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 *hdkeychain.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 added in v0.0.27

func GetHDKeyFromExtendedPublicKey(xPublicKey string) (*hdkeychain.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 added in v0.0.15

func GetPrivateKeyByPath(hdKey *hdkeychain.ExtendedKey, chain, num uint32) (*bsvec.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 *bsvec.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.Serialize()), 0, 1)
Output:

private key (32) found at path 0/1

func GetPrivateKeyFromHDKey added in v0.0.20

func GetPrivateKeyFromHDKey(hdKey *hdkeychain.ExtendedKey) (*bsvec.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 *bsvec.PrivateKey
if privateKey, err = GetPrivateKeyFromHDKey(hdKey); err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}

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

private key: 0ccf07f2cbe10dbe6f6034b7efbf62fc83cac3d44f49d67aa22ac8893d294e7a

func GetPrivateKeyStringFromHDKey added in v0.0.27

func GetPrivateKeyStringFromHDKey(hdKey *hdkeychain.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 added in v0.0.20

func GetPublicKeyFromHDKey(hdKey *hdkeychain.ExtendedKey) (*bsvec.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 *bsvec.PublicKey
if publicKey, err = GetPublicKeyFromHDKey(hdKey); err != nil {
	fmt.Printf("error occurred: %s", err.Error())
	return
}

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

public key: 03a25f6c10eedcd41eebac22c6bbc5278690fa1aab3afc2bbe8f2277c85e5c5def

func GetPublicKeysForPath added in v0.0.21

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

GetPublicKeysForPath gets the PublicKeys for a given derivation path Uses the standard m/0/0 (internal) and m/0/1 (external) 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 []*bsvec.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].SerializeCompressed()), hex.EncodeToString(publicKeys[1].SerializeCompressed()))
Output:

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

func PrivateAndPublicKeys added in v0.0.12

func PrivateAndPublicKeys(privateKey string) (*bsvec.PrivateKey, *bsvec.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.Serialize()), hex.EncodeToString(publicKey.SerializeCompressed()))
Output:

private key: 54035dd4c7dda99ac473905a3d82f7864322b49bab1ff441cc457183b9bd8abd public key: 031b8c93100d35bd448f4646cc4678f278351b439b52b303ea31ec9edb5475e73f

func PrivateKeyFromString added in v0.0.6

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

PrivateKeyFromString turns a private key (hex encoded string) into an bsvec.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.Serialize()))
Output:

key converted: 54035dd4c7dda99ac473905a3d82f7864322b49bab1ff441cc457183b9bd8abd

func PrivateKeyToWif added in v0.0.13

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

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

Example

ExamplePrivateKeyToWif example using PrivateKeyToWif()

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

converted wif: 5JTHas7yTFMBLqgFogxZFf8Vc5uKEbkE7yQAQ2g3xPHo2sNG1Ei

func PrivateKeyToWifString added in v0.0.13

func PrivateKeyToWifString(privateKey string) (string, error)

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

Example

ExamplePrivateKeyToWifString example using PrivateKeyToWifString()

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

converted wif: 5JTHas7yTFMBLqgFogxZFf8Vc5uKEbkE7yQAQ2g3xPHo2sNG1Ei

func PubKeyFromPrivateKey added in v0.0.7

func PubKeyFromPrivateKey(privateKey *bsvec.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 added in v0.0.27

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 added in v0.2.23

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

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

func PubKeyFromString added in v0.0.10

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

PubKeyFromString will convert a pubKey (string) into a pubkey (*bsvec.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.SerializeCompressed()))
Output:

pubkey from string: 031b8c93100d35bd448f4646cc4678f278351b439b52b303ea31ec9edb5475e73f

func ScriptFromAddress added in v0.0.9

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 added in v0.0.16

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.GetTxID())
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 added in v0.0.26

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 WifToPrivateKey added in v0.0.13

func WifToPrivateKey(wif string) (*bsvec.PrivateKey, error)

WifToPrivateKey will convert a WIF to a private key (*bsvec.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.Serialize()))
Output:

private key: 54035dd4c7dda99ac473905a3d82f7864322b49bab1ff441cc457183b9bd8abd

func WifToPrivateKeyString added in v0.0.13

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 a 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 a A25 address

type OpReturnData added in v0.0.16

type OpReturnData [][]byte

OpReturnData is the op return data to include in the tx

type PayToAddress added in v0.0.16

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

PayToAddress is the pay-to-address

type Utxo added in v0.0.16

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