gocoin

package module
v0.0.0-...-d82142f Latest Latest
Warning

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

Go to latest
Published: Dec 17, 2019 License: BSD-3-Clause, MIT Imports: 20 Imported by: 0

README

Build Status GoDoc GitHub license Coverage Status

GOcoin

Overview

This is a library to make bitcoin address and transactions which was initially forked from hellobitcoin, and added some useful features.

GOcoin uses btcec library in btcd instead of https://github.com/toxeus/go-secp256k1 to make it a pure GO program.

Features

  1. Normaly Payment(P2PKH) supporting multi TxIns and multi TxOuts.
  2. Gethering unspent transaction outputs(UTXO) and send transactions by using Blockr.io WEB API.
  3. M of N multisig whose codes were partially ported from https://github.com/soroushjp/go-bitcoin-multisig.
  4. Micropayment Channel

Requirements

This requires

  • git
  • go 1.3+

Installation

$ mkdir tmp
$ cd tmp
$ mkdir src
$ mkdir bin
$ mkdir pkg
$ exoprt GOPATH=`pwd`
$ go get github.com/StorjPlatform/gocoin

Example

(This example omits error handlings for simplicity.)

Key Handling


import gocoin

func main(){
	//make a public and private key pair.
	key, _ := gocoin.GenerateKey(true)
	adr, _ := key.Pub.GetAddress()
	fmt.Println("address=", adr)
	wif := key.Priv.GetWIFAddress()
	fmt.Println("wif=", wif)
	
	//get key from wif
	wif := "928Qr9J5oAC6AYieWJ3fG3dZDjuC7BFVUqgu4GsvRVpoXiTaJJf"
	txKey, _ := gocoin.GetKeyFromWIF(wif)
}

Normal Payment

import gocoin

