zcash

package module
v0.0.0-...-3480b96 Latest Latest
Warning

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

Go to latest
Published: Jun 22, 2018 License: MIT Imports: 32 Imported by: 0

README

Build Status Coverage Status Go Report Card

zcash-light

Lightweight Zcash API-wallet library in Go. It connects to an Insight API endpoint to fetch and send transactions.

Library Usage:

// Create a new config
config := zcash.Config{}

// Select network
config.Params = &chaincfg.TestNet3Params

// Select wallet datastore
sqliteDatastore, _ := db.Create(config.RepoPath)
config.DB = sqliteDatastore

// Create the wallet
wallet, _ := zcash.NewWallet(config)

// Start it!
go wallet.Start()

The wallet implements the interface from github.com/OpenBazaar/wallet-interface

Documentation

Index

Constants

View Source
const (
	MaxBlockBaseSize = 2000000

	NumJoinSplitInputs  = 2
	NumJoinSplitOutputs = 2

	SproutVersionGroupID uint32 = 0

	OverwinterFlagMask       uint32 = 0x80000000
	OverwinterVersionGroupID        = 0x03C48270

	TxExpiryHeightThreshold uint32 = 500000000

	SproutMinCurrentVersion     uint32 = 1
	SproutMaxCurrentVersion            = 2
	OverwinterMinCurrentVersion        = 3
	OverwinterMaxCurrentVersion        = 3
)
View Source
const (
	// RedeemP2PKHSigScriptSize is the worst case (largest) serialize size
	// of a transaction input script that redeems a compressed P2PKH output.
	// It is calculated as:
	//
	//   - OP_DATA_73
	//   - 72 bytes DER signature + 1 byte sighash
	//   - OP_DATA_33
	//   - 33 bytes serialized compressed pubkey
	RedeemP2PKHSigScriptSize = 1 + 73 + 1 + 33

	// RedeemP2SHMultisigSigScriptSize is the worst case (largest) serialize size
	// of a transaction input script that redeems a 2 of 3 P2SH multisig output with compressed keys.
	// It is calculated as:
	//
	//   - OP_0
	//   - OP_DATA_72
	//   - 72 bytes DER signature
	//   - OP_DATA_72
	//   - 72 bytes DER signature
	//   - OP_PUSHDATA
	//   - OP_2
	//   - OP_DATA_33
	//   - 33 bytes serialized compressed pubkey
	//   - OP_DATA_33
	//   - 33 bytes serialized compressed pubkey
	//   - OP_DATA_33
	//   - 33 bytes serialized compressed pubkey
	//   - OP3
	//   - OP_CHECKMULTISIG
	RedeemP2SH2of3MultisigSigScriptSize = 1 + 1 + 72 + 1 + 72 + 1 + 1 + 1 + 33 + 1 + 33 + 1 + 33 + 1 + 1

	// RedeemP2SH1of2MultisigSigScriptSize is the worst case (largest) serialize size
	// of a transaction input script that redeems a 1 of 2 P2SH multisig output with compressed keys.
	// It is calculated as:
	//
	//   - OP_0
	//   - OP_DATA_72
	//   - 72 bytes DER signature
	//   - OP_PUSHDATA
	//   - OP_1
	//   - OP_DATA_33
	//   - 33 bytes serialized compressed pubkey
	//   - OP_DATA_33
	//   - 33 bytes serialized compressed pubkey
	//   - OP2
	//   - OP_CHECKMULTISIG
	RedeemP2SH1of2MultisigSigScriptSize = 1 + 1 + 72 + 1 + 1 + 1 + 33 + 1 + 33 + 1 + 1

	// RedeemP2SHMultisigTimelock1SigScriptSize is the worst case (largest) serialize size
	// of a transaction input script that redeems a compressed P2SH timelocked multisig using the timeout.
	// It is calculated as:
	//
	//   - OP_DATA_72
	//   - 72 bytes DER signature
	//   - OP_0
	//   - OP_PUSHDATA
	//   - OP_IF
	//   - OP_2
	//   - OP_DATA_33
	//   - 33 bytes serialized compressed pubkey
	//   - OP_DATA_33
	//   - 33 bytes serialized compressed pubkey
	//   - OP_DATA_33
	//   - 33 bytes serialized compressed pubkey
	//   - OP3
	//   - OP_CHECKMULTISIG
	//   - OP_ELSE
	//   - OP_PUSHDATA
	//   - 2 byte block height
	//   - OP_CHECKSEQUENCEVERIFY
	//   - OP_DROP
	//   - OP_DATA_33
	//   - 33 bytes serialized compressed pubkey
	//   - OP_CHECKSIG
	//   - OP_ENDIF
	RedeemP2SHMultisigTimelock1SigScriptSize = 1 + 72 + 1 + 1 + 1 + 1 + 1 + 33 + 1 + 33 + 1 + 33 + 1 + 1 + 1 + 1 + 2 + 1 + 1 + 1 + 33 + 1 + 1

	// RedeemP2SHMultisigTimelock2SigScriptSize is the worst case (largest) serialize size
	// of a transaction input script that redeems a compressed P2SH timelocked multisig without using the timeout.
	// It is calculated as:
	//
	//   - OP_0
	//   - OP_DATA_72
	//   - 72 bytes DER signature
	//   - OP_DATA_72
	//   - 72 bytes DER signature
	//   - OP_1
	//   - OP_PUSHDATA
	//   - OP_IF
	//   - OP_2
	//   - OP_DATA_33
	//   - 33 bytes serialized compressed pubkey
	//   - OP_DATA_33
	//   - 33 bytes serialized compressed pubkey
	//   - OP_DATA_33
	//   - 33 bytes serialized compressed pubkey
	//   - OP3
	//   - OP_CHECKMULTISIG
	//   - OP_ELSE
	//   - OP_PUSHDATA
	//   - 2 byte block height
	//   - OP_CHECKSEQUENCEVERIFY
	//   - OP_DROP
	//   - OP_DATA_33
	//   - 33 bytes serialized compressed pubkey
	//   - OP_CHECKSIG
	//   - OP_ENDIF
	RedeemP2SHMultisigTimelock2SigScriptSize = 1 + 1 + 72 + +1 + 72 + 1 + 1 + 1 + 1 + 1 + 33 + 1 + 33 + 1 + 33 + 1 + 1 + 1 + 1 + 2 + 1 + 1 + 1 + 33 + 1 + 1

	// P2PKHPkScriptSize is the size of a transaction output script that
	// pays to a compressed pubkey hash.  It is calculated as:
	//
	//   - OP_DUP
	//   - OP_HASH160
	//   - OP_DATA_20
	//   - 20 bytes pubkey hash
	//   - OP_EQUALVERIFY
	//   - OP_CHECKSIG
	P2PKHPkScriptSize = 1 + 1 + 1 + 20 + 1 + 1

	// RedeemP2PKHInputSize is the worst case (largest) serialize size of a
	// transaction input redeeming a compressed P2PKH output.  It is
	// calculated as:
	//
	//   - 32 bytes previous tx
	//   - 4 bytes output index
	//   - 1 byte script len
	//   - signature script
	//   - 4 bytes sequence
	RedeemP2PKHInputSize = 32 + 4 + 1 + RedeemP2PKHSigScriptSize + 4

	// RedeemP2SH2of3MultisigInputSize is the worst case (largest) serialize size of a
	// transaction input redeeming a compressed P2SH 2 of 3 multisig output.  It is
	// calculated as:
	//
	//   - 32 bytes previous tx
	//   - 4 bytes output index
	//   - 1 byte script len
	//   - 4 bytes sequence
	///  - witness discounted signature script
	RedeemP2SH2of3MultisigInputSize = 32 + 4 + 1 + 4 + (RedeemP2SH2of3MultisigSigScriptSize / 4)

	// RedeemP2SH1of2MultisigInputSize is the worst case (largest) serialize size of a
	// transaction input redeeming a compressed P2SH 2 of 3 multisig output.  It is
	// calculated as:
	//
	//   - 32 bytes previous tx
	//   - 4 bytes output index
	//   - 1 byte script len
	//   - 4 bytes sequence
	///  - witness discounted signature script
	RedeemP2SH1of2MultisigInputSize = 32 + 4 + 1 + 4 + (RedeemP2SH1of2MultisigSigScriptSize / 4)

	// RedeemP2SHMultisigTimelock1InputSize is the worst case (largest) serialize size of a
	// transaction input redeeming a compressed p2sh timelocked multig output with using the timeout.  It is
	// calculated as:
	//
	//   - 32 bytes previous tx
	//   - 4 bytes output index
	//   - 1 byte script len
	//   - 4 bytes sequence
	///  - witness discounted signature script
	RedeemP2SHMultisigTimelock1InputSize = 32 + 4 + 1 + 4 + (RedeemP2SHMultisigTimelock1SigScriptSize / 4)

	// RedeemP2SHMultisigTimelock2InputSize is the worst case (largest) serialize size of a
	// transaction input redeeming a compressed P2SH timelocked multisig output without using the timeout.  It is
	// calculated as:
	//
	//   - 32 bytes previous tx
	//   - 4 bytes output index
	//   - 1 byte script len
	//   - 4 bytes sequence
	///  - witness discounted signature script
	RedeemP2SHMultisigTimelock2InputSize = 32 + 4 + 1 + 4 + (RedeemP2SHMultisigTimelock2SigScriptSize / 4)

	// P2PKHOutputSize is the serialize size of a transaction output with a
	// P2PKH output script.  It is calculated as:
	//
	//   - 8 bytes output value
	//   - 1 byte compact int encoding value 25
	//   - 25 bytes P2PKH output script
	P2PKHOutputSize = 8 + 1 + P2PKHPkScriptSize
)

