2013-08-21 16:37:30 +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 (
|
Perform smarter UTXO tracking.
This change fixes many issues with the tracking of unspent transaction
outputs. First, notifications for when UTXOs arse spent are now
requested from btcd, and when spent, will be removed from the
UtxoStore.
Second, when transactions are created, the unconfirmed (not yet in a
block) Utxo (with block height -1 and zeroed block hash) is added to
the wallet's UtxoStore. Notifications for when this UTXO is spent are
also requested from btcd. After the tx appears in a block, because
the UTXO has a pkScript to be spent by another owned wallet address, a
notification with the UTXO will be sent to btcwallet. We already
store the unconfirmed UTXO, so at this point the actual block height
and hash are filled in.
Finally, when calculating the balance, if confirmations is zero,
unconfirmed UTXOs (block height -1) will be included in the balance.
Otherwise, they are ignored.
2013-10-22 15:55:53 +02:00
|
|
|
"bytes"
|
2013-09-04 01:05:59 +02:00
|
|
|
"encoding/json"
|
2013-09-03 16:21:14 +02:00
|
|
|
"errors"
|
2013-08-21 16:37:30 +02:00
|
|
|
"fmt"
|
2013-09-04 01:05:59 +02:00
|
|
|
"github.com/conformal/btcjson"
|
2013-09-04 19:41:33 +02:00
|
|
|
"github.com/conformal/btcutil"
|
2013-09-03 06:10:32 +02:00
|
|
|
"github.com/conformal/btcwallet/tx"
|
2013-08-21 16:37:30 +02:00
|
|
|
"github.com/conformal/btcwallet/wallet"
|
2013-09-04 15:54:06 +02:00
|
|
|
"github.com/conformal/btcwire"
|
2013-08-21 16:37:30 +02:00
|
|
|
"github.com/conformal/seelog"
|
|
|
|
"os"
|
2013-09-03 06:10:32 +02:00
|
|
|
"path/filepath"
|
|
|
|
"sync"
|
2013-08-21 16:37:30 +02:00
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2013-09-05 21:31:39 +02:00
|
|
|
const (
|
|
|
|
satoshiPerBTC = 100000000
|
|
|
|
)
|
|
|
|
|
2013-09-03 16:21:14 +02:00
|
|
|
var (
|
2013-09-09 20:14:57 +02:00
|
|
|
// ErrNoWallet describes an error where a wallet does not exist and
|
|
|
|
// must be created first.
|
|
|
|
ErrNoWallet = errors.New("wallet file does not exist")
|
|
|
|
|
|
|
|
cfg *config
|
|
|
|
log = seelog.Default
|
2013-09-03 16:21:14 +02:00
|
|
|
|
2013-09-05 21:31:39 +02:00
|
|
|
curHeight = struct {
|
|
|
|
sync.RWMutex
|
|
|
|
h int64
|
|
|
|
}{
|
|
|
|
h: btcutil.BlockHeightUnknown,
|
|
|
|
}
|
2013-09-09 20:14:57 +02:00
|
|
|
wallets = NewBtcWalletStore()
|
2013-08-21 16:37:30 +02:00
|
|
|
)
|
|
|
|
|
2013-09-09 20:14:57 +02:00
|
|
|
// BtcWallet is a structure containing all the components for a
|
|
|
|
// complete wallet. It contains the Armory-style wallet (to store
|
|
|
|
// addresses and keys), and tx and utxo data stores, along with locks
|
|
|
|
// to prevent against incorrect multiple access.
|
2013-09-03 06:10:32 +02:00
|
|
|
type BtcWallet struct {
|
|
|
|
*wallet.Wallet
|
Perform smarter UTXO tracking.
This change fixes many issues with the tracking of unspent transaction
outputs. First, notifications for when UTXOs arse spent are now
requested from btcd, and when spent, will be removed from the
UtxoStore.
Second, when transactions are created, the unconfirmed (not yet in a
block) Utxo (with block height -1 and zeroed block hash) is added to
the wallet's UtxoStore. Notifications for when this UTXO is spent are
also requested from btcd. After the tx appears in a block, because
the UTXO has a pkScript to be spent by another owned wallet address, a
notification with the UTXO will be sent to btcwallet. We already
store the unconfirmed UTXO, so at this point the actual block height
and hash are filled in.
Finally, when calculating the balance, if confirmations is zero,
unconfirmed UTXOs (block height -1) will be included in the balance.
Otherwise, they are ignored.
2013-10-22 15:55:53 +02:00
|
|
|
mtx sync.RWMutex
|
|
|
|
name string
|
|
|
|
dirty bool
|
|
|
|
NewBlockTxSeqN uint64
|
|
|
|
SpentOutpointSeqN uint64
|
|
|
|
UtxoStore struct {
|
2013-09-04 01:05:59 +02:00
|
|
|
sync.RWMutex
|
|
|
|
dirty bool
|
|
|
|
s tx.UtxoStore
|
|
|
|
}
|
|
|
|
TxStore struct {
|
|
|
|
sync.RWMutex
|
|
|
|
dirty bool
|
|
|
|
s tx.TxStore
|
|
|
|
}
|
2013-09-03 06:10:32 +02:00
|
|
|
}
|
|
|
|
|
2013-10-14 22:39:15 +02:00
|
|
|
// BtcWalletStore stores all wallets currently being handled by
|
|
|
|
// btcwallet. Wallet are stored in a map with the account name as the
|
|
|
|
// key. A RWMutex is used to protect against incorrect concurrent
|
|
|
|
// access.
|
2013-09-09 20:14:57 +02:00
|
|
|
type BtcWalletStore struct {
|
|
|
|
sync.RWMutex
|
|
|
|
m map[string]*BtcWallet
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewBtcWalletStore returns an initialized and empty BtcWalletStore.
|
|
|
|
func NewBtcWalletStore() *BtcWalletStore {
|
|
|
|
return &BtcWalletStore{
|
|
|
|
m: make(map[string]*BtcWallet),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2013-10-14 22:39:15 +02:00
|
|
|
// Rollback rolls back each BtcWallet saved in the store.
|
2013-09-09 20:14:57 +02:00
|
|
|
func (s *BtcWalletStore) Rollback(height int64, hash *btcwire.ShaHash) {
|
|
|
|
s.Lock()
|
|
|
|
for _, w := range s.m {
|
|
|
|
w.Rollback(height, hash)
|
|
|
|
}
|
|
|
|
s.Unlock()
|
|
|
|
}
|
|
|
|
|
2013-10-14 22:39:15 +02:00
|
|
|
// Rollback reverts each stored BtcWallet to a state before the block
|
|
|
|
// with the passed chainheight and block hash was connected to the main
|
|
|
|
// chain. This is used to remove transactions and utxos for each wallet
|
|
|
|
// that occured on a chain no longer considered to be the main chain.
|
2013-09-09 20:14:57 +02:00
|
|
|
func (w *BtcWallet) Rollback(height int64, hash *btcwire.ShaHash) {
|
|
|
|
w.UtxoStore.Lock()
|
|
|
|
w.UtxoStore.dirty = w.UtxoStore.dirty || w.UtxoStore.s.Rollback(height, hash)
|
|
|
|
w.UtxoStore.Unlock()
|
|
|
|
|
|
|
|
w.TxStore.Lock()
|
|
|
|
w.TxStore.dirty = w.TxStore.dirty || w.TxStore.s.Rollback(height, hash)
|
|
|
|
w.TxStore.Unlock()
|
2013-10-15 22:55:28 +02:00
|
|
|
|
|
|
|
if err := w.writeDirtyToDisk(); err != nil {
|
|
|
|
log.Errorf("cannot sync dirty wallet: %v", err)
|
|
|
|
}
|
2013-09-09 20:14:57 +02:00
|
|
|
}
|
|
|
|
|
2013-09-03 15:49:16 +02:00
|
|
|
// walletdir returns the directory path which holds the wallet, utxo,
|
|
|
|
// and tx files.
|
|
|
|
func walletdir(cfg *config, account string) string {
|
2013-09-03 06:10:32 +02:00
|
|
|
var wname string
|
|
|
|
if account == "" {
|
|
|
|
wname = "btcwallet"
|
|
|
|
} else {
|
|
|
|
wname = fmt.Sprintf("btcwallet-%s", account)
|
|
|
|
}
|
|
|
|
|
2013-09-03 15:49:16 +02:00
|
|
|
return filepath.Join(cfg.DataDir, wname)
|
|
|
|
}
|
|
|
|
|
2013-09-09 20:14:57 +02:00
|
|
|
// OpenWallet opens a wallet described by account in the data
|
|
|
|
// directory specified by cfg. If the wallet does not exist, ErrNoWallet
|
|
|
|
// is returned as an error.
|
2013-10-17 17:16:45 +02:00
|
|
|
//
|
|
|
|
// Wallets opened from this function are not set to track against a
|
|
|
|
// btcd connection.
|
2013-09-03 16:21:14 +02:00
|
|
|
func OpenWallet(cfg *config, account string) (*BtcWallet, error) {
|
2013-09-03 15:49:16 +02:00
|
|
|
wdir := walletdir(cfg, account)
|
2013-09-03 06:10:32 +02:00
|
|
|
fi, err := os.Stat(wdir)
|
|
|
|
if err != nil {
|
|
|
|
if os.IsNotExist(err) {
|
|
|
|
// Attempt data directory creation
|
|
|
|
if err = os.MkdirAll(wdir, 0700); err != nil {
|
2013-09-09 20:14:57 +02:00
|
|
|
return nil, fmt.Errorf("cannot create data directory: %s", err)
|
2013-09-03 06:10:32 +02:00
|
|
|
}
|
|
|
|
} else {
|
2013-09-09 20:14:57 +02:00
|
|
|
return nil, fmt.Errorf("error checking data directory: %s", err)
|
2013-09-03 06:10:32 +02:00
|
|
|
}
|
|
|
|
} else {
|
|
|
|
if !fi.IsDir() {
|
2013-09-09 20:14:57 +02:00
|
|
|
return nil, fmt.Errorf("data directory '%s' is not a directory", cfg.DataDir)
|
2013-09-03 06:10:32 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
wfilepath := filepath.Join(wdir, "wallet.bin")
|
|
|
|
txfilepath := filepath.Join(wdir, "tx.bin")
|
|
|
|
utxofilepath := filepath.Join(wdir, "utxo.bin")
|
|
|
|
var wfile, txfile, utxofile *os.File
|
|
|
|
if wfile, err = os.Open(wfilepath); err != nil {
|
|
|
|
if os.IsNotExist(err) {
|
2013-09-03 16:21:14 +02:00
|
|
|
// Must create and save wallet first.
|
|
|
|
return nil, ErrNoWallet
|
2013-09-03 06:10:32 +02:00
|
|
|
}
|
2013-09-09 20:14:57 +02:00
|
|
|
return nil, fmt.Errorf("cannot open wallet file: %s", err)
|
2013-09-03 06:10:32 +02:00
|
|
|
}
|
2013-09-03 23:05:22 +02:00
|
|
|
defer wfile.Close()
|
2013-09-03 06:10:32 +02:00
|
|
|
if txfile, err = os.Open(txfilepath); err != nil {
|
|
|
|
if os.IsNotExist(err) {
|
|
|
|
if txfile, err = os.Create(txfilepath); err != nil {
|
2013-09-09 20:14:57 +02:00
|
|
|
return nil, fmt.Errorf("cannot create tx file: %s", err)
|
2013-09-03 06:10:32 +02:00
|
|
|
}
|
|
|
|
} else {
|
2013-09-09 20:14:57 +02:00
|
|
|
return nil, fmt.Errorf("cannot open tx file: %s", err)
|
2013-09-03 06:10:32 +02:00
|
|
|
}
|
|
|
|
}
|
2013-09-03 23:05:22 +02:00
|
|
|
defer txfile.Close()
|
2013-09-03 06:10:32 +02:00
|
|
|
if utxofile, err = os.Open(utxofilepath); err != nil {
|
|
|
|
if os.IsNotExist(err) {
|
|
|
|
if utxofile, err = os.Create(utxofilepath); err != nil {
|
2013-09-09 20:14:57 +02:00
|
|
|
return nil, fmt.Errorf("cannot create utxo file: %s", err)
|
2013-09-03 06:10:32 +02:00
|
|
|
}
|
|
|
|
} else {
|
2013-09-09 20:14:57 +02:00
|
|
|
return nil, fmt.Errorf("cannot open utxo file: %s", err)
|
2013-09-03 06:10:32 +02:00
|
|
|
}
|
|
|
|
}
|
2013-09-03 23:05:22 +02:00
|
|
|
defer utxofile.Close()
|
2013-09-03 06:10:32 +02:00
|
|
|
|
|
|
|
wlt := new(wallet.Wallet)
|
|
|
|
if _, err = wlt.ReadFrom(wfile); err != nil {
|
2013-09-09 20:14:57 +02:00
|
|
|
return nil, fmt.Errorf("cannot read wallet: %s", err)
|
2013-09-03 06:10:32 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
var txs tx.TxStore
|
|
|
|
if _, err = txs.ReadFrom(txfile); err != nil {
|
2013-09-09 20:14:57 +02:00
|
|
|
return nil, fmt.Errorf("cannot read tx file: %s", err)
|
2013-09-03 06:10:32 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
var utxos tx.UtxoStore
|
|
|
|
if _, err = utxos.ReadFrom(utxofile); err != nil {
|
2013-09-09 20:14:57 +02:00
|
|
|
return nil, fmt.Errorf("cannot read utxo file: %s", err)
|
2013-09-03 06:10:32 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
w := &BtcWallet{
|
2013-09-04 01:05:59 +02:00
|
|
|
Wallet: wlt,
|
2013-10-09 17:23:54 +02:00
|
|
|
name: account,
|
2013-09-03 06:10:32 +02:00
|
|
|
}
|
2013-09-04 01:05:59 +02:00
|
|
|
w.UtxoStore.s = utxos
|
|
|
|
w.TxStore.s = txs
|
2013-09-03 06:10:32 +02:00
|
|
|
|
2013-09-03 23:16:07 +02:00
|
|
|
return w, nil
|
|
|
|
}
|
|
|
|
|
2013-09-05 21:31:39 +02:00
|
|
|
func getCurHeight() (height int64) {
|
|
|
|
curHeight.RLock()
|
|
|
|
height = curHeight.h
|
|
|
|
curHeight.RUnlock()
|
|
|
|
if height != btcutil.BlockHeightUnknown {
|
|
|
|
return height
|
2013-09-09 20:14:57 +02:00
|
|
|
}
|
2013-09-05 21:31:39 +02:00
|
|
|
|
2013-10-15 16:40:23 +02:00
|
|
|
n := <-NewJSONID
|
2013-09-09 20:14:57 +02:00
|
|
|
m, err := btcjson.CreateMessageWithId("getblockcount",
|
|
|
|
fmt.Sprintf("btcwallet(%v)", n))
|
|
|
|
if err != nil {
|
|
|
|
// Can't continue.
|
|
|
|
return btcutil.BlockHeightUnknown
|
|
|
|
}
|
2013-09-05 21:31:39 +02:00
|
|
|
|
2013-09-09 20:14:57 +02:00
|
|
|
c := make(chan int64)
|
2013-09-05 21:31:39 +02:00
|
|
|
|
2013-09-09 20:14:57 +02:00
|
|
|
replyHandlers.Lock()
|
|
|
|
replyHandlers.m[n] = func(result interface{}, e *btcjson.Error) bool {
|
|
|
|
if e != nil {
|
|
|
|
c <- btcutil.BlockHeightUnknown
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
if balance, ok := result.(float64); ok {
|
|
|
|
c <- int64(balance)
|
2013-09-05 21:31:39 +02:00
|
|
|
} else {
|
2013-09-09 20:14:57 +02:00
|
|
|
c <- btcutil.BlockHeightUnknown
|
2013-09-05 21:31:39 +02:00
|
|
|
}
|
2013-09-09 20:14:57 +02:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
replyHandlers.Unlock()
|
2013-09-05 21:31:39 +02:00
|
|
|
|
2013-09-09 20:14:57 +02:00
|
|
|
// send message
|
|
|
|
btcdMsgs <- m
|
|
|
|
|
|
|
|
// Block until reply is ready.
|
|
|
|
height = <-c
|
|
|
|
curHeight.Lock()
|
|
|
|
if height > curHeight.h {
|
|
|
|
curHeight.h = height
|
|
|
|
} else {
|
|
|
|
height = curHeight.h
|
2013-09-05 21:31:39 +02:00
|
|
|
}
|
2013-09-09 20:14:57 +02:00
|
|
|
curHeight.Unlock()
|
|
|
|
|
|
|
|
return height
|
2013-09-05 21:31:39 +02:00
|
|
|
}
|
|
|
|
|
2013-09-09 20:14:57 +02:00
|
|
|
// CalculateBalance sums the amounts of all unspent transaction
|
|
|
|
// outputs to addresses of a wallet and returns the balance as a
|
|
|
|
// float64.
|
2013-09-05 21:31:39 +02:00
|
|
|
func (w *BtcWallet) CalculateBalance(confirmations int) float64 {
|
2013-09-09 20:14:57 +02:00
|
|
|
var bal uint64 // Measured in satoshi
|
2013-09-05 21:31:39 +02:00
|
|
|
|
|
|
|
height := getCurHeight()
|
|
|
|
if height == btcutil.BlockHeightUnknown {
|
|
|
|
return 0.
|
|
|
|
}
|
|
|
|
|
|
|
|
w.UtxoStore.RLock()
|
2013-09-09 20:14:57 +02:00
|
|
|
for _, u := range w.UtxoStore.s {
|
2013-09-05 21:31:39 +02:00
|
|
|
if int(height-u.Height) >= confirmations {
|
Perform smarter UTXO tracking.
This change fixes many issues with the tracking of unspent transaction
outputs. First, notifications for when UTXOs arse spent are now
requested from btcd, and when spent, will be removed from the
UtxoStore.
Second, when transactions are created, the unconfirmed (not yet in a
block) Utxo (with block height -1 and zeroed block hash) is added to
the wallet's UtxoStore. Notifications for when this UTXO is spent are
also requested from btcd. After the tx appears in a block, because
the UTXO has a pkScript to be spent by another owned wallet address, a
notification with the UTXO will be sent to btcwallet. We already
store the unconfirmed UTXO, so at this point the actual block height
and hash are filled in.
Finally, when calculating the balance, if confirmations is zero,
unconfirmed UTXOs (block height -1) will be included in the balance.
Otherwise, they are ignored.
2013-10-22 15:55:53 +02:00
|
|
|
// Utxos not yet in blocks (height -1) should only be
|
|
|
|
// added if confirmations is 0.
|
|
|
|
if u.Height != -1 || (confirmations == 0 && u.Height == -1) {
|
|
|
|
bal += u.Amt
|
|
|
|
}
|
2013-09-05 21:31:39 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
w.UtxoStore.RUnlock()
|
|
|
|
return float64(bal) / satoshiPerBTC
|
|
|
|
}
|
|
|
|
|
2013-09-09 20:14:57 +02:00
|
|
|
// Track requests btcd to send notifications of new transactions for
|
|
|
|
// each address stored in a wallet and sets up a new reply handler for
|
|
|
|
// these notifications.
|
2013-09-03 23:16:07 +02:00
|
|
|
func (w *BtcWallet) Track() {
|
2013-10-15 16:40:23 +02:00
|
|
|
n := <-NewJSONID
|
2013-09-05 17:51:33 +02:00
|
|
|
w.mtx.Lock()
|
|
|
|
w.NewBlockTxSeqN = n
|
|
|
|
w.mtx.Unlock()
|
2013-09-04 01:05:59 +02:00
|
|
|
|
2013-09-05 17:19:48 +02:00
|
|
|
replyHandlers.Lock()
|
2013-09-09 20:14:57 +02:00
|
|
|
replyHandlers.m[n] = w.newBlockTxHandler
|
2013-09-05 17:19:48 +02:00
|
|
|
replyHandlers.Unlock()
|
2013-09-04 01:05:59 +02:00
|
|
|
for _, addr := range w.GetActiveAddresses() {
|
2013-10-17 17:16:45 +02:00
|
|
|
w.ReqNewTxsForAddress(addr)
|
2013-09-04 01:05:59 +02:00
|
|
|
}
|
Perform smarter UTXO tracking.
This change fixes many issues with the tracking of unspent transaction
outputs. First, notifications for when UTXOs arse spent are now
requested from btcd, and when spent, will be removed from the
UtxoStore.
Second, when transactions are created, the unconfirmed (not yet in a
block) Utxo (with block height -1 and zeroed block hash) is added to
the wallet's UtxoStore. Notifications for when this UTXO is spent are
also requested from btcd. After the tx appears in a block, because
the UTXO has a pkScript to be spent by another owned wallet address, a
notification with the UTXO will be sent to btcwallet. We already
store the unconfirmed UTXO, so at this point the actual block height
and hash are filled in.
Finally, when calculating the balance, if confirmations is zero,
unconfirmed UTXOs (block height -1) will be included in the balance.
Otherwise, they are ignored.
2013-10-22 15:55:53 +02:00
|
|
|
|
|
|
|
n = <-NewJSONID
|
|
|
|
w.mtx.Lock()
|
|
|
|
w.SpentOutpointSeqN = n
|
|
|
|
w.mtx.Unlock()
|
|
|
|
|
|
|
|
replyHandlers.Lock()
|
|
|
|
replyHandlers.m[n] = w.spentUtxoHandler
|
|
|
|
replyHandlers.Unlock()
|
|
|
|
w.UtxoStore.RLock()
|
|
|
|
for _, utxo := range w.UtxoStore.s {
|
|
|
|
w.ReqSpentUtxoNtfn(utxo)
|
|
|
|
}
|
|
|
|
w.UtxoStore.RUnlock()
|
2013-09-04 01:05:59 +02:00
|
|
|
}
|
|
|
|
|
2013-09-09 20:14:57 +02:00
|
|
|
// RescanForAddress requests btcd to rescan the blockchain for new
|
|
|
|
// transactions to addr. This is useful for making btcwallet catch up to
|
|
|
|
// a long-running btcd process, or for importing addresses and rescanning
|
|
|
|
// for unspent tx outputs. If len(blocks) is 0, the entire blockchain is
|
|
|
|
// rescanned. If len(blocks) is 1, the rescan will begin at height
|
|
|
|
// blocks[0]. If len(blocks) is 2 or greater, the rescan will be
|
|
|
|
// performed for the block range blocks[0]...blocks[1] (inclusive).
|
2013-09-04 01:05:59 +02:00
|
|
|
func (w *BtcWallet) RescanForAddress(addr string, blocks ...int) {
|
2013-10-15 16:40:23 +02:00
|
|
|
n := <-NewJSONID
|
2013-09-04 01:05:59 +02:00
|
|
|
params := []interface{}{addr}
|
|
|
|
if len(blocks) > 0 {
|
|
|
|
params = append(params, blocks[0])
|
|
|
|
}
|
|
|
|
if len(blocks) > 1 {
|
|
|
|
params = append(params, blocks[1])
|
|
|
|
}
|
|
|
|
m := &btcjson.Message{
|
|
|
|
Jsonrpc: "1.0",
|
|
|
|
Id: fmt.Sprintf("btcwallet(%v)", n),
|
|
|
|
Method: "rescan",
|
|
|
|
Params: params,
|
|
|
|
}
|
|
|
|
msg, _ := json.Marshal(m)
|
|
|
|
|
|
|
|
replyHandlers.Lock()
|
2013-09-09 20:14:57 +02:00
|
|
|
replyHandlers.m[n] = func(result interface{}, e *btcjson.Error) bool {
|
2013-09-04 01:05:59 +02:00
|
|
|
// TODO(jrick)
|
|
|
|
|
|
|
|
// btcd returns a nil result when the rescan is complete.
|
|
|
|
// Returning true signals that this handler is finished
|
|
|
|
// and can be removed.
|
|
|
|
return result == nil
|
|
|
|
}
|
|
|
|
replyHandlers.Unlock()
|
|
|
|
|
|
|
|
btcdMsgs <- msg
|
|
|
|
}
|
|
|
|
|
2013-09-09 20:14:57 +02:00
|
|
|
// ReqNewTxsForAddress sends a message to btcd to request tx updates
|
|
|
|
// for addr for each new block that is added to the blockchain.
|
2013-09-04 19:41:33 +02:00
|
|
|
func (w *BtcWallet) ReqNewTxsForAddress(addr string) {
|
2013-10-17 17:16:45 +02:00
|
|
|
log.Debugf("Requesting notifications of TXs sending to address %v", addr)
|
|
|
|
|
2013-09-05 17:19:48 +02:00
|
|
|
w.mtx.RLock()
|
|
|
|
n := w.NewBlockTxSeqN
|
|
|
|
w.mtx.RUnlock()
|
2013-09-04 01:05:59 +02:00
|
|
|
|
|
|
|
m := &btcjson.Message{
|
|
|
|
Jsonrpc: "1.0",
|
|
|
|
Id: fmt.Sprintf("btcwallet(%d)", n),
|
2013-09-04 20:14:21 +02:00
|
|
|
Method: "notifynewtxs",
|
2013-09-04 01:05:59 +02:00
|
|
|
Params: []interface{}{addr},
|
|
|
|
}
|
|
|
|
msg, _ := json.Marshal(m)
|
|
|
|
|
2013-09-05 17:19:48 +02:00
|
|
|
btcdMsgs <- msg
|
|
|
|
}
|
2013-09-04 01:05:59 +02:00
|
|
|
|
Perform smarter UTXO tracking.
This change fixes many issues with the tracking of unspent transaction
outputs. First, notifications for when UTXOs arse spent are now
requested from btcd, and when spent, will be removed from the
UtxoStore.
Second, when transactions are created, the unconfirmed (not yet in a
block) Utxo (with block height -1 and zeroed block hash) is added to
the wallet's UtxoStore. Notifications for when this UTXO is spent are
also requested from btcd. After the tx appears in a block, because
the UTXO has a pkScript to be spent by another owned wallet address, a
notification with the UTXO will be sent to btcwallet. We already
store the unconfirmed UTXO, so at this point the actual block height
and hash are filled in.
Finally, when calculating the balance, if confirmations is zero,
unconfirmed UTXOs (block height -1) will be included in the balance.
Otherwise, they are ignored.
2013-10-22 15:55:53 +02:00
|
|
|
// ReqSpentUtxoNtfn sends a message to btcd to request updates for when
|
|
|
|
// a stored UTXO has been spent.
|
|
|
|
func (w *BtcWallet) ReqSpentUtxoNtfn(u *tx.Utxo) {
|
|
|
|
log.Debugf("Requesting spent UTXO notifications for Outpoint hash %s index %d",
|
|
|
|
u.Out.Hash, u.Out.Index)
|
|
|
|
|
|
|
|
w.mtx.RLock()
|
|
|
|
n := w.SpentOutpointSeqN
|
|
|
|
w.mtx.RUnlock()
|
|
|
|
|
|
|
|
m := &btcjson.Message{
|
|
|
|
Jsonrpc: "1.0",
|
|
|
|
Id: fmt.Sprintf("btcwallet(%d)", n),
|
|
|
|
Method: "notifyspent",
|
|
|
|
Params: []interface{}{
|
|
|
|
u.Out.Hash.String(),
|
|
|
|
u.Out.Index,
|
|
|
|
},
|
|
|
|
}
|
|
|
|
msg, _ := json.Marshal(m)
|
|
|
|
|
|
|
|
btcdMsgs <- msg
|
|
|
|
}
|
|
|
|
|
|
|
|
// spentUtxoHandler is the handler function for btcd spent UTXO notifications
|
|
|
|
// resulting from transactions in newly-attached blocks.
|
|
|
|
func (w *BtcWallet) spentUtxoHandler(result interface{}, e *btcjson.Error) bool {
|
|
|
|
if e != nil {
|
|
|
|
log.Errorf("Spent UTXO Handler: Error %d received from btcd: %s",
|
|
|
|
e.Code, e.Message)
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
v, ok := result.(map[string]interface{})
|
|
|
|
if !ok {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
txHashBE, ok := v["txhash"].(string)
|
|
|
|
if !ok {
|
|
|
|
log.Error("Spent UTXO Handler: Unspecified transaction hash.")
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
txHash, err := btcwire.NewShaHashFromStr(txHashBE)
|
|
|
|
if err != nil {
|
|
|
|
log.Errorf("Spent UTXO Handler: Bad transaction hash: %s", err)
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
index, ok := v["index"].(float64)
|
|
|
|
if !ok {
|
|
|
|
log.Error("Spent UTXO Handler: Unspecified index.")
|
|
|
|
}
|
|
|
|
|
|
|
|
_, _ = txHash, index
|
|
|
|
|
|
|
|
// Never remove this handler.
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2013-09-09 20:14:57 +02:00
|
|
|
// newBlockTxHandler is the handler function for btcd transaction
|
|
|
|
// notifications resulting from newly-attached blocks.
|
|
|
|
func (w *BtcWallet) newBlockTxHandler(result interface{}, e *btcjson.Error) bool {
|
2013-09-05 21:31:39 +02:00
|
|
|
if e != nil {
|
2013-09-09 20:14:57 +02:00
|
|
|
log.Errorf("Tx Handler: Error %d received from btcd: %s",
|
|
|
|
e.Code, e.Message)
|
|
|
|
return false
|
2013-09-05 21:31:39 +02:00
|
|
|
}
|
|
|
|
|
2013-09-05 17:19:48 +02:00
|
|
|
v, ok := result.(map[string]interface{})
|
|
|
|
if !ok {
|
2013-09-05 21:31:39 +02:00
|
|
|
// The first result sent from btcd is nil. This could be used to
|
|
|
|
// indicate that the request for notifications succeeded.
|
|
|
|
if result != nil {
|
|
|
|
log.Errorf("Tx Handler: Unexpected result type %T.", result)
|
|
|
|
}
|
2013-09-05 17:19:48 +02:00
|
|
|
return false
|
|
|
|
}
|
2013-10-11 00:44:44 +02:00
|
|
|
sender, ok := v["sender"].(string)
|
2013-09-05 17:19:48 +02:00
|
|
|
if !ok {
|
|
|
|
log.Error("Tx Handler: Unspecified sender.")
|
|
|
|
return false
|
|
|
|
}
|
2013-10-11 00:44:44 +02:00
|
|
|
receiver, ok := v["receiver"].(string)
|
2013-09-05 17:19:48 +02:00
|
|
|
if !ok {
|
|
|
|
log.Error("Tx Handler: Unspecified receiver.")
|
|
|
|
return false
|
|
|
|
}
|
2013-09-09 20:14:57 +02:00
|
|
|
blockhashBE, ok := v["blockhash"].(string)
|
|
|
|
if !ok {
|
|
|
|
log.Error("Tx Handler: Unspecified block hash.")
|
|
|
|
return false
|
|
|
|
}
|
2013-09-05 17:19:48 +02:00
|
|
|
height, ok := v["height"].(float64)
|
|
|
|
if !ok {
|
|
|
|
log.Error("Tx Handler: Unspecified height.")
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
txhashBE, ok := v["txhash"].(string)
|
|
|
|
if !ok {
|
|
|
|
log.Error("Tx Handler: Unspecified transaction hash.")
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
index, ok := v["index"].(float64)
|
|
|
|
if !ok {
|
|
|
|
log.Error("Tx Handler: Unspecified transaction index.")
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
amt, ok := v["amount"].(float64)
|
|
|
|
if !ok {
|
|
|
|
log.Error("Tx Handler: Unspecified amount.")
|
|
|
|
return false
|
|
|
|
}
|
2013-10-11 19:01:15 +02:00
|
|
|
pkscript58, ok := v["pkscript"].(string)
|
|
|
|
if !ok {
|
|
|
|
log.Error("Tx Handler: Unspecified pubkey script.")
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
pkscript := btcutil.Base58Decode(pkscript58)
|
2013-09-05 17:19:48 +02:00
|
|
|
spent, ok := v["spent"].(bool)
|
|
|
|
if !ok {
|
|
|
|
log.Error("Tx Handler: Unspecified spent field.")
|
|
|
|
return false
|
|
|
|
}
|
2013-09-04 01:05:59 +02:00
|
|
|
|
2013-09-09 20:14:57 +02:00
|
|
|
// btcd sends the block and tx hashes as BE strings. Convert both
|
|
|
|
// to a LE ShaHash.
|
|
|
|
blockhash, err := btcwire.NewShaHashFromStr(blockhashBE)
|
|
|
|
if err != nil {
|
|
|
|
log.Error("Tx Handler: Block hash string cannot be parsed: " + err.Error())
|
|
|
|
return false
|
|
|
|
}
|
2013-09-05 17:19:48 +02:00
|
|
|
txhash, err := btcwire.NewShaHashFromStr(txhashBE)
|
|
|
|
if err != nil {
|
|
|
|
log.Error("Tx Handler: Tx hash string cannot be parsed: " + err.Error())
|
2013-09-04 01:05:59 +02:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2013-10-11 00:44:44 +02:00
|
|
|
// TODO(jrick): btcd does not find the sender yet.
|
|
|
|
senderHash, _, _ := btcutil.DecodeAddress(sender)
|
|
|
|
receiverHash, _, err := btcutil.DecodeAddress(receiver)
|
|
|
|
if err != nil {
|
|
|
|
log.Error("Tx Handler: receiver address can not be decoded: " + err.Error())
|
|
|
|
return false
|
|
|
|
}
|
2013-09-05 17:19:48 +02:00
|
|
|
|
|
|
|
go func() {
|
|
|
|
t := &tx.RecvTx{
|
2013-09-09 20:14:57 +02:00
|
|
|
Amt: uint64(amt),
|
2013-09-05 17:19:48 +02:00
|
|
|
}
|
|
|
|
copy(t.TxHash[:], txhash[:])
|
2013-09-09 20:14:57 +02:00
|
|
|
copy(t.BlockHash[:], blockhash[:])
|
2013-10-11 00:44:44 +02:00
|
|
|
copy(t.SenderAddr[:], senderHash)
|
|
|
|
copy(t.ReceiverAddr[:], receiverHash)
|
2013-09-05 17:19:48 +02:00
|
|
|
|
|
|
|
w.TxStore.Lock()
|
|
|
|
txs := w.TxStore.s
|
|
|
|
w.TxStore.s = append(txs, t)
|
|
|
|
w.TxStore.dirty = true
|
|
|
|
w.TxStore.Unlock()
|
2013-10-15 22:55:28 +02:00
|
|
|
|
|
|
|
if err = w.writeDirtyToDisk(); err != nil {
|
|
|
|
log.Errorf("cannot sync dirty wallet: %v", err)
|
|
|
|
}
|
2013-09-05 17:19:48 +02:00
|
|
|
}()
|
|
|
|
|
2013-09-09 20:14:57 +02:00
|
|
|
// Do not add output to utxo store if spent.
|
|
|
|
if !spent {
|
|
|
|
go func() {
|
Perform smarter UTXO tracking.
This change fixes many issues with the tracking of unspent transaction
outputs. First, notifications for when UTXOs arse spent are now
requested from btcd, and when spent, will be removed from the
UtxoStore.
Second, when transactions are created, the unconfirmed (not yet in a
block) Utxo (with block height -1 and zeroed block hash) is added to
the wallet's UtxoStore. Notifications for when this UTXO is spent are
also requested from btcd. After the tx appears in a block, because
the UTXO has a pkScript to be spent by another owned wallet address, a
notification with the UTXO will be sent to btcwallet. We already
store the unconfirmed UTXO, so at this point the actual block height
and hash are filled in.
Finally, when calculating the balance, if confirmations is zero,
unconfirmed UTXOs (block height -1) will be included in the balance.
Otherwise, they are ignored.
2013-10-22 15:55:53 +02:00
|
|
|
// First, iterate through all stored utxos. If an unconfirmed utxo
|
|
|
|
// (not present in a block) has the same outpoint as this utxo,
|
|
|
|
// update the block height and hash.
|
|
|
|
w.UtxoStore.RLock()
|
|
|
|
for _, u := range w.UtxoStore.s {
|
|
|
|
if u.Height != -1 {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
if bytes.Equal(u.Out.Hash[:], txhash[:]) && u.Out.Index == uint32(index) {
|
|
|
|
// Found it.
|
|
|
|
copy(u.BlockHash[:], blockhash[:])
|
|
|
|
u.Height = int64(height)
|
|
|
|
w.UtxoStore.RUnlock()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
w.UtxoStore.RUnlock()
|
|
|
|
|
2013-09-09 20:14:57 +02:00
|
|
|
u := &tx.Utxo{
|
2013-10-14 01:27:30 +02:00
|
|
|
Amt: uint64(amt),
|
|
|
|
Height: int64(height),
|
2013-10-11 19:01:15 +02:00
|
|
|
Subscript: pkscript,
|
2013-09-09 20:14:57 +02:00
|
|
|
}
|
|
|
|
copy(u.Out.Hash[:], txhash[:])
|
|
|
|
u.Out.Index = uint32(index)
|
2013-10-14 01:27:30 +02:00
|
|
|
|
2013-10-11 00:44:44 +02:00
|
|
|
copy(u.AddrHash[:], receiverHash)
|
2013-09-09 20:14:57 +02:00
|
|
|
copy(u.BlockHash[:], blockhash[:])
|
2013-09-05 17:19:48 +02:00
|
|
|
|
2013-09-09 20:14:57 +02:00
|
|
|
w.UtxoStore.Lock()
|
|
|
|
w.UtxoStore.s = append(w.UtxoStore.s, u)
|
|
|
|
w.UtxoStore.dirty = true
|
|
|
|
w.UtxoStore.Unlock()
|
2013-10-15 22:55:28 +02:00
|
|
|
if err = w.writeDirtyToDisk(); err != nil {
|
|
|
|
log.Errorf("cannot sync dirty wallet: %v", err)
|
|
|
|
}
|
|
|
|
|
2013-10-09 17:23:54 +02:00
|
|
|
confirmed := w.CalculateBalance(6)
|
|
|
|
unconfirmed := w.CalculateBalance(0) - confirmed
|
|
|
|
NotifyWalletBalance(frontendNotificationMaster, w.name, confirmed)
|
|
|
|
NotifyWalletBalanceUnconfirmed(frontendNotificationMaster, w.name, unconfirmed)
|
2013-09-09 20:14:57 +02:00
|
|
|
}()
|
|
|
|
}
|
2013-09-05 17:19:48 +02:00
|
|
|
|
|
|
|
// Never remove this handler.
|
|
|
|
return false
|
2013-09-03 06:10:32 +02:00
|
|
|
}
|
2013-09-09 20:14:57 +02:00
|
|
|
|
2013-10-15 16:40:23 +02:00
|
|
|
// NewJSONID is used to receive the next unique JSON ID for btcd
|
2013-10-15 00:45:48 +02:00
|
|
|
// requests, starting from zero and incrementing by one after each
|
|
|
|
// read.
|
2013-10-15 16:40:23 +02:00
|
|
|
var NewJSONID = make(chan uint64)
|
2013-10-15 00:45:48 +02:00
|
|
|
|
2013-10-15 16:40:23 +02:00
|
|
|
// JSONIDGenerator sends incremental integers across a channel. This
|
2013-10-15 00:45:48 +02:00
|
|
|
// is meant to provide a unique value for the JSON ID field for btcd
|
|
|
|
// messages.
|
2013-10-15 16:40:23 +02:00
|
|
|
func JSONIDGenerator(c chan uint64) {
|
2013-10-15 00:45:48 +02:00
|
|
|
var n uint64
|
|
|
|
for {
|
|
|
|
c <- n
|
|
|
|
n++
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2013-09-09 20:14:57 +02:00
|
|
|
func main() {
|
|
|
|
tcfg, _, err := loadConfig()
|
|
|
|
if err != nil {
|
|
|
|
log.Error(err)
|
|
|
|
os.Exit(1)
|
|
|
|
}
|
|
|
|
cfg = tcfg
|
|
|
|
|
2013-10-15 21:53:49 +02:00
|
|
|
// Open default wallet
|
2013-09-09 20:14:57 +02:00
|
|
|
w, err := OpenWallet(cfg, "")
|
|
|
|
if err != nil {
|
|
|
|
log.Info(err.Error())
|
|
|
|
} else {
|
|
|
|
wallets.Lock()
|
|
|
|
wallets.m[""] = w
|
|
|
|
wallets.Unlock()
|
|
|
|
}
|
|
|
|
|
|
|
|
go func() {
|
|
|
|
// Start HTTP server to listen and send messages to frontend and btcd
|
|
|
|
// backend. Try reconnection if connection failed.
|
|
|
|
for {
|
|
|
|
if err := FrontendListenAndServe(); err == ErrConnRefused {
|
|
|
|
// wait and try again.
|
|
|
|
log.Info("Unable to start frontend HTTP server. Retrying in 5 seconds.")
|
|
|
|
time.Sleep(5 * time.Second)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
2013-10-15 00:45:48 +02:00
|
|
|
// Begin generating new IDs for JSON calls.
|
2013-10-15 16:40:23 +02:00
|
|
|
go JSONIDGenerator(NewJSONID)
|
2013-10-15 00:45:48 +02:00
|
|
|
|
2013-09-09 20:14:57 +02:00
|
|
|
for {
|
|
|
|
replies := make(chan error)
|
|
|
|
done := make(chan int)
|
|
|
|
go func() {
|
|
|
|
BtcdConnect(replies)
|
|
|
|
close(done)
|
|
|
|
}()
|
|
|
|
selectLoop:
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-done:
|
|
|
|
break selectLoop
|
|
|
|
case err := <-replies:
|
|
|
|
switch err {
|
|
|
|
case ErrConnRefused:
|
|
|
|
btcdConnected.c <- false
|
|
|
|
log.Info("btcd connection refused, retying in 5 seconds")
|
|
|
|
time.Sleep(5 * time.Second)
|
|
|
|
case ErrConnLost:
|
|
|
|
btcdConnected.c <- false
|
|
|
|
log.Info("btcd connection lost, retrying in 5 seconds")
|
|
|
|
time.Sleep(5 * time.Second)
|
|
|
|
case nil:
|
|
|
|
btcdConnected.c <- true
|
|
|
|
log.Info("Established connection to btcd.")
|
|
|
|
default:
|
|
|
|
log.Infof("Unhandled error: %v", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|