func main(){
	key, _ := gocoin.GenerateKey(true)

	//get unspent transactions
	service := gocoin.NewBlockrService(true)
	txs, _ := service.GetUTXO(adr,nil)
	
	//Normal Payment
	gocoin.Pay([]*Key{txKey}, []*gocoin.Amounts{&{gocoin.Amounts{"n2eMqTT929pb1RDNuqEnxdaLau1rxy3efi", 0.01*gocoin.BTC}}, service)
}

M of N Multisig

import gocoin

func main(){
	key, _ := gocoin.GenerateKey(true)
	service := gocoin.NewBlockrService(true)

	//2 of 3 multisig
	key1, _ := gocoin.GenerateKey(true)
	key2, _ := gocoin.GenerateKey(true)
	key3, _ := gocoin.GenerateKey(true)
	rs, _:= gocoin.NewRedeemScript(2, []*PublicKey{key1.Pub, key2.Pub, key3.Pub})
	//make a fund
	rs.Pay([]*Key{txKey}, 0.05*gocoin.BTC, service)

    //get a raw transaction for signing.
	rawtx, tx, _:= rs.CreateRawTransactionHashed([]*gocoin.Amounts{&{gocoin.Amounts{"n3Bp1hbgtmwDtjQTpa6BnPPCA8fTymsiZy", 0.05*gocoin.BTC}}, service)

	//spend the fund
	sign1, _:= key2.Priv.Sign(rawtx)
	sign2, _:= key3.Priv.Sign(rawtx)
	rs.Spend(tx, [][]byte{nil, sign1, sign2}, service)
}

Micropayment Channel

import gocoin

func main(){
	service := gocoin.NewBlockrService(true)

	key1, _ := gocoin.GenerateKey(true) //payer
	key2, _ := gocoin.GenerateKey(true) //payee

	payer, _:= gocoin.NewMicropayer(key1, key2.Pub, service)
	payee, _:= gocoin.NewMicropayee(key2, key1.Pub, service)

	txHash, _:= payer.CreateBond([]*Key{key1}, 0.05*BTC)

	locktime := time.Now().Add(time.Hour)
	sign, _:= payee.SignToRefund(txHash, 0.05*gocoin.BTC-gocoin.Fee, uint32(locktime.Unix()))
	payer.SendBond(uint32(locktime.Unix()), sign) //return an error if payee's sig is invalid

	signIP, _:= payer.SignToIncrementedPayment(0.001 * gocoin.BTC)
	payee.IncrementPayment(0.001*gocoin.BTC, signIP) //return an error if payer's sig is invalid
	//more payments

	payee.SendLastPayment()
	//or
	//	payer.SendRefund() after locktime

}

Note:

payer.SendRefund() must be called after locktime.

http://chimera.labs.oreilly.com/books/1234000001802/ch05.html#tx_propagation

Transactions with locktime specifying a future block or time must be held by the originating system and transmitted to the bitcoin network only after they become valid.

Contribution

Improvements to the codebase and pull requests are encouraged.

Documentation

Index

Constants

View Source
const (

	//BTC is unit to convert BTC to satoshi
	BTC = 100000000

	//Fee for a transaction
	DefaultFee = uint64(0.0001 * BTC) //  0.0001 BTC/kB
)

Variables

View Source
var Services = []func() (Service, error){
	NewBlockrService,
}

TestServices is an array containing generator of Services

View Source
var TestServices = []func() (Service, error){
	NewBlockrServiceForTest,
}

TestServices is an array containing generator of Services for testnet

Functions

func IsTestnet

func IsTestnet(addr string) (bool, error)

IsTestnet returns true if addr is for testnet.

func Pay

func Pay(keys []*Key, addresses []*Amounts, service Service) ([]byte, error)

Pay pays in a nomal way.(P2KSH)

func PayWithCustomData

func PayWithCustomData(keys []*Key, addresses []*Amounts, service Service, customData []byte) ([]byte, error)

PayWithCustomData pays in a nomal way.(P2KSH) with an additional custom field (OP_RETURN)

func SetLogger

func SetLogger(logger *log.Logger)

SetLogger sets logger this module uses.

func SetUTXOSpent

func SetUTXOSpent(hash []byte)

SetTXSpent sets tx hash is already spent.

Types

type Amounts

type Amounts struct {
	Address string
	Amount  uint64
}

Amounts represents amount of bitcoin of address

type BlockrService

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

BlockrService is a service using Blockr.io.

func (*BlockrService) GetServiceName

func (b *BlockrService) GetServiceName() string

GetServiceName return service name.

func (*BlockrService) GetUTXO

func (b *BlockrService) GetUTXO(addr string, key *Key) (UTXOs, error)

GetUTXO gets unspent transaction outputs by using Blockr.io.

func (*BlockrService) SendTX

func (b *BlockrService) SendTX(data []byte) ([]byte, error)

SendTX send a transaction using Blockr.io.

type Key

type Key struct {
	Pub  *PublicKey
	Priv *PrivateKey
}

Key includes PublicKey and PrivateKey.

func GenerateKey

func GenerateKey(flagTestnet bool) (*Key, error)

GenerateKey generates random PublicKey and PrivateKey.

func GetKeyFromWIF

func GetKeyFromWIF(wif string) (*Key, error)

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

func (*Key) SignMessage

func (key *Key) SignMessage(hash []byte) ([]byte, error)

SignMessage sign using bitcoin sign struct

type Micropayee

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

Micropayee represents payee of Micropayment.

func NewMicropayee

func NewMicropayee(key *Key, publicKey *PublicKey, service Service) (*Micropayee, error)

NewMicropayee creates new MicroPayee struct.

func (*Micropayee) IncrementPayment

func (m *Micropayee) IncrementPayment(increment uint64, sign []byte) error

IncrementPayment increment payment ,creates transaction and store its tx into struct.

func (*Micropayee) SendLastPayment

func (m *Micropayee) SendLastPayment() ([]byte, error)

SendLastPayment sends last incremented tx and returns tx hash.

func (*Micropayee) SignToRefund

func (m *Micropayee) SignToRefund(txHash []byte, amount uint64, lockTime *time.Time) ([]byte, error)

SignToRefund create signature of refund tx.

type Micropayer

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

Micropayer represents payer of Micropayment.

func NewMicropayer

func NewMicropayer(key *Key, publicKey *PublicKey, service Service) (*Micropayer, error)

NewMicropayer creates new MicroPayer struct.

func (*Micropayer) CreateBond

func (m *Micropayer) CreateBond(keys []*Key, amount uint64) ([]byte, error)

CreateBond creates bond and return its hash.

func (*Micropayer) SendBond

func (m *Micropayer) SendBond(lockTime *time.Time, sign []byte) ([]byte, error)

SendBond send bond and refunds and returns bond tx hash.

func (*Micropayer) SendRefund

func (m *Micropayer) SendRefund() ([]byte, error)

SendRefund sends refunt tx and returns tx hash. bond tx will be locked after sending thye refund (?).

func (*Micropayer) SignToIncrementedPayment

func (m *Micropayer) SignToIncrementedPayment(increment uint64) ([]byte, error)

SignToIncrementedPayment creates signature for incremented payment tx.

type PrivateKey

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

PrivateKey represents private key for bitcoin

func (*PrivateKey) GetWIFAddress

func (priv *PrivateKey) GetWIFAddress() string

GetWIFAddress returns WIF format string from PrivateKey

func (*PrivateKey) Sign

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

Sign sign data.

type PublicKey

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

PublicKey represents public key for bitcoin

func GetPublicKey

func GetPublicKey(pubKeyByte []byte, isTestnet bool) (*PublicKey, error)

GetPublicKey returns PublicKey struct using public key hex string.

func (*PublicKey) GetAddress

func (pub *PublicKey) GetAddress() (string, []byte)

GetAddress returns bitcoin address from PublicKey

type RedeemScript

type RedeemScript struct {
	M          int
	PublicKeys []*PublicKey
	Script     []byte
}

RedeemScript represents Redeem script for M of N multisig transaction.

func NewRedeemScript

func NewRedeemScript(m int, publicKeys []*PublicKey) (*RedeemScript, error)

NewRedeemScript creates a M-of-N Multisig redeem script given m, n and n public keys and return RedeemScript struct.

func (*RedeemScript) CreateRawTransactionHashed

func (rs *RedeemScript) CreateRawTransactionHashed(addresses []*Amounts, service Service) ([]byte, *TX, error)

CreateRawTransactionHashed returns a hash of raw transaction for signing.

func (*RedeemScript) GetAddress

func (rs *RedeemScript) GetAddress() string

GetAddress creates P2SH multisig addresses.

func (*RedeemScript) Pay

func (rs *RedeemScript) Pay(keys []*Key, amount uint64, service Service) ([]byte, error)

Pay pays to a fund.

func (*RedeemScript) Spend

func (rs *RedeemScript) Spend(tx *TX, signs [][]byte, service Service) ([]byte, error)

Spend spend the fund.

type Service

type Service interface {
	GetServiceName() string
	GetUTXO(string, *Key) (UTXOs, error)
	SendTX([]byte) ([]byte, error)
}

Service is for getting UTXO or sending transactions , basically by using WEB API.

func NewBlockrService

func NewBlockrService() (Service, error)

NewBlockrService creates BlockrService struct for not test.

func NewBlockrServiceForTest

func NewBlockrServiceForTest() (Service, error)

NewBlockrServiceForTest creates BlockrService struct for test.

func SelectService

func SelectService(isTestnet bool) (Service, error)

SelectService returns a service randomly.

type TX

type TX struct {
	Txin       []*TXin
	Txout      []*TXout
	Locktime   uint32
	CustomData []byte
}

TX represents transaction.

func (*TX) AttachCustomData

func (tx *TX) AttachCustomData(customData []byte) error

AttachCustomData will attach custom data to transaction (passed through an OP_RETURN operator) 40 bytes max alloxwed by bitcoin protocol

func (*TX) MakeTX

func (tx *TX) MakeTX() ([]byte, error)

MakeTX makes transaction and return tx hex string(not send)

type TXin

type TXin struct {
	Hash  []byte
	Index uint32

	Sequence         uint32
	PrevScriptPubkey []byte
	CreateScriptSig  func(rawTransactionHashed []byte) ([]byte, error)
	// contains filtered or unexported fields
}

TXin represents tx input of a transaction.

type TXout

type TXout struct {
	Value        uint64
	ScriptPubkey []byte
}

TXout represents tx output of a transaction.

type UTXO

type UTXO struct {
	Addr   string
	Hash   []byte
	Amount uint64
	Index  uint32
	Script []byte
	Age    uint64
	Key    *Key
}

UTXO represents unspent transaction outputs.

type UTXOs

type UTXOs []*UTXO

UTXOs is for sorting UTXO

func (UTXOs) Len

func (us UTXOs) Len() int

Len returns length of UTXO

func (UTXOs) Less

func (us UTXOs) Less(i, j int) bool

Less returns true is age is smaller.

func (UTXOs) Swap

func (us UTXOs) Swap(i, j int)

Swap swaps UTXO

Directories

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

Jump to

Keyboard shortcuts

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