Worst case script and input/output size estimates.

View Source
const NotAnInput int = -1

Special case nIn for signing JoinSplits.

View Source
const (
	OverwinterProtocolVersion = 170005
)

Variables

View Source
var (
	// ErrChecksumMismatch describes an error where decoding failed due
	// to a bad checksum.
	ErrChecksumMismatch = errors.New("checksum mismatch")

	// ErrUnknownAddressType describes an error where an address can not
	// decoded as a specific address type due to the string encoding
	// begining with an identifier byte unknown to any standard or
	// registered (via chaincfg.Register) network.
	ErrUnknownAddressType = errors.New("unknown address type")

	// ErrAddressCollision describes an error where an address can not
	// be uniquely determined as either a pay-to-pubkey-hash or
	// pay-to-script-hash address since the leading identifier is used for
	// describing both address kinds, but for different networks.  Rather
	// than assuming or defaulting to one or the other, this error is
	// returned and the caller must decide how to decode the address.
	ErrAddressCollision = errors.New("address collision")

	// ErrInvalidFormat describes an error where decoding failed due to invalid version
	ErrInvalidFormat = errors.New("invalid format: version and/or checksum bytes missing")

	NetIDs = map[string]NetID{
		chaincfg.MainNetParams.Name:       NetID{[]byte{0x1c, 0xb8}, []byte{0x1c, 0xbd}, []byte{0x16, 0x9a}},
		chaincfg.TestNet3Params.Name:      NetID{[]byte{0x1d, 0x25}, []byte{0x1c, 0xba}, []byte{0x16, 0xb6}},
		chaincfg.RegressionNetParams.Name: NetID{[]byte{0x1d, 0x25}, []byte{0x1c, 0xba}, []byte{0x16, 0xb6}},
	}
)
View Source
var (
	PrevoutsHashPersonalization   = []byte("ZcashPrevoutHash")
	SequenceHashPersonalization   = []byte("ZcashSequencHash")
	OutputsHashPersonalization    = []byte("ZcashOutputsHash")
	JoinSplitsHashPersonalization = []byte("ZcashJSplitsHash")
)
View Source
var (
	ErrOverwinterTxVersionTooLow = fmt.Errorf("overwinter transaction version too low")
	ErrUnknownTxVersionGroupID   = fmt.Errorf("transaction has unknown version group id")
	ErrTxExpiryHeightIsTooHigh   = fmt.Errorf("transaction expiry height is too high")
	ErrTxVersionTooLow           = fmt.Errorf("transaction version too low")
	ErrTxVersionTooHigh          = fmt.Errorf("transaction version too high")
	ErrNoTxInputs                = fmt.Errorf("transaction has no inputs")
	ErrNoTxOutputs               = fmt.Errorf("transaction has no outputs")
	ErrDuplicateTxInputs         = fmt.Errorf("transaction contains duplicate inputs")
	ErrDuplicateTxNullifiers     = fmt.Errorf("transaction contains duplicate nullifiers")
	ErrPrevOutIsNull             = fmt.Errorf("transaction input refers to null previous output")
	ErrCoinBaseTxHasJoinSplits   = fmt.Errorf("coinbase transaction has joinsplits")
	ErrCoinBaseTxHasOutputs      = fmt.Errorf("coinbase transaction has outputs")
)
View Source
var BumpFeeAlreadyConfirmedError = errors.New("Transaction is confirmed, cannot bump fee")
View Source
var BumpFeeNotFoundError = errors.New("Transaction either doesn't exist or has already been spent")
View Source
var BumpFeeTransactionDeadError = errors.New("Cannot bump fee of dead transaction")

