2013-09-09 20:14:57 +02:00
|
|
|
/*
|
|
|
|
* Copyright (c) 2013 Conformal Systems LLC <info@conformal.com>
|
|
|
|
*
|
|
|
|
* Permission to use, copy, modify, and distribute this software for any
|
|
|
|
* purpose with or without fee is hereby granted, provided that the above
|
|
|
|
* copyright notice and this permission notice appear in all copies.
|
|
|
|
*
|
|
|
|
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
|
|
|
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
|
|
|
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
|
|
|
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
|
|
|
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
|
|
|
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
|
|
|
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
|
|
|
*/
|
|
|
|
|
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"github.com/conformal/btcscript"
|
|
|
|
"github.com/conformal/btcutil"
|
|
|
|
"github.com/conformal/btcwallet/tx"
|
|
|
|
"github.com/conformal/btcwire"
|
|
|
|
"sort"
|
2013-10-07 21:14:39 +02:00
|
|
|
"sync"
|
2013-09-09 20:14:57 +02:00
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
// ErrInsufficientFunds represents an error where there are not enough
|
|
|
|
// funds from unspent tx outputs for a wallet to create a transaction.
|
|
|
|
var ErrInsufficientFunds = errors.New("insufficient funds")
|
|
|
|
|
|
|
|
// ErrUnknownBitcoinNet represents an error where the parsed or
|
|
|
|
// requested bitcoin network is invalid (neither mainnet nor testnet).
|
|
|
|
var ErrUnknownBitcoinNet = errors.New("unknown bitcoin network")
|
|
|
|
|
2013-10-07 21:14:39 +02:00
|
|
|
// TxFee represents the global transaction fee added to newly-created
|
|
|
|
// transactions and sent as a reward to the block miner.
|
|
|
|
var TxFee struct {
|
|
|
|
sync.Mutex
|
|
|
|
i int64
|
|
|
|
}
|
|
|
|
|
2013-09-09 20:14:57 +02:00
|
|
|
// ByAmount defines the methods needed to satisify sort.Interface to
|
|
|
|
// sort a slice of Utxos by their amount.
|
|
|
|
type ByAmount []*tx.Utxo
|
|
|
|
|
|
|
|
func (u ByAmount) Len() int {
|
|
|
|
return len(u)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (u ByAmount) Less(i, j int) bool {
|
|
|
|
return u[i].Amt < u[j].Amt
|
|
|
|
}
|
|
|
|
|
|
|
|
func (u ByAmount) Swap(i, j int) {
|
|
|
|
u[i], u[j] = u[j], u[i]
|
|
|
|
}
|
|
|
|
|
2013-10-14 22:14:04 +02:00
|
|
|
// selectInputs selects the minimum number possible of unspent
|
2013-09-09 20:14:57 +02:00
|
|
|
// outputs to use to create a new transaction that spends amt satoshis.
|
2013-10-14 22:14:04 +02:00
|
|
|
// Previous outputs with less than minconf confirmations are ignored. btcout
|
|
|
|
// is the total number of satoshis which would be spent by the combination
|
|
|
|
// of all selected previous outputs. err will equal ErrInsufficientFunds if there
|
2013-09-09 20:14:57 +02:00
|
|
|
// are not enough unspent outputs to spend amt.
|
2013-10-14 22:14:04 +02:00
|
|
|
func selectInputs(s tx.UtxoStore, amt uint64, minconf int) (inputs []*tx.Utxo, btcout uint64, err error) {
|
2013-09-09 20:14:57 +02:00
|
|
|
height := getCurHeight()
|
|
|
|
|
2013-10-14 22:14:04 +02:00
|
|
|
// Create list of eligible unspent previous outputs to use as tx
|
|
|
|
// inputs, and sort by the amount in reverse order so a minimum number
|
|
|
|
// of inputs is needed.
|
2013-09-09 20:14:57 +02:00
|
|
|
var eligible []*tx.Utxo
|
|
|
|
for _, utxo := range s {
|
|
|
|
if int(height-utxo.Height) >= minconf {
|
|
|
|
eligible = append(eligible, utxo)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
sort.Sort(sort.Reverse(ByAmount(eligible)))
|
|
|
|
|
2013-10-14 22:14:04 +02:00
|
|
|
// Iterate throguh eligible transactions, appending to outputs and
|
2013-09-09 20:14:57 +02:00
|
|
|
// increasing btcout. This is finished when btcout is greater than the
|
|
|
|
// requested amt to spend.
|
|
|
|
for _, u := range eligible {
|
2013-10-14 22:14:04 +02:00
|
|
|
inputs = append(inputs, u)
|
2013-09-09 20:14:57 +02:00
|
|
|
if btcout += u.Amt; btcout >= amt {
|
2013-10-14 22:14:04 +02:00
|
|
|
return inputs, btcout, nil
|
2013-09-09 20:14:57 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
if btcout < amt {
|
|
|
|
return nil, 0, ErrInsufficientFunds
|
|
|
|
}
|
|
|
|
|
2013-10-14 22:14:04 +02:00
|
|
|
return inputs, btcout, nil
|
2013-09-09 20:14:57 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// txToPairs creates a raw transaction sending the amounts for each
|
|
|
|
// address/amount pair and fee to each address and the miner. minconf
|
|
|
|
// specifies the minimum number of confirmations required before an
|
|
|
|
// unspent output is eligible for spending. Leftover input funds not sent
|
|
|
|
// to addr or as a fee for the miner are sent to a newly generated
|
|
|
|
// address. ErrInsufficientFunds is returned if there are not enough
|
|
|
|
// eligible unspent outputs to create the transaction.
|
2013-10-14 22:14:04 +02:00
|
|
|
func (w *BtcWallet) txToPairs(pairs map[string]uint64, fee uint64, minconf int) (rawtx []byte, inputs []*tx.Utxo, err error) {
|
2013-09-09 20:14:57 +02:00
|
|
|
// Recorded unspent transactions should not be modified until this
|
|
|
|
// finishes.
|
|
|
|
w.UtxoStore.RLock()
|
|
|
|
defer w.UtxoStore.RUnlock()
|
|
|
|
|
|
|
|
// Create a new transaction which will include all input scripts.
|
|
|
|
msgtx := btcwire.NewMsgTx()
|
|
|
|
|
|
|
|
// Calculate minimum amount needed for inputs.
|
|
|
|
var amt uint64
|
|
|
|
for _, v := range pairs {
|
|
|
|
amt += v
|
|
|
|
}
|
|
|
|
|
|
|
|
// Select unspent outputs to be used in transaction.
|
2013-10-14 22:14:04 +02:00
|
|
|
inputs, btcout, err := selectInputs(w.UtxoStore.s, amt+fee, minconf)
|
2013-09-09 20:14:57 +02:00
|
|
|
if err != nil {
|
2013-10-14 22:14:04 +02:00
|
|
|
return nil, nil, err
|
2013-09-09 20:14:57 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Add outputs to new tx.
|
|
|
|
for addr, amt := range pairs {
|
|
|
|
addr160, _, err := btcutil.DecodeAddress(addr)
|
|
|
|
if err != nil {
|
2013-10-14 22:14:04 +02:00
|
|
|
return nil, nil, fmt.Errorf("cannot decode address: %s", err)
|
2013-09-09 20:14:57 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Spend amt to addr160
|
|
|
|
pkScript, err := btcscript.PayToPubKeyHashScript(addr160)
|
|
|
|
if err != nil {
|
2013-10-14 22:14:04 +02:00
|
|
|
return nil, nil, fmt.Errorf("cannot create txout script: %s", err)
|
2013-09-09 20:14:57 +02:00
|
|
|
}
|
|
|
|
txout := btcwire.NewTxOut(int64(amt), pkScript)
|
|
|
|
msgtx.AddTxOut(txout)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check if there are leftover unspent outputs, and return coins back to
|
|
|
|
// a new address we own.
|
|
|
|
if btcout > amt+fee {
|
|
|
|
// Create a new address to spend leftover outputs to.
|
|
|
|
// TODO(jrick): use the next chained address, not the next unused.
|
|
|
|
newaddr, err := w.NextUnusedAddress()
|
|
|
|
if err != nil {
|
2013-10-14 22:14:04 +02:00
|
|
|
return nil, nil, fmt.Errorf("failed to get next unused address: %s", err)
|
2013-09-09 20:14:57 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Spend change
|
|
|
|
change := btcout - (amt + fee)
|
|
|
|
newaddr160, _, err := btcutil.DecodeAddress(newaddr)
|
|
|
|
if err != nil {
|
2013-10-14 22:14:04 +02:00
|
|
|
return nil, nil, fmt.Errorf("cannot decode new address: %s", err)
|
2013-09-09 20:14:57 +02:00
|
|
|
}
|
|
|
|
pkScript, err := btcscript.PayToPubKeyHashScript(newaddr160)
|
|
|
|
if err != nil {
|
2013-10-14 22:14:04 +02:00
|
|
|
return nil, nil, fmt.Errorf("cannot create txout script: %s", err)
|
2013-09-09 20:14:57 +02:00
|
|
|
}
|
2013-10-11 16:53:55 +02:00
|
|
|
msgtx.AddTxOut(btcwire.NewTxOut(int64(change), pkScript))
|
2013-09-09 20:14:57 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Selected unspent outputs become new transaction's inputs.
|
2013-10-14 22:14:04 +02:00
|
|
|
for _, ip := range inputs {
|
|
|
|
msgtx.AddTxIn(btcwire.NewTxIn((*btcwire.OutPoint)(&ip.Out), nil))
|
2013-09-09 20:14:57 +02:00
|
|
|
}
|
2013-10-14 22:14:04 +02:00
|
|
|
for i, ip := range inputs {
|
|
|
|
addrstr, err := btcutil.EncodeAddress(ip.AddrHash[:], w.Wallet.Net())
|
2013-09-09 20:14:57 +02:00
|
|
|
if err != nil {
|
2013-10-14 22:14:04 +02:00
|
|
|
return nil, nil, err
|
2013-09-09 20:14:57 +02:00
|
|
|
}
|
|
|
|
privkey, err := w.GetAddressKey(addrstr)
|
|
|
|
if err != nil {
|
2013-10-14 22:14:04 +02:00
|
|
|
return nil, nil, fmt.Errorf("cannot get address key: %v", err)
|
2013-09-09 20:14:57 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// TODO(jrick): we want compressed pubkeys. Switch wallet to
|
|
|
|
// generate addresses from the compressed key. This will break
|
|
|
|
// armory wallet compat but oh well.
|
|
|
|
sigscript, err := btcscript.SignatureScript(msgtx, i,
|
2013-10-14 22:14:04 +02:00
|
|
|
ip.Subscript, btcscript.SigHashAll, privkey, false)
|
2013-09-09 20:14:57 +02:00
|
|
|
if err != nil {
|
2013-10-14 22:14:04 +02:00
|
|
|
return nil, nil, fmt.Errorf("cannot create sigscript: %s", err)
|
2013-09-09 20:14:57 +02:00
|
|
|
}
|
|
|
|
msgtx.TxIn[i].SignatureScript = sigscript
|
|
|
|
}
|
|
|
|
|
|
|
|
// Validate msgtx before returning the raw transaction.
|
2013-10-11 16:53:55 +02:00
|
|
|
bip16 := time.Now().After(btcscript.Bip16Activation)
|
2013-09-09 20:14:57 +02:00
|
|
|
for i, txin := range msgtx.TxIn {
|
2013-10-14 22:14:04 +02:00
|
|
|
engine, err := btcscript.NewScript(txin.SignatureScript, inputs[i].Subscript, i,
|
2013-10-11 16:53:55 +02:00
|
|
|
msgtx, bip16)
|
2013-09-09 20:14:57 +02:00
|
|
|
if err != nil {
|
2013-10-14 22:14:04 +02:00
|
|
|
return nil, nil, fmt.Errorf("cannot create script engine: %s", err)
|
2013-09-09 20:14:57 +02:00
|
|
|
}
|
|
|
|
if err = engine.Execute(); err != nil {
|
2013-10-14 22:14:04 +02:00
|
|
|
return nil, nil, fmt.Errorf("cannot validate transaction: %s", err)
|
2013-09-09 20:14:57 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
buf := new(bytes.Buffer)
|
|
|
|
msgtx.BtcEncode(buf, btcwire.ProtocolVersion)
|
2013-10-14 22:14:04 +02:00
|
|
|
return buf.Bytes(), inputs, nil
|
2013-09-09 20:14:57 +02:00
|
|
|
}
|