2013-08-21 16:37:30 +02:00
|
|
|
/*
|
2014-01-03 19:34:37 +01:00
|
|
|
* Copyright (c) 2013, 2014 Conformal Systems LLC <info@conformal.com>
|
2013-08-21 16:37:30 +02:00
|
|
|
*
|
|
|
|
* 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 (
|
|
|
|
"code.google.com/p/go.net/websocket"
|
2013-12-05 17:59:08 +01:00
|
|
|
"crypto/sha256"
|
2013-12-03 16:52:09 +01:00
|
|
|
_ "crypto/sha512" // for cert generation
|
2013-12-05 17:59:08 +01:00
|
|
|
"crypto/subtle"
|
2013-11-19 18:21:54 +01:00
|
|
|
"crypto/tls"
|
|
|
|
"crypto/x509"
|
2013-10-03 15:11:35 +02:00
|
|
|
"encoding/base64"
|
2014-01-03 19:34:37 +01:00
|
|
|
"encoding/hex"
|
2013-08-21 16:37:30 +02:00
|
|
|
"encoding/json"
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"github.com/conformal/btcjson"
|
2014-01-10 21:51:54 +01:00
|
|
|
"github.com/conformal/btcutil"
|
Implement address rescanning.
When a wallet is opened, a rescan request will be sent to btcd with
all active addresses from the wallet, to rescan from the last synced
block (now saved to the wallet file) and the current best block.
As multi-account support is further explored, rescan requests should
be batched together to send a single request for all addresses from
all wallets.
This change introduces several changes to the wallet, tx, and utxo
files. Wallet files are still compatible, however, a rescan will try
to start at the genesis block since no correct "last synced to" or
"created at block X" was saved. The tx and utxo files, however, are
not compatible and should be deleted (or an error will occur on read).
If any errors occur opening the utxo file, a rescan will start
beginning at the creation block saved in the wallet.
2013-10-30 02:22:14 +01:00
|
|
|
"github.com/conformal/btcwallet/wallet"
|
2013-11-06 17:23:30 +01:00
|
|
|
"github.com/conformal/btcws"
|
2013-11-20 02:47:15 +01:00
|
|
|
"github.com/conformal/go-socks"
|
2014-01-10 21:51:54 +01:00
|
|
|
"io/ioutil"
|
2013-10-16 23:49:35 +02:00
|
|
|
"net"
|
2013-08-21 16:37:30 +02:00
|
|
|
"net/http"
|
2013-12-03 16:52:09 +01:00
|
|
|
"os"
|
2013-12-05 23:20:52 +01:00
|
|
|
"runtime"
|
2013-08-21 16:37:30 +02:00
|
|
|
"sync"
|
2013-12-03 16:52:09 +01:00
|
|
|
"time"
|
2013-08-21 16:37:30 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
2013-09-09 20:14:57 +02:00
|
|
|
// ErrConnRefused represents an error where a connection to another
|
|
|
|
// process cannot be established.
|
|
|
|
ErrConnRefused = errors.New("connection refused")
|
|
|
|
|
|
|
|
// ErrConnLost represents an error where a connection to another
|
|
|
|
// process cannot be established.
|
|
|
|
ErrConnLost = errors.New("connection lost")
|
2013-08-21 16:37:30 +02:00
|
|
|
|
|
|
|
// Adds a frontend listener channel
|
|
|
|
addFrontendListener = make(chan (chan []byte))
|
|
|
|
|
|
|
|
// Removes a frontend listener channel
|
|
|
|
deleteFrontendListener = make(chan (chan []byte))
|
|
|
|
|
|
|
|
// Messages sent to this channel are sent to each connected frontend.
|
|
|
|
frontendNotificationMaster = make(chan []byte, 100)
|
|
|
|
)
|
|
|
|
|
2013-11-18 19:31:58 +01:00
|
|
|
// server holds the items the RPC server may need to access (auth,
|
|
|
|
// config, shutdown, etc.)
|
|
|
|
type server struct {
|
|
|
|
wg sync.WaitGroup
|
|
|
|
listeners []net.Listener
|
2013-12-05 17:59:08 +01:00
|
|
|
authsha [sha256.Size]byte
|
2013-11-18 19:31:58 +01:00
|
|
|
}
|
|
|
|
|
2013-12-05 23:20:52 +01:00
|
|
|
// parseListeners splits the list of listen addresses passed in addrs into
|
|
|
|
// IPv4 and IPv6 slices and returns them. This allows easy creation of the
|
|
|
|
// listeners on the correct interface "tcp4" and "tcp6". It also properly
|
|
|
|
// detects addresses which apply to "all interfaces" and adds the address to
|
|
|
|
// both slices.
|
|
|
|
func parseListeners(addrs []string) ([]string, []string, error) {
|
|
|
|
ipv4ListenAddrs := make([]string, 0, len(addrs)*2)
|
|
|
|
ipv6ListenAddrs := make([]string, 0, len(addrs)*2)
|
|
|
|
for _, addr := range addrs {
|
|
|
|
host, _, err := net.SplitHostPort(addr)
|
|
|
|
if err != nil {
|
|
|
|
// Shouldn't happen due to already being normalized.
|
|
|
|
return nil, nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Empty host or host of * on plan9 is both IPv4 and IPv6.
|
|
|
|
if host == "" || (host == "*" && runtime.GOOS == "plan9") {
|
|
|
|
ipv4ListenAddrs = append(ipv4ListenAddrs, addr)
|
|
|
|
ipv6ListenAddrs = append(ipv6ListenAddrs, addr)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
// Parse the IP.
|
|
|
|
ip := net.ParseIP(host)
|
|
|
|
if ip == nil {
|
|
|
|
return nil, nil, fmt.Errorf("'%s' is not a valid IP "+
|
|
|
|
"address", host)
|
|
|
|
}
|
|
|
|
|
|
|
|
// To4 returns nil when the IP is not an IPv4 address, so use
|
|
|
|
// this determine the address type.
|
|
|
|
if ip.To4() == nil {
|
|
|
|
ipv6ListenAddrs = append(ipv6ListenAddrs, addr)
|
|
|
|
} else {
|
|
|
|
ipv4ListenAddrs = append(ipv4ListenAddrs, addr)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return ipv4ListenAddrs, ipv6ListenAddrs, nil
|
|
|
|
}
|
|
|
|
|
2013-11-18 19:31:58 +01:00
|
|
|
// newServer returns a new instance of the server struct.
|
2013-12-05 23:20:52 +01:00
|
|
|
func newServer(listenAddrs []string) (*server, error) {
|
2013-12-05 17:59:08 +01:00
|
|
|
login := cfg.Username + ":" + cfg.Password
|
|
|
|
auth := "Basic " + base64.StdEncoding.EncodeToString([]byte(login))
|
2013-11-18 19:31:58 +01:00
|
|
|
s := server{
|
2013-12-05 17:59:08 +01:00
|
|
|
authsha: sha256.Sum256([]byte(auth)),
|
2013-12-03 16:52:09 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// Check for existence of cert file and key file
|
|
|
|
if !fileExists(cfg.RPCKey) && !fileExists(cfg.RPCCert) {
|
|
|
|
// if both files do not exist, we generate them.
|
2014-01-10 21:51:54 +01:00
|
|
|
err := genCertPair(cfg.RPCKey, cfg.RPCCert)
|
2013-12-03 16:52:09 +01:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
keypair, err := tls.LoadX509KeyPair(cfg.RPCCert, cfg.RPCKey)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
tlsConfig := tls.Config{
|
|
|
|
Certificates: []tls.Certificate{keypair},
|
2013-11-18 19:31:58 +01:00
|
|
|
}
|
|
|
|
|
2013-12-05 23:20:52 +01:00
|
|
|
ipv4ListenAddrs, ipv6ListenAddrs, err := parseListeners(listenAddrs)
|
|
|
|
listeners := make([]net.Listener, 0,
|
|
|
|
len(ipv6ListenAddrs)+len(ipv4ListenAddrs))
|
|
|
|
for _, addr := range ipv4ListenAddrs {
|
|
|
|
listener, err := tls.Listen("tcp4", addr, &tlsConfig)
|
|
|
|
if err != nil {
|
|
|
|
log.Warnf("RPCS: Can't listen on %s: %v", addr,
|
|
|
|
err)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
listeners = append(listeners, listener)
|
2013-11-18 19:31:58 +01:00
|
|
|
}
|
|
|
|
|
2013-12-05 23:20:52 +01:00
|
|
|
for _, addr := range ipv6ListenAddrs {
|
|
|
|
listener, err := tls.Listen("tcp6", addr, &tlsConfig)
|
|
|
|
if err != nil {
|
|
|
|
log.Warnf("RPCS: Can't listen on %s: %v", addr,
|
|
|
|
err)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
listeners = append(listeners, listener)
|
|
|
|
}
|
|
|
|
if len(listeners) == 0 {
|
|
|
|
return nil, errors.New("RPCS: No valid listen address")
|
2013-11-18 19:31:58 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
s.listeners = listeners
|
|
|
|
|
|
|
|
return &s, nil
|
|
|
|
}
|
|
|
|
|
2014-01-10 21:51:54 +01:00
|
|
|
// genCertPair generates a key/cert pair to the paths provided.
|
|
|
|
func genCertPair(certFile, keyFile string) error {
|
2013-12-03 16:52:09 +01:00
|
|
|
log.Infof("Generating TLS certificates...")
|
|
|
|
|
2014-01-10 21:51:54 +01:00
|
|
|
org := "btcwallet autogenerated cert"
|
|
|
|
validUntil := time.Now().Add(10 * 365 * 24 * time.Hour)
|
|
|
|
cert, key, err := btcutil.NewTLSCertPair(org, validUntil, nil)
|
2013-12-03 16:52:09 +01:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2014-01-10 21:51:54 +01:00
|
|
|
// Write cert and key files.
|
|
|
|
if err = ioutil.WriteFile(certFile, cert, 0666); err != nil {
|
2013-12-03 16:52:09 +01:00
|
|
|
return err
|
|
|
|
}
|
2014-01-10 21:51:54 +01:00
|
|
|
if err = ioutil.WriteFile(keyFile, key, 0600); err != nil {
|
|
|
|
os.Remove(certFile)
|
2013-12-03 16:52:09 +01:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2014-01-10 21:51:54 +01:00
|
|
|
log.Infof("Done generating TLS certificates")
|
2013-12-03 16:52:09 +01:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2013-11-18 19:31:58 +01:00
|
|
|
// handleRPCRequest processes a JSON-RPC request from a frontend.
|
|
|
|
func (s *server) handleRPCRequest(w http.ResponseWriter, r *http.Request) {
|
|
|
|
body, err := btcjson.GetRaw(r.Body)
|
|
|
|
if err != nil {
|
|
|
|
log.Errorf("RPCS: Error getting JSON message: %v", err)
|
|
|
|
}
|
|
|
|
|
2014-01-03 19:34:37 +01:00
|
|
|
response := ProcessFrontendRequest(body, false)
|
|
|
|
mresponse, err := json.Marshal(response)
|
|
|
|
if err != nil {
|
|
|
|
id := response.Id
|
|
|
|
response = &btcjson.Reply{
|
|
|
|
Id: id,
|
|
|
|
Error: &btcjson.ErrInternal,
|
2013-11-18 22:37:28 +01:00
|
|
|
}
|
2014-01-03 19:34:37 +01:00
|
|
|
mresponse, _ = json.Marshal(response)
|
|
|
|
}
|
2013-11-18 22:37:28 +01:00
|
|
|
|
2014-01-03 19:34:37 +01:00
|
|
|
if _, err := w.Write(mresponse); err != nil {
|
|
|
|
log.Warnf("RPCS: could not respond to RPC request: %v", err)
|
|
|
|
}
|
2013-11-18 19:31:58 +01:00
|
|
|
}
|
|
|
|
|
2013-08-21 16:37:30 +02:00
|
|
|
// frontendListenerDuplicator listens for new wallet listener channels
|
|
|
|
// and duplicates messages sent to frontendNotificationMaster to all
|
|
|
|
// connected listeners.
|
|
|
|
func frontendListenerDuplicator() {
|
|
|
|
// frontendListeners is a map holding each currently connected frontend
|
|
|
|
// listener as the key. The value is ignored, as this is only used as
|
|
|
|
// a set.
|
|
|
|
frontendListeners := make(map[chan []byte]bool)
|
|
|
|
|
|
|
|
// Don't want to add or delete a wallet listener while iterating
|
|
|
|
// through each to propigate to every attached wallet. Use a mutex to
|
|
|
|
// prevent this.
|
2013-10-06 17:04:01 +02:00
|
|
|
var mtx sync.Mutex
|
2013-08-21 16:37:30 +02:00
|
|
|
|
|
|
|
// Check for listener channels to add or remove from set.
|
|
|
|
go func() {
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case c := <-addFrontendListener:
|
|
|
|
mtx.Lock()
|
|
|
|
frontendListeners[c] = true
|
|
|
|
mtx.Unlock()
|
2013-10-09 17:23:54 +02:00
|
|
|
|
2014-01-03 19:34:37 +01:00
|
|
|
NotifyBtcdConnection(c)
|
|
|
|
bs, err := GetCurBlock()
|
|
|
|
if err == nil {
|
2013-12-13 17:00:31 +01:00
|
|
|
NotifyNewBlockChainHeight(c, bs)
|
2013-10-29 07:19:40 +01:00
|
|
|
NotifyBalances(c)
|
|
|
|
}
|
|
|
|
|
2013-08-21 16:37:30 +02:00
|
|
|
case c := <-deleteFrontendListener:
|
|
|
|
mtx.Lock()
|
|
|
|
delete(frontendListeners, c)
|
|
|
|
mtx.Unlock()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
2013-09-09 20:14:57 +02:00
|
|
|
// Duplicate all messages sent across frontendNotificationMaster, as
|
|
|
|
// well as internal btcwallet notifications, to each listening wallet.
|
2013-08-21 16:37:30 +02:00
|
|
|
for {
|
2014-01-03 19:34:37 +01:00
|
|
|
ntfn := <-frontendNotificationMaster
|
2013-09-09 20:14:57 +02:00
|
|
|
|
2013-08-21 16:37:30 +02:00
|
|
|
mtx.Lock()
|
2013-09-09 20:14:57 +02:00
|
|
|
for c := range frontendListeners {
|
2013-08-21 16:37:30 +02:00
|
|
|
c <- ntfn
|
|
|
|
}
|
|
|
|
mtx.Unlock()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-01-03 19:34:37 +01:00
|
|
|
// NotifyBtcdConnection notifies a frontend of the current connection
|
|
|
|
// status of btcwallet to btcd.
|
|
|
|
func NotifyBtcdConnection(reply chan []byte) {
|
|
|
|
if btcd, ok := CurrentRPCConn().(*BtcdRPCConn); ok {
|
|
|
|
ntfn := btcws.NewBtcdConnectedNtfn(btcd.Connected())
|
|
|
|
mntfn, _ := ntfn.MarshalJSON()
|
|
|
|
reply <- mntfn
|
|
|
|
}
|
2013-12-13 17:00:31 +01:00
|
|
|
|
2013-10-29 14:19:11 +01:00
|
|
|
}
|
|
|
|
|
2013-11-18 19:31:58 +01:00
|
|
|
// frontendSendRecv is the handler function for websocket connections from
|
|
|
|
// a btcwallet instance. It reads requests and sends responses to a
|
|
|
|
// frontend, as well as notififying wallets of chain updates. There can
|
|
|
|
// possibly be many of these running, one for each currently connected
|
|
|
|
// frontend.
|
|
|
|
func frontendSendRecv(ws *websocket.Conn) {
|
2013-08-21 16:37:30 +02:00
|
|
|
// Add frontend notification channel to set so this handler receives
|
|
|
|
// updates.
|
|
|
|
frontendNotification := make(chan []byte)
|
|
|
|
addFrontendListener <- frontendNotification
|
|
|
|
defer func() {
|
|
|
|
deleteFrontendListener <- frontendNotification
|
|
|
|
}()
|
|
|
|
|
|
|
|
// jsonMsgs receives JSON messages from the currently connected frontend.
|
|
|
|
jsonMsgs := make(chan []byte)
|
|
|
|
|
|
|
|
// Receive messages from websocket and send across jsonMsgs until
|
|
|
|
// connection is lost
|
|
|
|
go func() {
|
|
|
|
for {
|
|
|
|
var m []byte
|
|
|
|
if err := websocket.Message.Receive(ws, &m); err != nil {
|
|
|
|
close(jsonMsgs)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
jsonMsgs <- m
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case m, ok := <-jsonMsgs:
|
|
|
|
if !ok {
|
|
|
|
// frontend disconnected.
|
|
|
|
return
|
|
|
|
}
|
2013-11-18 19:31:58 +01:00
|
|
|
// Handle request here.
|
2014-01-03 19:34:37 +01:00
|
|
|
go func() {
|
|
|
|
reply := ProcessFrontendRequest(m, true)
|
|
|
|
mreply, _ := json.Marshal(reply)
|
|
|
|
frontendNotification <- mreply
|
|
|
|
}()
|
|
|
|
|
2013-08-21 16:37:30 +02:00
|
|
|
case ntfn, _ := <-frontendNotification:
|
|
|
|
if err := websocket.Message.Send(ws, ntfn); err != nil {
|
|
|
|
// Frontend disconnected.
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2013-10-29 07:19:40 +01:00
|
|
|
// NotifyNewBlockChainHeight notifies all frontends of a new
|
2013-12-13 17:00:31 +01:00
|
|
|
// blockchain height. This sends the same notification as
|
|
|
|
// btcd, so this can probably be removed.
|
|
|
|
func NotifyNewBlockChainHeight(reply chan []byte, bs wallet.BlockStamp) {
|
|
|
|
ntfn := btcws.NewBlockConnectedNtfn(bs.Hash.String(), bs.Height)
|
|
|
|
mntfn, _ := ntfn.MarshalJSON()
|
|
|
|
reply <- mntfn
|
2013-10-29 07:19:40 +01:00
|
|
|
}
|
|
|
|
|
2013-09-09 20:14:57 +02:00
|
|
|
var duplicateOnce sync.Once
|
|
|
|
|
2013-11-18 19:31:58 +01:00
|
|
|
// Start starts a HTTP server to provide standard RPC and extension
|
|
|
|
// websocket connections for any number of btcwallet frontends.
|
|
|
|
func (s *server) Start() {
|
2013-08-21 16:37:30 +02:00
|
|
|
// We'll need to duplicate replies to frontends to each frontend.
|
|
|
|
// Replies are sent to frontendReplyMaster, and duplicated to each valid
|
|
|
|
// channel in frontendReplySet. This runs a goroutine to duplicate
|
|
|
|
// requests for each channel in the set.
|
2013-09-09 20:14:57 +02:00
|
|
|
//
|
|
|
|
// Use a sync.Once to insure no extra duplicators run.
|
|
|
|
go duplicateOnce.Do(frontendListenerDuplicator)
|
2013-08-21 16:37:30 +02:00
|
|
|
|
2013-12-03 16:52:09 +01:00
|
|
|
log.Trace("Starting RPC server")
|
|
|
|
|
2013-11-18 19:31:58 +01:00
|
|
|
serveMux := http.NewServeMux()
|
|
|
|
httpServer := &http.Server{Handler: serveMux}
|
|
|
|
serveMux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
2013-12-05 17:59:08 +01:00
|
|
|
if err := s.checkAuth(r); err != nil {
|
|
|
|
http.Error(w, "401 Unauthorized.", http.StatusUnauthorized)
|
|
|
|
return
|
|
|
|
}
|
2013-11-18 19:31:58 +01:00
|
|
|
s.handleRPCRequest(w, r)
|
|
|
|
})
|
2013-12-05 17:59:08 +01:00
|
|
|
serveMux.HandleFunc("/frontend", func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
if err := s.checkAuth(r); err != nil {
|
|
|
|
http.Error(w, "401 Unauthorized.", http.StatusUnauthorized)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
websocket.Handler(frontendSendRecv).ServeHTTP(w, r)
|
|
|
|
})
|
2013-11-18 19:31:58 +01:00
|
|
|
for _, listener := range s.listeners {
|
|
|
|
s.wg.Add(1)
|
|
|
|
go func(listener net.Listener) {
|
|
|
|
log.Infof("RPCS: RPC server listening on %s", listener.Addr())
|
|
|
|
httpServer.Serve(listener)
|
|
|
|
log.Tracef("RPCS: RPC listener done for %s", listener.Addr())
|
|
|
|
s.wg.Done()
|
|
|
|
}(listener)
|
|
|
|
}
|
2013-09-09 20:14:57 +02:00
|
|
|
}
|
|
|
|
|
2013-12-05 17:59:08 +01:00
|
|
|
// checkAuth checks the HTTP Basic authentication supplied by a frontend
|
|
|
|
// in the HTTP request r. If the frontend's supplied authentication does
|
|
|
|
// not match the username and password expected, a non-nil error is
|
|
|
|
// returned.
|
|
|
|
//
|
|
|
|
// This check is time-constant.
|
|
|
|
func (s *server) checkAuth(r *http.Request) error {
|
|
|
|
authhdr := r.Header["Authorization"]
|
|
|
|
if len(authhdr) <= 0 {
|
|
|
|
log.Infof("Frontend did not supply authentication.")
|
|
|
|
return errors.New("auth failure")
|
|
|
|
}
|
|
|
|
|
|
|
|
authsha := sha256.Sum256([]byte(authhdr[0]))
|
|
|
|
cmp := subtle.ConstantTimeCompare(authsha[:], s.authsha[:])
|
|
|
|
if cmp != 1 {
|
|
|
|
log.Infof("Frontend did not supply correct authentication.")
|
|
|
|
return errors.New("auth failure")
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2014-01-03 19:34:37 +01:00
|
|
|
// BtcdWS opens a websocket connection to a btcd instance.
|
|
|
|
func BtcdWS(certificates []byte) (*websocket.Conn, error) {
|
2013-11-19 18:21:54 +01:00
|
|
|
url := fmt.Sprintf("wss://%s/wallet", cfg.Connect)
|
|
|
|
config, err := websocket.NewConfig(url, "https://localhost/")
|
2013-10-03 15:11:35 +02:00
|
|
|
if err != nil {
|
2014-01-03 19:34:37 +01:00
|
|
|
return nil, err
|
2013-10-03 15:11:35 +02:00
|
|
|
}
|
2013-11-19 18:21:54 +01:00
|
|
|
|
2014-01-03 19:34:37 +01:00
|
|
|
// btcd uses a self-signed TLS certifiate which is used as the CA.
|
2013-11-19 18:21:54 +01:00
|
|
|
pool := x509.NewCertPool()
|
|
|
|
pool.AppendCertsFromPEM(certificates)
|
|
|
|
config.TlsConfig = &tls.Config{
|
2013-11-21 22:41:15 +01:00
|
|
|
RootCAs: pool,
|
|
|
|
MinVersion: tls.VersionTLS12,
|
2013-11-19 18:21:54 +01:00
|
|
|
}
|
|
|
|
|
2014-01-03 19:34:37 +01:00
|
|
|
// btcd requires basic authorization, so set the Authorization header.
|
2013-11-19 18:21:54 +01:00
|
|
|
login := cfg.Username + ":" + cfg.Password
|
2013-11-20 00:25:42 +01:00
|
|
|
auth := "Basic " + base64.StdEncoding.EncodeToString([]byte(login))
|
2013-10-03 15:11:35 +02:00
|
|
|
config.Header.Add("Authorization", auth)
|
|
|
|
|
2014-01-03 19:34:37 +01:00
|
|
|
// Dial connection.
|
|
|
|
var ws *websocket.Conn
|
2013-11-20 02:47:15 +01:00
|
|
|
var cerr error
|
|
|
|
if cfg.Proxy != "" {
|
|
|
|
proxy := &socks.Proxy{
|
|
|
|
Addr: cfg.Proxy,
|
|
|
|
Username: cfg.ProxyUser,
|
|
|
|
Password: cfg.ProxyPass,
|
|
|
|
}
|
|
|
|
conn, err := proxy.Dial("tcp", cfg.Connect)
|
|
|
|
if err != nil {
|
2014-01-03 19:34:37 +01:00
|
|
|
return nil, err
|
2013-11-20 02:47:15 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
tlsConn := tls.Client(conn, config.TlsConfig)
|
2014-01-03 19:34:37 +01:00
|
|
|
ws, cerr = websocket.NewClient(config, tlsConn)
|
2013-11-20 02:47:15 +01:00
|
|
|
} else {
|
2014-01-03 19:34:37 +01:00
|
|
|
ws, cerr = websocket.DialConfig(config)
|
2013-11-20 02:47:15 +01:00
|
|
|
}
|
|
|
|
if cerr != nil {
|
2014-01-03 19:34:37 +01:00
|
|
|
return nil, cerr
|
2013-09-09 20:14:57 +02:00
|
|
|
}
|
2014-01-03 19:34:37 +01:00
|
|
|
return ws, nil
|
|
|
|
}
|
2013-11-21 21:01:23 +01:00
|
|
|
|
2014-01-03 19:34:37 +01:00
|
|
|
// BtcdConnect connects to a running btcd instance over a websocket
|
|
|
|
// for sending and receiving chain-related messages, failing if the
|
|
|
|
// connection cannot be established or is lost.
|
|
|
|
func BtcdConnect(certificates []byte) (*BtcdRPCConn, error) {
|
|
|
|
// Open websocket connection.
|
|
|
|
ws, err := BtcdWS(certificates)
|
|
|
|
if err != nil {
|
|
|
|
log.Errorf("Cannot open websocket connection to btcd: %v", err)
|
|
|
|
return nil, err
|
2013-11-21 21:01:23 +01:00
|
|
|
}
|
|
|
|
|
2014-01-03 19:34:37 +01:00
|
|
|
// Create and start RPC connection using the btcd websocket.
|
|
|
|
rpc := NewBtcdRPCConn(ws)
|
|
|
|
rpc.Start()
|
|
|
|
return rpc, nil
|
2013-10-07 18:35:32 +02:00
|
|
|
}
|
|
|
|
|
2014-01-03 19:34:37 +01:00
|
|
|
// resendUnminedTxs resends any transactions in the unmined transaction
|
|
|
|
// pool to btcd using the 'sendrawtransaction' RPC command.
|
2013-11-08 18:45:18 +01:00
|
|
|
func resendUnminedTxs() {
|
|
|
|
for _, createdTx := range UnminedTxs.m {
|
2014-01-03 19:34:37 +01:00
|
|
|
hextx := hex.EncodeToString(createdTx.rawTx)
|
|
|
|
if txid, err := SendRawTransaction(CurrentRPCConn(), hextx); err != nil {
|
|
|
|
// TODO(jrick): Check error for if this tx is a double spend,
|
|
|
|
// remove it if so.
|
|
|
|
} else {
|
|
|
|
log.Debugf("Resent unmined transaction %v", txid)
|
2013-11-08 18:45:18 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-01-03 19:34:37 +01:00
|
|
|
// Handshake first checks that the websocket connection between btcwallet and
|
|
|
|
// btcd is valid, that is, that there are no mismatching settings between
|
|
|
|
// the two processes (such as running on different Bitcoin networks). If the
|
|
|
|
// sanity checks pass, all wallets are set to be tracked against chain
|
|
|
|
// notifications from this btcd connection.
|
2013-12-06 21:37:07 +01:00
|
|
|
//
|
|
|
|
// TODO(jrick): Track and Rescan commands should be replaced with a
|
|
|
|
// single TrackSince function (or similar) which requests address
|
|
|
|
// notifications and performs the rescan since some block height.
|
2014-01-03 19:34:37 +01:00
|
|
|
func Handshake(rpc RPCConn) error {
|
|
|
|
net, jsonErr := GetCurrentNet(rpc)
|
|
|
|
if jsonErr != nil {
|
|
|
|
return jsonErr
|
2013-10-07 18:35:32 +02:00
|
|
|
}
|
2014-01-03 19:34:37 +01:00
|
|
|
if net != cfg.Net() {
|
2013-11-21 21:01:23 +01:00
|
|
|
return errors.New("btcd and btcwallet running on different Bitcoin networks")
|
2013-10-07 18:35:32 +02:00
|
|
|
}
|
|
|
|
|
2013-12-06 21:37:07 +01:00
|
|
|
// Get current best block. If this is before than the oldest
|
|
|
|
// saved block hash, assume that this btcd instance is not yet
|
|
|
|
// synced up to a previous btcd that was last used with this
|
|
|
|
// wallet.
|
|
|
|
bs, err := GetCurBlock()
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("cannot get best block: %v", err)
|
|
|
|
}
|
2013-12-13 17:00:31 +01:00
|
|
|
NotifyNewBlockChainHeight(frontendNotificationMaster, bs)
|
2013-12-06 21:37:07 +01:00
|
|
|
NotifyBalances(frontendNotificationMaster)
|
Implement address rescanning.
When a wallet is opened, a rescan request will be sent to btcd with
all active addresses from the wallet, to rescan from the last synced
block (now saved to the wallet file) and the current best block.
As multi-account support is further explored, rescan requests should
be batched together to send a single request for all addresses from
all wallets.
This change introduces several changes to the wallet, tx, and utxo
files. Wallet files are still compatible, however, a rescan will try
to start at the genesis block since no correct "last synced to" or
"created at block X" was saved. The tx and utxo files, however, are
not compatible and should be deleted (or an error will occur on read).
If any errors occur opening the utxo file, a rescan will start
beginning at the creation block saved in the wallet.
2013-10-30 02:22:14 +01:00
|
|
|
|
2013-12-09 22:51:07 +01:00
|
|
|
// Get default account. Only the default account is used to
|
|
|
|
// track recently-seen blocks.
|
|
|
|
a, err := accountstore.Account("")
|
|
|
|
if err != nil {
|
2014-01-10 01:20:11 +01:00
|
|
|
// No account yet is not a handshake error, but means our
|
|
|
|
// handshake is done.
|
|
|
|
return nil
|
2013-12-09 22:51:07 +01:00
|
|
|
}
|
|
|
|
|
2013-12-06 21:37:07 +01:00
|
|
|
// TODO(jrick): if height is less than the earliest-saved block
|
|
|
|
// height, should probably wait for btcd to catch up.
|
2013-12-02 20:56:06 +01:00
|
|
|
|
2013-12-06 21:37:07 +01:00
|
|
|
// Check that there was not any reorgs done since last connection.
|
|
|
|
// If so, rollback and rescan to catch up.
|
|
|
|
it := a.Wallet.NewIterateRecentBlocks()
|
|
|
|
for cont := it != nil; cont; cont = it.Prev() {
|
|
|
|
bs := it.BlockStamp()
|
|
|
|
log.Debugf("Checking for previous saved block with height %v hash %v",
|
|
|
|
bs.Height, bs.Hash)
|
2013-10-29 07:19:40 +01:00
|
|
|
|
2014-01-03 19:34:37 +01:00
|
|
|
_, err := GetBlock(rpc, bs.Hash.String())
|
|
|
|
if err != nil {
|
2013-12-06 21:37:07 +01:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
log.Debug("Found matching block.")
|
|
|
|
|
|
|
|
// If we had to go back to any previous blocks (it.Next
|
|
|
|
// returns true), then rollback the next and all child blocks.
|
|
|
|
// This rollback is done here instead of in the blockMissing
|
|
|
|
// check above for each removed block because Rollback will
|
|
|
|
// try to write new tx and utxo files on each rollback.
|
|
|
|
if it.Next() {
|
|
|
|
bs := it.BlockStamp()
|
|
|
|
accountstore.Rollback(bs.Height, &bs.Hash)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Set default account to be marked in sync with the current
|
|
|
|
// blockstamp. This invalidates the iterator.
|
|
|
|
a.Wallet.SetSyncedWith(bs)
|
|
|
|
|
|
|
|
// Begin tracking wallets against this btcd instance.
|
|
|
|
accountstore.Track()
|
|
|
|
accountstore.RescanActiveAddresses()
|
|
|
|
|
|
|
|
// (Re)send any unmined transactions to btcd in case of a btcd restart.
|
|
|
|
resendUnminedTxs()
|
Implement address rescanning.
When a wallet is opened, a rescan request will be sent to btcd with
all active addresses from the wallet, to rescan from the last synced
block (now saved to the wallet file) and the current best block.
As multi-account support is further explored, rescan requests should
be batched together to send a single request for all addresses from
all wallets.
This change introduces several changes to the wallet, tx, and utxo
files. Wallet files are still compatible, however, a rescan will try
to start at the genesis block since no correct "last synced to" or
"created at block X" was saved. The tx and utxo files, however, are
not compatible and should be deleted (or an error will occur on read).
If any errors occur opening the utxo file, a rescan will start
beginning at the creation block saved in the wallet.
2013-10-30 02:22:14 +01:00
|
|
|
|
2013-12-06 21:37:07 +01:00
|
|
|
// Get current blockchain height and best block hash.
|
|
|
|
return nil
|
Implement address rescanning.
When a wallet is opened, a rescan request will be sent to btcd with
all active addresses from the wallet, to rescan from the last synced
block (now saved to the wallet file) and the current best block.
As multi-account support is further explored, rescan requests should
be batched together to send a single request for all addresses from
all wallets.
This change introduces several changes to the wallet, tx, and utxo
files. Wallet files are still compatible, however, a rescan will try
to start at the genesis block since no correct "last synced to" or
"created at block X" was saved. The tx and utxo files, however, are
not compatible and should be deleted (or an error will occur on read).
If any errors occur opening the utxo file, a rescan will start
beginning at the creation block saved in the wallet.
2013-10-30 02:22:14 +01:00
|
|
|
}
|
2013-11-21 21:01:23 +01:00
|
|
|
|
2013-12-06 21:37:07 +01:00
|
|
|
log.Warnf("None of the previous saved blocks in btcd chain. Must perform full rescan.")
|
|
|
|
|
|
|
|
// Iterator was invalid (wallet has never been synced) or there was a
|
|
|
|
// huge chain fork + reorg (more than 20 blocks). Since we don't know
|
|
|
|
// what block (if any) this wallet is synced to, roll back everything
|
|
|
|
// and start a new rescan since the earliest block wallet must know
|
|
|
|
// about.
|
|
|
|
a.fullRescan = true
|
|
|
|
accountstore.Track()
|
|
|
|
accountstore.RescanActiveAddresses()
|
|
|
|
resendUnminedTxs()
|
2013-11-21 21:01:23 +01:00
|
|
|
return nil
|
2013-08-21 16:37:30 +02:00
|
|
|
}
|