Functions

func CheckDecode

func CheckDecode(input string) (result []byte, version []byte, err error)

CheckDecode decodes a string that was encoded with CheckEncode and verifies the checksum.

func CheckEncode

func CheckEncode(input []byte, version []byte) string

CheckEncode prepends a version byte and appends a four byte checksum.

func DecodeAddress

func DecodeAddress(addr string, defaultNet *chaincfg.Params) (btcutil.Address, error)

DecodeAddress decodes the string encoding of an address and returns the Address if addr is a valid encoding for a known address type.

The zcash network the address is associated with is extracted if possible.

func EstimateSerializeSize

func EstimateSerializeSize(inputCount int, txOuts []Output, addChangeOutput bool, inputType InputType) int

EstimateSerializeSize is reused from spvwallet and modified to be less btc-specific

EstimateSerializeSize returns a worst case serialize size estimate for a signed transaction that spends inputCount number of compressed P2PKH outputs and contains each transaction output from txOuts. The estimated size is incremented for an additional P2PKH change output if addChangeOutput is true.

TODO: Include joinsplits in the size estimate

func ExtractPkScriptAddrs

func ExtractPkScriptAddrs(pkScript []byte, chainParams *chaincfg.Params) (btcutil.Address, error)

ExtractPkScriptAddrs returns the type of script, addresses and required signatures associated with the passed PkScript. Note that it only works for 'standard' transaction script types. Any data such as public keys which are invalid are omitted from the results.

func KeyToAddress

func KeyToAddress(key *hd.ExtendedKey, params *chaincfg.Params) (btcutil.Address, error)

func KeysToAddresses

func KeysToAddresses(params *chaincfg.Params, keys []*hd.ExtendedKey) (addrs []btcutil.Address, err error)

func MoneyRange

func MoneyRange(v int64) bool

func NewCoin

func NewCoin(txid []byte, index uint32, value btc.Amount, numConfs int64, scriptPubKey []byte) coinset.Coin

func PayToAddrScript

func PayToAddrScript(addr btcutil.Address) ([]byte, error)

PayToAddrScript creates a new script to pay a transaction output to a the specified address.

func ProduceSignature

func ProduceSignature(
	params *chaincfg.Params,
	tx *Transaction,
	idx int,
	pkScript []byte,
	hashType txscript.SigHashType,
	kdb txscript.KeyDB,
	sdb txscript.ScriptDB,
	previousScript []byte,
) ([]byte, error)

TODO: Support pre-overwinter v2 joinsplit transactions here (maybe)

func PushAll

func PushAll(scripts [][]byte) ([]byte, error)

func Sign1

func Sign1(address btc.Address, creator SignatureCreator, scriptCode []byte, consensusBranchId uint32) ([]byte, bool)

func SignN

func SignN(params *chaincfg.Params, multisigdata [][]byte, creator SignatureCreator, scriptCode []byte, consensusBranchId uint32) ([][]byte, bool)

func SignStep

func SignStep(params *chaincfg.Params, creator SignatureCreator, scriptPubKey []byte, consensusBranchId uint32) ([][]byte, txscript.ScriptClass, bool)

*

  • Sign scriptPubKey using signature made with creator.
  • Signatures are returned in scriptSigRet (or returns false if scriptPubKey can't be signed),
  • unless scriptClass is txscript.ScriptHashTy, in which case scriptSigRet is the redemption script.
  • Returns false if scriptPubKey could not be completely satisfied.

func SignatureHash

func SignatureHash(scriptCode []byte, tx *Transaction, idx int, hashType txscript.SigHashType, consensusBranchId uint32) ([]byte, error)

func SumOutputSerializeSizes

func SumOutputSerializeSizes(outputs []Output) (serializeSize int)

SumOutputSerializeSizes is reused from spvwallet and modified to be less btc-specific

SumOutputSerializeSizes sums up the serialized size of the supplied outputs.

Types

type AddressPubKeyHash

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

AddressPubKeyHash is an Address for a pay-to-pubkey-hash (P2PKH) transaction.

func NewAddressPubKeyHash

func NewAddressPubKeyHash(pkHash []byte, net *chaincfg.Params) (*AddressPubKeyHash, error)

NewAddressPubKeyHash returns a new AddressPubKeyHash. pkHash mustbe 20 bytes.

func (*AddressPubKeyHash) EncodeAddress

func (a *AddressPubKeyHash) EncodeAddress() string

EncodeAddress returns the string encoding of a pay-to-pubkey-hash address. Part of the Address interface.

func (*AddressPubKeyHash) Hash160

func (a *AddressPubKeyHash) Hash160() *[ripemd160.Size]byte

Hash160 returns the underlying array of the pubkey hash. This can be useful when an array is more appropiate than a slice (for example, when used as map keys).

func (*AddressPubKeyHash) IsForNet

func (a *AddressPubKeyHash) IsForNet(net *chaincfg.Params) bool

IsForNet returns whether or not the pay-to-pubkey-hash address is associated with the passed zcash network.

func (*AddressPubKeyHash) ScriptAddress

func (a *AddressPubKeyHash) ScriptAddress() []byte

ScriptAddress returns the bytes to be included in a txout script to pay to a pubkey hash. Part of the Address interface.

func (*AddressPubKeyHash) String

func (a *AddressPubKeyHash) String() string

String returns a human-readable string for the pay-to-pubkey-hash address. This is equivalent to calling EncodeAddress, but is provided so the type can be used as a fmt.Stringer.

type AddressScriptHash

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

AddressScriptHash is an Address for a pay-to-script-hash (P2SH) transaction.

func NewAddressScriptHash

func NewAddressScriptHash(serializedScript []byte, net *chaincfg.Params) (*AddressScriptHash, error)

NewAddressScriptHash returns a new AddressScriptHash.

func NewAddressScriptHashFromHash

func NewAddressScriptHashFromHash(scriptHash []byte, net *chaincfg.Params) (*AddressScriptHash, error)

NewAddressScriptHashFromHash returns a new AddressScriptHash. scriptHash must be 20 bytes.

func (*AddressScriptHash) EncodeAddress

func (a *AddressScriptHash) EncodeAddress() string

EncodeAddress returns the string encoding of a pay-to-script-hash address. Part of the Address interface.

func (*AddressScriptHash) Hash160

func (a *AddressScriptHash) Hash160() *[ripemd160.Size]byte

Hash160 returns the underlying array of the script hash. This can be useful when an array is more appropiate than a slice (for example, when used as map keys).

func (*AddressScriptHash) IsForNet

func (a *AddressScriptHash) IsForNet(net *chaincfg.Params) bool

IsForNet returns whether or not the pay-to-script-hash address is associated with the passed zcash network.

func (*AddressScriptHash) ScriptAddress

func (a *AddressScriptHash) ScriptAddress() []byte

ScriptAddress returns the bytes to be included in a txout script to pay to a script hash. Part of the Address interface.

func (*AddressScriptHash) String

func (a *AddressScriptHash) String() string

String returns a human-readable string for the pay-to-script-hash address. This is equivalent to calling EncodeAddress, but is provided so the type can be used as a fmt.Stringer.

type Coin

type Coin struct {
	TxHash       *chainhash.Hash
	TxIndex      uint32
	TxValue      btc.Amount
	TxNumConfs   int64
	ScriptPubKey []byte
}

func (*Coin) Hash

func (c *Coin) Hash() *chainhash.Hash

func (*Coin) Index

func (c *Coin) Index() uint32

func (*Coin) NumConfs

func (c *Coin) NumConfs() int64

func (*Coin) PkScript

func (c *Coin) PkScript() []byte

func (*Coin) Value

func (c *Coin) Value() btc.Amount

func (*Coin) ValueAge

func (c *Coin) ValueAge() int64

type Config

type Config struct {
	Mnemonic string
	Params   *chaincfg.Params
	DB       wallet.Datastore
	Proxy    proxy.Dialer
}

func (Config) MasterKeys

func (c Config) MasterKeys() (priv, pub *hd.ExtendedKey)

MasterKeys generates the master private and public keys for this mnemonic and network params

type Input

type Input struct {
	PreviousOutPoint wire.OutPoint
	SignatureScript  []byte
	Sequence         uint32
}

func (Input) IsEqual

func (i Input) IsEqual(other Input) bool

func (*Input) ReadFrom

func (i *Input) ReadFrom(r io.Reader) (int64, error)

func (*Input) WriteTo

func (i *Input) WriteTo(w io.Writer) (int64, error)

type InputSource

type InputSource func(target btc.Amount) (total btc.Amount, inputs []Input, scripts [][]byte, err error)

type InputType

type InputType int
const (
	P2PKH InputType = iota
	P2SH_1of2_Multisig
	P2SH_2of3_Multisig
	P2SH_Multisig_Timelock_1Sig
	P2SH_Multisig_Timelock_2Sigs
)

type InsightClient

type InsightClient interface {
	GetInfo() (*client.Info, error)
	GetBestBlock() (*client.Block, error)
	GetBlocksBefore(time.Time, int) (*client.BlockList, error)
	GetTransactions(addrs []btc.Address) ([]client.Transaction, error)
	GetRawTransaction(txid string) ([]byte, error)
	BlockNotify() <-chan client.Block
	TransactionNotify() <-chan client.Transaction
	Broadcast(tx []byte) (string, error)
	EstimateFee(nbBlocks int) (int, error)
	ListenAddress(addr btc.Address)
	Close()
}

type JoinSplit

type JoinSplit struct {
	// A value v_{pub}^{old} that the JoinSplit transfer removes from the
	// transparent value pool.
	VPubOld uint64

	// A value v_{pub}^{new} that the JoinSplit transfer inserts into the
	// transparent value pool.
	VPubNew uint64

	// A merkle root of the note commitment tree at some block height in the
	// past, or the merkle root produced by a previous JoinSplit transfer in this
	// transaction.
	//
	// JoinSplits are always anchored to a root in the note commitment tree at
	// some point in the blockchain history or in the history of the current
	// transaction.
	Anchor [32]byte

	// A sequence of nullifiers of the input notes $nf$_{1..N^{old}}^{old}
	//
	// Nullifiers are used to prevent double-spends. They are derived from the
	// secrets placed in the note and the secret spend-authority key known by the
	// spender.
	Nullifiers [NumJoinSplitInputs][32]byte

	// A sequence of note commitments for the output notes $cm$_{1..N^{new}}^{new}
	//
	// Note commitments are introduced into the commitment tree, blinding the
	// public about the values and destinations involved in the JoinSplit. The
	// presence of a commitment in the note commitment tree is required to spend
	// it.
	Commitments [NumJoinSplitOutputs][32]byte

	// A Curve25519 public key epk.
	EphemeralKey [32]byte

	// A 256-bit seed that must be chosen independently at random for each
	// JoinSplit description.
	RandomSeed [32]byte

	// A sequence of message authentication tags h_{1..N^{old}} that bind h^{Sig}
	// to each a_{sk} of the JoinSplit description.
	//
	// The verification of the JoinSplit requires these MACs to be provided as an
	// input.
	Macs [NumJoinSplitInputs][32]byte

	// An encoding of the zero-knowledge proof \pi_{ZKJoinSplit}
	//
	// This is a zk-SNARK which ensures that this JoinSplit is valid.
	Proof [296]byte

	// A sequence of ciphertext components for the encrypted output notes,
	// C_{1..N^{new}}^{enc}
	//
	// These contain trapdoors, values and other information that the recipient
	// needs, including a memo field. It is encrypted using the scheme
	// implemented in crypto/NoteEncryption.cpp
	Ciphertexts [NumJoinSplitOutputs][601]byte
}

func (JoinSplit) IsEqual

func (js JoinSplit) IsEqual(other JoinSplit) bool

func (*JoinSplit) ReadFrom

func (js *JoinSplit) ReadFrom(r io.Reader) (int64, error)

func (*JoinSplit) WriteTo

func (js *JoinSplit) WriteTo(w io.Writer) (n int64, err error)

type NetID

type NetID struct {
	AddressPubKeyHash []byte
	AddressScriptHash []byte
	ZAddress          []byte
}

type Output

type Output struct {
	Value        int64
	ScriptPubKey []byte
}

func (Output) IsEqual

func (o Output) IsEqual(other Output) bool

func (*Output) IsFoundersReward

func (o *Output) IsFoundersReward(params *chaincfg.Params) bool

func (*Output) ReadFrom

func (o *Output) ReadFrom(r io.Reader) (int64, error)

func (*Output) SerializeSize

func (o *Output) SerializeSize() int

SerializeSize returns the number of bytes it would take to serialize the the transaction output.

func (*Output) WriteTo

func (o *Output) WriteTo(w io.Writer) (int64, error)

type SignatureCreator

type SignatureCreator interface {
	CreateSig(address btc.Address, scriptCode []byte, consensusBranchId uint32) ([]byte, bool)
	txscript.KeyDB
	txscript.ScriptDB
}

func TransactionSignatureCreator

func TransactionSignatureCreator(kdb txscript.KeyDB, sdb txscript.ScriptDB, tx *Transaction, idx int, hashType txscript.SigHashType) SignatureCreator

type Transaction

type Transaction struct {
	IsOverwinter       bool
	Version            uint32
	VersionGroupID     uint32
	Inputs             []Input
	Outputs            []Output
	LockTime           uint32
	ExpiryHeight       uint32
	JoinSplits         []JoinSplit
	JoinSplitPubKey    [32]byte
	JoinSplitSignature [64]byte
}

func NewUnsignedTransaction

func NewUnsignedTransaction(outputs []Output, feePerKb btc.Amount, fetchInputs InputSource, fetchChange txauthor.ChangeSource, isOverwinter bool) (*Transaction, error)

NewUnsignedTransaction is reused from spvwallet and modified to be less btc-specific

func (*Transaction) GetHeader

func (t *Transaction) GetHeader() uint32

func (*Transaction) IsCoinBase

func (t *Transaction) IsCoinBase() bool

IsCoinBase determines whether or not a transaction is a coinbase. A coinbase is a special transaction created by miners that has no inputs. This is represented in the block chain by a transaction with a single input that has a previous output transaction index set to the maximum value along with a zero hash.

func (*Transaction) IsEqual

func (t *Transaction) IsEqual(other *Transaction) bool

func (*Transaction) MarshalBinary

func (t *Transaction) MarshalBinary() ([]byte, error)

func (*Transaction) ReadFrom

func (t *Transaction) ReadFrom(r io.Reader) (n int64, err error)

func (*Transaction) Sort

func (t *Transaction) Sort()

Sort in-place sorts the inputs and outputs for BIP 69

func (*Transaction) TxHash

func (t *Transaction) TxHash() chainhash.Hash

TxHash generates the Hash for the transaction.

func (*Transaction) UnmarshalBinary

func (t *Transaction) UnmarshalBinary(data []byte) error

func (*Transaction) Validate

func (tx *Transaction) Validate(params *chaincfg.Params) error

func (*Transaction) WriteTo

func (t *Transaction) WriteTo(w io.Writer) (n int64, err error)

type TxStore

type TxStore struct {
	wallet.Datastore
	// contains filtered or unexported fields
}

func NewTxStore

func NewTxStore(p *chaincfg.Params, db wallet.Datastore, keyManager *keys.KeyManager) (*TxStore, error)

func (*TxStore) CheckDoubleSpends

func (ts *TxStore) CheckDoubleSpends(argTx *Transaction) ([]*chainhash.Hash, error)

GetDoubleSpends takes a transaction and compares it with all transactions in the db. It returns a slice of all txids in the db which are double spent by the received tx.

func (*TxStore) Ingest

func (ts *TxStore) Ingest(tx *Transaction, raw []byte, height int32, timestamp time.Time) (uint32, error)

Ingest puts a tx into the DB atomically. This can result in a gain, a loss, or no result. Gain or loss in satoshis is returned.

func (*TxStore) PopulateAdrs

func (ts *TxStore) PopulateAdrs() error

PopulateAdrs just puts a bunch of adrs in ram; it doesn't touch the DB

type Wallet

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

func NewWallet

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

func (*Wallet) AddTransactionListener

func (w *Wallet) AddTransactionListener(callback func(wallet.TransactionCallback))

Add a callback for incoming transactions

func (*Wallet) AddWatchedScript

func (w *Wallet) AddWatchedScript(script []byte) error

Add a script to the wallet and get notifications back when coins are received or spent from it

func (*Wallet) AddressToScript

func (w *Wallet) AddressToScript(addr btc.Address) ([]byte, error)

Turn the given address into an output script

func (*Wallet) Balance

func (w *Wallet) Balance() (confirmed, unconfirmed int64)

Get the confirmed and unconfirmed balances TODO: Handle this error TODO: Maybe we could just use insight api for this

func (*Wallet) BumpFee

func (w *Wallet) BumpFee(txid chainhash.Hash) (*chainhash.Hash, error)

func (*Wallet) ChainTip

func (w *Wallet) ChainTip() (uint32, chainhash.Hash)

Get the height and best hash of the blockchain TODO: We should fetch all blocks and watch for changes here instead of being so dependent on the insight api

func (*Wallet) Close

func (w *Wallet) Close()

Cleanly disconnect from the wallet

func (*Wallet) CreateMultisigSignature

func (w *Wallet) CreateMultisigSignature(ins []wallet.TransactionInput, outs []wallet.TransactionOutput, key *hd.ExtendedKey, redeemScript []byte, feePerByte uint64) ([]wallet.Signature, error)

Create a signature for a multisig transaction

func (*Wallet) CurrencyCode

func (w *Wallet) CurrencyCode() string

Returns the type of crytocurrency this wallet implements

func (*Wallet) CurrentAddress

func (w *Wallet) CurrentAddress(purpose wallet.KeyPurpose) btc.Address

Get the current address for the given purpose TODO: Handle these errors

func (*Wallet) DecodeAddress

func (w *Wallet) DecodeAddress(addr string) (btc.Address, error)

Parse the address string and return an address interface

func (*Wallet) EstimateFee

func (w *Wallet) EstimateFee(ins []wallet.TransactionInput, outs []wallet.TransactionOutput, feePerByte uint64) uint64

Calculates the estimated size of the transaction and returns the total fee for the given feePerByte

func (*Wallet) EstimateSpendFee

func (w *Wallet) EstimateSpendFee(amount int64, feeLevel wallet.FeeLevel) (uint64, error)

Build a spend transaction for the amount and return the transaction fee

func (*Wallet) GenerateMultisigScript

func (w *Wallet) GenerateMultisigScript(keys []hd.ExtendedKey, threshold int, timeout time.Duration, timeoutKey *hd.ExtendedKey) (addr btc.Address, redeemScript []byte, err error)

Generate a multisig script from public keys. If a timeout is included the returned script should be a timelocked escrow which releases using the timeoutKey.

func (*Wallet) GetConfirmations

func (w *Wallet) GetConfirmations(txid chainhash.Hash) (confirms, atHeight uint32, err error)

Return the number of confirmations and the height for a transaction

func (*Wallet) GetFeePerByte

func (w *Wallet) GetFeePerByte(feeLevel wallet.FeeLevel) uint64

Get the current fee per byte

func (*Wallet) GetTransaction

func (w *Wallet) GetTransaction(txid chainhash.Hash) (wallet.Txn, error)

Get info on a specific transaction

func (*Wallet) HasKey

func (w *Wallet) HasKey(addr btc.Address) bool

Returns if the wallet has the key for the given address

func (*Wallet) IsDust

func (w *Wallet) IsDust(amount int64) bool

Check if this amount is considered dust

func (*Wallet) MainNetworkEnabled

func (w *Wallet) MainNetworkEnabled() bool

MainNetworkEnabled indicates if the current network being used is the live Network

func (*Wallet) MasterPrivateKey

func (w *Wallet) MasterPrivateKey() *hd.ExtendedKey

Get the master private key

func (*Wallet) MasterPublicKey

func (w *Wallet) MasterPublicKey() *hd.ExtendedKey

Get the master public key

func (*Wallet) Multisign

func (w *Wallet) Multisign(ins []wallet.TransactionInput, outs []wallet.TransactionOutput, sigs1 []wallet.Signature, sigs2 []wallet.Signature, redeemScript []byte, feePerByte uint64, broadcast bool) ([]byte, error)

Combine signatures and optionally broadcast

func (*Wallet) NewAddress

func (w *Wallet) NewAddress(purpose wallet.KeyPurpose) btc.Address

Returns a fresh address that has never been returned by this function

func (*Wallet) Params

func (w *Wallet) Params() *chaincfg.Params

Return the network parameters

func (*Wallet) ReSyncBlockchain

func (w *Wallet) ReSyncBlockchain(fromDate time.Time)

func (*Wallet) RegressionNetworkEnabled

func (w *Wallet) RegressionNetworkEnabled() bool

RegressionNetworkEnabled indicates if the current network being used is Regression Network

func (*Wallet) ScriptToAddress

func (w *Wallet) ScriptToAddress(script []byte) (btc.Address, error)

Turn the given output script into an address

func (*Wallet) Spend

func (w *Wallet) Spend(amount int64, addr btc.Address, feeLevel wallet.FeeLevel) (*chainhash.Hash, error)

func (*Wallet) Start

func (w *Wallet) Start()

func (*Wallet) SweepAddress

func (w *Wallet) SweepAddress(utxos []wallet.Utxo, address *btc.Address, key *hd.ExtendedKey, redeemScript *[]byte, feeLevel wallet.FeeLevel) (*chainhash.Hash, error)

Build and broadcast a transaction that sweeps all coins from an address. If it is a p2sh multisig, the redeemScript must be included

func (*Wallet) TestNetworkEnabled

func (w *Wallet) TestNetworkEnabled() bool

TestNetworkEnabled indicates if the current network being used is Test Network

func (*Wallet) Transactions

func (w *Wallet) Transactions() ([]wallet.Txn, error)

Jump to

Keyboard shortcuts

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