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 (
|
|
|
|
"code.google.com/p/go.net/websocket"
|
2013-12-03 16:52:09 +01:00
|
|
|
"crypto/ecdsa"
|
|
|
|
"crypto/elliptic"
|
|
|
|
"crypto/rand"
|
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-12-03 16:52:09 +01:00
|
|
|
"crypto/x509/pkix"
|
2013-10-03 15:11:35 +02:00
|
|
|
"encoding/base64"
|
2013-08-21 16:37:30 +02:00
|
|
|
"encoding/json"
|
2013-12-03 16:52:09 +01:00
|
|
|
"encoding/pem"
|
2013-08-21 16:37:30 +02:00
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"github.com/conformal/btcjson"
|
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-08-27 22:45:22 +02:00
|
|
|
"github.com/conformal/btcwire"
|
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"
|
2013-12-03 16:52:09 +01:00
|
|
|
"math/big"
|
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
|
|
|
|
2013-10-29 07:19:40 +01:00
|
|
|
// Channel for updates and boolean with the most recent update of
|
|
|
|
// whether the connection to btcd is active or not.
|
2013-09-09 20:14:57 +02:00
|
|
|
btcdConnected = struct {
|
|
|
|
b bool
|
|
|
|
c chan bool
|
|
|
|
}{
|
|
|
|
c: make(chan bool),
|
|
|
|
}
|
2013-08-21 16:37:30 +02:00
|
|
|
|
2013-09-05 21:31:39 +02:00
|
|
|
// Channel to send messages btcwallet does not understand and requests
|
|
|
|
// from btcwallet to btcd.
|
2013-11-21 21:49:07 +01:00
|
|
|
btcdMsgs = make(chan []byte)
|
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-10-15 00:45:48 +02:00
|
|
|
// replyHandlers maps between a unique number (passed as part of
|
2013-09-05 18:50:39 +02:00
|
|
|
// the JSON Id field) and a function to handle a reply or notification
|
|
|
|
// from btcd. As requests are received, this map is checked for a
|
2013-10-07 18:35:32 +02:00
|
|
|
// handler function to route the reply to. If the function returns
|
|
|
|
// true, the handler is removed from the map.
|
2013-08-21 16:37:30 +02:00
|
|
|
replyHandlers = struct {
|
|
|
|
sync.Mutex
|
2013-09-09 20:14:57 +02:00
|
|
|
m map[uint64]func(interface{}, *btcjson.Error) bool
|
2013-08-21 16:37:30 +02:00
|
|
|
}{
|
2013-09-09 20:14:57 +02:00
|
|
|
m: make(map[uint64]func(interface{}, *btcjson.Error) bool),
|
2013-08-21 16:37:30 +02:00
|
|
|
}
|
2013-10-15 00:45:48 +02:00
|
|
|
|
|
|
|
// replyRouter maps unique uint64 ids to reply channels, so btcd
|
|
|
|
// replies can be routed to the correct frontend.
|
|
|
|
replyRouter = struct {
|
|
|
|
sync.Mutex
|
|
|
|
m map[uint64]chan []byte
|
|
|
|
}{
|
|
|
|
m: make(map[uint64]chan []byte),
|
|
|
|
}
|
2013-08-21 16:37:30 +02:00
|
|
|
)
|
|
|
|
|
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.
|
|
|
|
err := genKey(cfg.RPCKey, cfg.RPCCert)
|
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2013-12-03 16:52:09 +01:00
|
|
|
// genkey generates a key/cert pair to the paths provided.
|
|
|
|
// TODO(oga) wrap errors with fmt.Errorf for more context?
|
|
|
|
func genKey(key, cert string) error {
|
|
|
|
log.Infof("Generating TLS certificates...")
|
|
|
|
priv, err := ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
notBefore := time.Now()
|
|
|
|
notAfter := notBefore.Add(10 * 365 * 24 * time.Hour)
|
|
|
|
|
|
|
|
// end of ASN.1 time
|
|
|
|
endOfTime := time.Date(2049, 12, 31, 23, 59, 59, 0, time.UTC)
|
|
|
|
if notAfter.After(endOfTime) {
|
|
|
|
notAfter = endOfTime
|
|
|
|
}
|
|
|
|
|
|
|
|
template := x509.Certificate{
|
|
|
|
SerialNumber: new(big.Int).SetInt64(0),
|
|
|
|
Subject: pkix.Name{
|
|
|
|
Organization: []string{"btcwallet autogenerated cert"},
|
|
|
|
},
|
|
|
|
NotBefore: notBefore,
|
|
|
|
NotAfter: notAfter,
|
|
|
|
|
|
|
|
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageCertSign,
|
|
|
|
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
|
|
|
IsCA: true, // so can sign self.
|
|
|
|
BasicConstraintsValid: true,
|
|
|
|
}
|
|
|
|
|
|
|
|
host, err := os.Hostname()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
template.DNSNames = append(template.DNSNames, host, "localhost")
|
|
|
|
|
|
|
|
needLocalhost := true
|
|
|
|
addrs, err := net.InterfaceAddrs()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
for _, a := range addrs {
|
|
|
|
ip, _, err := net.ParseCIDR(a.String())
|
|
|
|
if err == nil {
|
|
|
|
if ip.String() == "127.0.0.1" {
|
|
|
|
needLocalhost = false
|
|
|
|
}
|
|
|
|
template.IPAddresses = append(template.IPAddresses, ip)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if needLocalhost {
|
|
|
|
localHost := net.ParseIP("127.0.0.1")
|
|
|
|
template.IPAddresses = append(template.IPAddresses, localHost)
|
|
|
|
}
|
|
|
|
|
|
|
|
derBytes, err := x509.CreateCertificate(rand.Reader, &template,
|
|
|
|
&template, &priv.PublicKey, priv)
|
|
|
|
if err != nil {
|
|
|
|
fmt.Fprintf(os.Stderr, "Failed to create certificate: %v\n", err)
|
|
|
|
os.Exit(-1)
|
|
|
|
}
|
|
|
|
|
|
|
|
certOut, err := os.Create(cert)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
|
|
|
|
certOut.Close()
|
|
|
|
|
|
|
|
keyOut, err := os.OpenFile(key, os.O_WRONLY|os.O_CREATE|os.O_TRUNC,
|
|
|
|
0600)
|
|
|
|
if err != nil {
|
|
|
|
os.Remove(cert)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
keybytes, err := x509.MarshalECPrivateKey(priv)
|
|
|
|
if err != nil {
|
|
|
|
os.Remove(key)
|
|
|
|
os.Remove(cert)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
pem.Encode(keyOut, &pem.Block{Type: "EC PRIVATE KEY", Bytes: keybytes})
|
|
|
|
keyOut.Close()
|
|
|
|
|
|
|
|
log.Info("Done generating TLS certificates")
|
|
|
|
|
|
|
|
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) {
|
|
|
|
frontend := make(chan []byte)
|
|
|
|
|
|
|
|
body, err := btcjson.GetRaw(r.Body)
|
|
|
|
if err != nil {
|
|
|
|
log.Errorf("RPCS: Error getting JSON message: %v", err)
|
|
|
|
}
|
|
|
|
|
2013-11-18 22:37:28 +01:00
|
|
|
done := make(chan struct{})
|
|
|
|
go func() {
|
|
|
|
if _, err := w.Write(<-frontend); err != nil {
|
|
|
|
log.Warnf("RPCS: could not respond to RPC request: %v",
|
|
|
|
err)
|
|
|
|
}
|
|
|
|
close(done)
|
|
|
|
}()
|
|
|
|
|
2013-11-20 02:18:11 +01:00
|
|
|
ProcessRequest(frontend, body, false)
|
2013-11-18 22:37:28 +01:00
|
|
|
<-done
|
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
|
|
|
|
2013-10-29 07:19:40 +01:00
|
|
|
// TODO(jrick): these notifications belong somewhere better.
|
|
|
|
// Probably want to copy AddWalletListener from btcd, and
|
|
|
|
// place these notifications in that function.
|
2013-10-29 14:19:11 +01:00
|
|
|
NotifyBtcdConnected(frontendNotificationMaster,
|
|
|
|
btcdConnected.b)
|
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
|
|
|
if bs, err := GetCurBlock(); 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 {
|
2013-09-09 20:14:57 +02:00
|
|
|
var ntfn []byte
|
|
|
|
|
|
|
|
select {
|
|
|
|
case conn := <-btcdConnected.c:
|
2013-10-29 14:19:11 +01:00
|
|
|
NotifyBtcdConnected(frontendNotificationMaster, conn)
|
|
|
|
continue
|
2013-09-09 20:14:57 +02:00
|
|
|
|
|
|
|
case ntfn = <-frontendNotificationMaster:
|
|
|
|
}
|
|
|
|
|
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()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
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
|
|
|
// NotifyBtcdConnected notifies all frontends of a new btcd connection.
|
2013-10-29 14:19:11 +01:00
|
|
|
func NotifyBtcdConnected(reply chan []byte, conn bool) {
|
|
|
|
btcdConnected.b = conn
|
2013-12-13 17:00:31 +01:00
|
|
|
|
|
|
|
ntfn := btcws.NewBtcdConnectedNtfn(conn)
|
|
|
|
mntfn, _ := ntfn.MarshalJSON()
|
|
|
|
frontendNotificationMaster <- mntfn
|
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.
|
2013-11-20 02:18:11 +01:00
|
|
|
go ProcessRequest(frontendNotification, m, true)
|
2013-08-21 16:37:30 +02:00
|
|
|
case ntfn, _ := <-frontendNotification:
|
|
|
|
if err := websocket.Message.Send(ws, ntfn); err != nil {
|
|
|
|
// Frontend disconnected.
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// BtcdHandler listens for replies and notifications from btcd over a
|
|
|
|
// websocket and sends messages that btcwallet does not understand to
|
|
|
|
// btcd. Unlike FrontendHandler, exactly one BtcdHandler goroutine runs.
|
2013-11-21 21:49:07 +01:00
|
|
|
// BtcdHandler spawns goroutines to perform these tasks, and closes the
|
|
|
|
// done channel once they are finished.
|
2013-11-21 19:45:14 +01:00
|
|
|
func BtcdHandler(ws *websocket.Conn, done chan struct{}) {
|
2013-08-21 16:37:30 +02:00
|
|
|
// Listen for replies/notifications from btcd, and decide how to handle them.
|
|
|
|
replies := make(chan []byte)
|
|
|
|
go func() {
|
|
|
|
for {
|
2013-11-21 21:49:07 +01:00
|
|
|
var m []byte
|
|
|
|
if err := websocket.Message.Receive(ws, &m); err != nil {
|
|
|
|
log.Debugf("cannot recevie btcd message: %v", err)
|
|
|
|
close(replies)
|
2013-08-21 16:37:30 +02:00
|
|
|
return
|
|
|
|
}
|
2013-11-21 21:49:07 +01:00
|
|
|
replies <- m
|
2013-08-21 16:37:30 +02:00
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
2013-11-21 19:45:14 +01:00
|
|
|
go func() {
|
2013-11-21 21:49:07 +01:00
|
|
|
defer close(done)
|
2013-11-21 19:45:14 +01:00
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case rply, ok := <-replies:
|
|
|
|
if !ok {
|
|
|
|
// btcd disconnected
|
|
|
|
return
|
|
|
|
}
|
|
|
|
// Handle message here.
|
|
|
|
go ProcessBtcdNotificationReply(rply)
|
|
|
|
|
|
|
|
case r := <-btcdMsgs:
|
|
|
|
if err := websocket.Message.Send(ws, r); err != nil {
|
|
|
|
// btcd disconnected.
|
|
|
|
log.Errorf("Unable to send message to btcd: %v", err)
|
|
|
|
return
|
|
|
|
}
|
2013-08-21 16:37:30 +02:00
|
|
|
}
|
|
|
|
}
|
2013-11-21 19:45:14 +01:00
|
|
|
}()
|
2013-08-21 16:37:30 +02:00
|
|
|
}
|
|
|
|
|
2013-12-13 17:00:31 +01:00
|
|
|
type notificationHandler func(btcjson.Cmd, []byte)
|
2013-11-08 18:45:18 +01:00
|
|
|
|
|
|
|
var notificationHandlers = map[string]notificationHandler{
|
2013-12-13 17:00:31 +01:00
|
|
|
btcws.BlockConnectedNtfnMethod: NtfnBlockConnected,
|
|
|
|
btcws.BlockDisconnectedNtfnMethod: NtfnBlockDisconnected,
|
|
|
|
btcws.TxMinedNtfnMethod: NtfnTxMined,
|
2013-11-08 18:45:18 +01:00
|
|
|
}
|
|
|
|
|
2013-08-21 16:37:30 +02:00
|
|
|
// ProcessBtcdNotificationReply unmarshalls the JSON notification or
|
|
|
|
// reply received from btcd and decides how to handle it. Replies are
|
|
|
|
// routed back to the frontend who sent the message, and wallet
|
|
|
|
// notifications are processed by btcwallet, and frontend notifications
|
|
|
|
// are sent to every connected frontend.
|
|
|
|
func ProcessBtcdNotificationReply(b []byte) {
|
2013-12-13 17:00:31 +01:00
|
|
|
// Idea: instead of reading btcd messages from just one websocket
|
|
|
|
// connection, maybe use two so the same connection isn't used
|
|
|
|
// for both notifications and responses? Should make handling
|
|
|
|
// must faster as unnecessary unmarshal attempts could be avoided.
|
|
|
|
|
|
|
|
// Check for notifications first.
|
|
|
|
if req, err := btcjson.ParseMarshaledCmd(b); err == nil {
|
|
|
|
// btcd should not be sending Requests except for
|
|
|
|
// notifications. Check for a nil id.
|
|
|
|
if req.Id() != nil {
|
|
|
|
// Invalid response
|
|
|
|
log.Warnf("btcd sent a non-notification JSON-RPC Request (ID: %v)",
|
|
|
|
req.Id())
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Message is a btcd notification. Check the method and dispatch
|
|
|
|
// correct handler, or if no handler, pass up to each wallet.
|
|
|
|
if ntfnHandler, ok := notificationHandlers[req.Method()]; ok {
|
|
|
|
ntfnHandler(req, b)
|
|
|
|
} else {
|
|
|
|
// No handler; send to all wallets.
|
|
|
|
frontendNotificationMaster <- b
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
2013-08-21 16:37:30 +02:00
|
|
|
|
2013-12-13 17:00:31 +01:00
|
|
|
// b is not a Request notification, so it must be a Response.
|
|
|
|
// Attempt to parse it as one and handle.
|
2013-09-09 20:14:57 +02:00
|
|
|
var r btcjson.Reply
|
|
|
|
if err := json.Unmarshal(b, &r); err != nil {
|
2013-12-13 17:00:31 +01:00
|
|
|
log.Warn("Unable to process btcd message as notification or response")
|
2013-09-09 20:14:57 +02:00
|
|
|
return
|
|
|
|
}
|
2013-12-13 17:00:31 +01:00
|
|
|
|
|
|
|
// Check for a valid ID.
|
|
|
|
//
|
|
|
|
// TODO(jrick): Remove this terrible ID overloading. Each
|
|
|
|
// passed-through request should be given a new unique ID number
|
|
|
|
// (reading from the NewJSONID channel) and a reply route with the
|
|
|
|
// frontend's incoming ID should be set.
|
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
|
|
|
if r.Id == nil {
|
2013-12-13 17:00:31 +01:00
|
|
|
// Responses with no IDs cannot be handled.
|
|
|
|
log.Warn("Unable to process btcd response without ID")
|
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
|
|
|
return
|
|
|
|
}
|
2013-09-09 20:14:57 +02:00
|
|
|
idStr, ok := (*r.Id).(string)
|
2013-08-21 16:37:30 +02:00
|
|
|
if !ok {
|
2013-12-13 17:00:31 +01:00
|
|
|
// btcd's responses to btcwallet should (currently, see TODO above)
|
|
|
|
// only ever be sending string IDs. If ID is not a string, log the
|
|
|
|
// error and drop the message.
|
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
|
|
|
log.Error("Incorrect btcd notification id type.")
|
2013-08-21 16:37:30 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2013-12-13 17:00:31 +01:00
|
|
|
var routeID uint64
|
|
|
|
var origID string
|
2013-09-09 20:14:57 +02:00
|
|
|
n, _ := fmt.Sscanf(idStr, "btcwallet(%d)-%s", &routeID, &origID)
|
2013-08-21 16:37:30 +02:00
|
|
|
if n == 1 {
|
|
|
|
// Request originated from btcwallet. Run and remove correct
|
|
|
|
// handler.
|
|
|
|
replyHandlers.Lock()
|
2013-09-09 20:14:57 +02:00
|
|
|
f := replyHandlers.m[routeID]
|
2013-08-21 16:37:30 +02:00
|
|
|
replyHandlers.Unlock()
|
|
|
|
if f != nil {
|
|
|
|
go func() {
|
2013-09-09 20:14:57 +02:00
|
|
|
if f(r.Result, r.Error) {
|
2013-08-21 16:37:30 +02:00
|
|
|
replyHandlers.Lock()
|
2013-09-09 20:14:57 +02:00
|
|
|
delete(replyHandlers.m, routeID)
|
2013-08-21 16:37:30 +02:00
|
|
|
replyHandlers.Unlock()
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
}
|
|
|
|
} else if n == 2 {
|
|
|
|
// Attempt to route btcd reply to correct frontend.
|
|
|
|
replyRouter.Lock()
|
2013-09-09 20:14:57 +02:00
|
|
|
c := replyRouter.m[routeID]
|
2013-08-21 16:37:30 +02:00
|
|
|
if c != nil {
|
2013-09-09 20:14:57 +02:00
|
|
|
delete(replyRouter.m, routeID)
|
2013-08-21 16:37:30 +02:00
|
|
|
} else {
|
|
|
|
// Can't route to a frontend, drop reply.
|
2013-11-21 16:48:35 +01:00
|
|
|
replyRouter.Unlock()
|
2013-08-21 16:37:30 +02:00
|
|
|
log.Info("Unable to route btcd reply to frontend. Dropping.")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
replyRouter.Unlock()
|
|
|
|
|
|
|
|
// Convert string back to number if possible.
|
2013-09-09 20:14:57 +02:00
|
|
|
var origIDNum float64
|
|
|
|
n, _ := fmt.Sscanf(origID, "%f", &origIDNum)
|
|
|
|
var id interface{}
|
2013-08-21 16:37:30 +02:00
|
|
|
if n == 1 {
|
2013-09-09 20:14:57 +02:00
|
|
|
id = origIDNum
|
2013-08-21 16:37:30 +02:00
|
|
|
} else {
|
2013-09-09 20:14:57 +02:00
|
|
|
id = origID
|
2013-08-21 16:37:30 +02:00
|
|
|
}
|
2013-09-09 20:14:57 +02:00
|
|
|
r.Id = &id
|
2013-08-21 16:37:30 +02:00
|
|
|
|
2013-09-09 20:14:57 +02:00
|
|
|
b, err := json.Marshal(r)
|
2013-08-21 16:37:30 +02:00
|
|
|
if err != nil {
|
|
|
|
log.Error("Error marshalling btcd reply. Dropping.")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
c <- b
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
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
|
|
|
// NtfnBlockConnected handles btcd notifications resulting from newly
|
2013-11-05 00:58:41 +01:00
|
|
|
// connected blocks to the main blockchain.
|
2013-12-09 23:03:51 +01:00
|
|
|
//
|
|
|
|
// TODO(jrick): Send block time with notification. This will be used
|
|
|
|
// to mark wallet files with a possibly-better earliest block height,
|
|
|
|
// and will greatly reduce rescan times for wallets created with an
|
|
|
|
// out of sync btcd.
|
2013-12-13 17:00:31 +01:00
|
|
|
func NtfnBlockConnected(n btcjson.Cmd, marshaled []byte) {
|
2013-11-08 18:45:18 +01:00
|
|
|
bcn, ok := n.(*btcws.BlockConnectedNtfn)
|
2013-09-09 20:14:57 +02:00
|
|
|
if !ok {
|
2013-12-13 17:00:31 +01:00
|
|
|
log.Errorf("%v handler: unexpected type", n.Method())
|
2013-09-09 20:14:57 +02:00
|
|
|
return
|
|
|
|
}
|
2013-11-08 18:45:18 +01:00
|
|
|
hash, err := btcwire.NewShaHashFromStr(bcn.Hash)
|
2013-09-09 20:14:57 +02:00
|
|
|
if err != nil {
|
2013-12-13 17:00:31 +01:00
|
|
|
log.Errorf("%v handler: invalid hash string", n.Method())
|
2013-10-24 00:23:20 +02:00
|
|
|
return
|
2013-09-09 20:14:57 +02:00
|
|
|
}
|
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-12 20:53:38 +01:00
|
|
|
// Update the blockstamp for the newly-connected block.
|
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
|
|
|
bs := &wallet.BlockStamp{
|
2013-11-08 18:45:18 +01:00
|
|
|
Height: bcn.Height,
|
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
|
|
|
Hash: *hash,
|
|
|
|
}
|
2013-11-08 18:45:18 +01:00
|
|
|
curBlock.Lock()
|
|
|
|
curBlock.BlockStamp = *bs
|
|
|
|
curBlock.Unlock()
|
2013-11-12 20:53:38 +01:00
|
|
|
|
|
|
|
// btcd notifies btcwallet about transactions first, and then sends
|
|
|
|
// the new block notification. New balance notifications for txs
|
|
|
|
// in blocks are therefore sent here after all tx notifications
|
2013-12-17 19:18:09 +01:00
|
|
|
// have arrived and finished being processed by the handlers.
|
|
|
|
workers := NotifyBalanceRequest{
|
|
|
|
block: *hash,
|
|
|
|
wg: make(chan *sync.WaitGroup),
|
|
|
|
}
|
|
|
|
NotifyBalanceSyncerChans.access <- workers
|
|
|
|
if wg := <-workers.wg; wg != nil {
|
|
|
|
wg.Wait()
|
|
|
|
NotifyBalanceSyncerChans.remove <- *hash
|
|
|
|
}
|
2013-12-02 20:56:06 +01:00
|
|
|
accountstore.BlockNotify(bs)
|
2013-10-29 07:19:40 +01:00
|
|
|
|
2013-12-13 17:00:31 +01:00
|
|
|
// Pass notification to frontends too.
|
|
|
|
frontendNotificationMaster <- marshaled
|
2013-09-09 20:14:57 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// NtfnBlockDisconnected handles btcd notifications resulting from
|
|
|
|
// blocks disconnected from the main chain in the event of a chain
|
|
|
|
// switch and notifies frontends of the new blockchain height.
|
2013-12-13 17:00:31 +01:00
|
|
|
func NtfnBlockDisconnected(n btcjson.Cmd, marshaled []byte) {
|
2013-11-08 18:45:18 +01:00
|
|
|
bdn, ok := n.(*btcws.BlockDisconnectedNtfn)
|
2013-09-09 20:14:57 +02:00
|
|
|
if !ok {
|
2013-12-13 17:00:31 +01:00
|
|
|
log.Errorf("%v handler: unexpected type", n.Method())
|
2013-09-09 20:14:57 +02:00
|
|
|
return
|
|
|
|
}
|
2013-11-08 18:45:18 +01:00
|
|
|
hash, err := btcwire.NewShaHashFromStr(bdn.Hash)
|
2013-08-21 16:37:30 +02:00
|
|
|
if err != nil {
|
2013-12-13 17:00:31 +01:00
|
|
|
log.Errorf("%v handler: invalid hash string", n.Method())
|
2013-09-09 20:14:57 +02:00
|
|
|
return
|
|
|
|
}
|
2013-08-21 16:37:30 +02:00
|
|
|
|
2013-09-09 20:14:57 +02:00
|
|
|
// Rollback Utxo and Tx data stores.
|
|
|
|
go func() {
|
2013-12-02 20:56:06 +01:00
|
|
|
accountstore.Rollback(bdn.Height, hash)
|
2013-09-09 20:14:57 +02:00
|
|
|
}()
|
2013-08-21 16:37:30 +02:00
|
|
|
|
2013-12-13 17:00:31 +01:00
|
|
|
// Pass notification to frontends too.
|
|
|
|
frontendNotificationMaster <- marshaled
|
2013-11-08 18:45:18 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// NtfnTxMined handles btcd notifications resulting from newly
|
|
|
|
// mined transactions that originated from this wallet.
|
2013-12-13 17:00:31 +01:00
|
|
|
func NtfnTxMined(n btcjson.Cmd, marshaled []byte) {
|
2013-11-08 18:45:18 +01:00
|
|
|
tmn, ok := n.(*btcws.TxMinedNtfn)
|
|
|
|
if !ok {
|
2013-12-13 17:00:31 +01:00
|
|
|
log.Errorf("%v handler: unexpected type", n.Method())
|
2013-11-08 18:45:18 +01:00
|
|
|
return
|
|
|
|
}
|
2013-11-22 19:42:25 +01:00
|
|
|
|
2013-11-25 18:54:49 +01:00
|
|
|
txid, err := btcwire.NewShaHashFromStr(tmn.TxID)
|
2013-11-08 18:45:18 +01:00
|
|
|
if err != nil {
|
2013-12-13 17:00:31 +01:00
|
|
|
log.Errorf("%v handler: invalid hash string", n.Method())
|
2013-11-08 18:45:18 +01:00
|
|
|
return
|
|
|
|
}
|
2013-11-22 19:42:25 +01:00
|
|
|
blockhash, err := btcwire.NewShaHashFromStr(tmn.BlockHash)
|
|
|
|
if err != nil {
|
2013-12-13 17:00:31 +01:00
|
|
|
log.Errorf("%v handler: invalid block hash string", n.Method())
|
2013-11-22 19:42:25 +01:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2013-12-02 20:56:06 +01:00
|
|
|
err = accountstore.RecordMinedTx(txid, blockhash,
|
|
|
|
tmn.BlockHeight, tmn.Index, tmn.BlockTime)
|
|
|
|
if err != nil {
|
2013-12-13 17:00:31 +01:00
|
|
|
log.Errorf("%v handler: %v", n.Method(), err)
|
2013-12-02 20:56:06 +01:00
|
|
|
return
|
2013-11-22 19:42:25 +01:00
|
|
|
}
|
2013-11-08 18:45:18 +01:00
|
|
|
|
|
|
|
// Remove mined transaction from pool.
|
|
|
|
UnminedTxs.Lock()
|
2013-11-22 19:42:25 +01:00
|
|
|
delete(UnminedTxs.m, TXID(*txid))
|
2013-11-08 18:45:18 +01:00
|
|
|
UnminedTxs.Unlock()
|
2013-09-09 20:14:57 +02:00
|
|
|
}
|
2013-09-05 17:51:33 +02: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
|
|
|
|
}
|
|
|
|
|
2013-09-09 20:14:57 +02: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.
|
2013-11-19 18:21:54 +01:00
|
|
|
func BtcdConnect(certificates []byte, reply chan error) {
|
|
|
|
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 {
|
|
|
|
reply <- ErrConnRefused
|
|
|
|
return
|
|
|
|
}
|
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
|
|
|
}
|
|
|
|
|
|
|
|
// btcd requires basic authorization, so we use a custom config with
|
|
|
|
// the Authorization header set.
|
|
|
|
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)
|
|
|
|
|
2013-09-09 20:14:57 +02:00
|
|
|
// Attempt to connect to running btcd instance. Bail if it fails.
|
2013-11-20 02:47:15 +01:00
|
|
|
var btcdws *websocket.Conn
|
|
|
|
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 {
|
|
|
|
log.Warnf("Error connecting to proxy: %v", err)
|
|
|
|
reply <- ErrConnRefused
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
tlsConn := tls.Client(conn, config.TlsConfig)
|
|
|
|
btcdws, cerr = websocket.NewClient(config, tlsConn)
|
|
|
|
} else {
|
|
|
|
btcdws, cerr = websocket.DialConfig(config)
|
|
|
|
}
|
|
|
|
if cerr != nil {
|
|
|
|
log.Errorf("%s", cerr)
|
2013-09-09 20:14:57 +02:00
|
|
|
reply <- ErrConnRefused
|
|
|
|
return
|
|
|
|
}
|
|
|
|
reply <- nil
|
|
|
|
|
|
|
|
// Remove all reply handlers (if any exist from an old connection).
|
|
|
|
replyHandlers.Lock()
|
|
|
|
for k := range replyHandlers.m {
|
|
|
|
delete(replyHandlers.m, k)
|
|
|
|
}
|
|
|
|
replyHandlers.Unlock()
|
|
|
|
|
2013-11-21 19:45:14 +01:00
|
|
|
done := make(chan struct{})
|
|
|
|
BtcdHandler(btcdws, done)
|
2013-11-21 21:01:23 +01:00
|
|
|
|
|
|
|
if err := BtcdHandshake(btcdws); err != nil {
|
|
|
|
log.Errorf("%v", err)
|
|
|
|
reply <- ErrConnRefused
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2013-11-21 21:49:07 +01:00
|
|
|
// done is closed when BtcdHandler's goroutines are finished.
|
2013-11-21 19:45:14 +01:00
|
|
|
<-done
|
2013-10-07 18:35:32 +02:00
|
|
|
reply <- ErrConnLost
|
|
|
|
}
|
|
|
|
|
2013-11-08 18:45:18 +01:00
|
|
|
// resendUnminedTxs resends any transactions in the unmined
|
|
|
|
// transaction pool to btcd using the 'sendrawtransaction' RPC
|
|
|
|
// command.
|
|
|
|
func resendUnminedTxs() {
|
|
|
|
for _, createdTx := range UnminedTxs.m {
|
|
|
|
n := <-NewJSONID
|
|
|
|
var id interface{} = fmt.Sprintf("btcwallet(%v)", n)
|
|
|
|
m, err := btcjson.CreateMessageWithId("sendrawtransaction", id, string(createdTx.rawTx))
|
|
|
|
if err != nil {
|
|
|
|
log.Errorf("cannot create resend request: %v", err)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
replyHandlers.Lock()
|
|
|
|
replyHandlers.m[n] = func(result interface{}, err *btcjson.Error) bool {
|
|
|
|
// Do nothing, just remove the handler.
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
replyHandlers.Unlock()
|
|
|
|
btcdMsgs <- m
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2013-10-07 18:35:32 +02:00
|
|
|
// BtcdHandshake 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.
|
2013-11-21 21:01:23 +01:00
|
|
|
func BtcdHandshake(ws *websocket.Conn) error {
|
2013-10-15 16:40:23 +02:00
|
|
|
n := <-NewJSONID
|
2013-12-06 21:37:07 +01:00
|
|
|
var cmd btcjson.Cmd
|
|
|
|
cmd = btcws.NewGetCurrentNetCmd(fmt.Sprintf("btcwallet(%v)", n))
|
2013-11-06 17:23:30 +01:00
|
|
|
mcmd, err := cmd.MarshalJSON()
|
|
|
|
if err != nil {
|
2013-11-21 21:01:23 +01:00
|
|
|
return fmt.Errorf("cannot complete btcd handshake: %v", err)
|
2013-10-07 18:35:32 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
correctNetwork := make(chan bool)
|
|
|
|
|
|
|
|
replyHandlers.Lock()
|
|
|
|
replyHandlers.m[n] = func(result interface{}, err *btcjson.Error) bool {
|
|
|
|
fnet, ok := result.(float64)
|
|
|
|
if !ok {
|
|
|
|
log.Error("btcd handshake: result is not a number")
|
|
|
|
correctNetwork <- false
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
Introduce new account file structure.
This changes the locations that account files (wallet.bin, utxo.bin,
and tx.bin) are searched for when opening or disk syncing accounts.
Previously, files were saved in the following layout:
~/.btcwallet/
- btcwallet/
- wallet.bin
- tx.bin
- utxo.bin
- btcwallet-AccountA/
- wallet.bin
- tx.bin
- utxo.bin
This format had two issues. First, each account would require its own
directory, causing a scalability issue on unix (and perhaps other)
platforms. Second, there was no distinction between testnet and
mainnet wallets, and if mainnet support was enabled, btcwallet would
attempt to open accounts with testnet wallets.
Instead, the following file structure is now used:
~/.btcwallet/
- testnet/
- wallet.bin
- tx.bin
- utxo.bin
- AccountA-wallet.bin
- AccountA-tx.bin
- AccountA-utxo.bin
This solves both of the previously-mentioned issues by requiring only
two subdirectories (one each for the testnet and mainnet bitcoin
networks), and by separating the locations to open and save testnet
and mainnet account files.
At startup, a check for the old account file structure is performed.
If found, files are moved to the new locations, and the old account
directories are removed. Account files are moved to the testnet
directory, as only testnet support is currently enabled.
The version has been bumped to 0.1.1 to reflect this change.
Fixes #16.
2013-12-05 02:16:50 +01:00
|
|
|
correctNetwork <- btcwire.BitcoinNet(fnet) == cfg.Net()
|
2013-10-07 18:35:32 +02:00
|
|
|
|
|
|
|
// No additional replies expected, remove handler.
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
replyHandlers.Unlock()
|
|
|
|
|
2013-11-06 17:23:30 +01:00
|
|
|
btcdMsgs <- mcmd
|
2013-10-07 18:35:32 +02:00
|
|
|
|
|
|
|
if !<-correctNetwork {
|
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 {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
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
|
|
|
|
2013-12-06 21:37:07 +01:00
|
|
|
n = <-NewJSONID
|
|
|
|
// NewGetBlockCmd can't fail, so don't check error.
|
|
|
|
// TODO(jrick): probably want to remove the error return value.
|
|
|
|
cmd, _ = btcjson.NewGetBlockCmd(fmt.Sprintf("btcwallet(%v)", n),
|
|
|
|
bs.Hash.String())
|
|
|
|
mcmd, _ = cmd.MarshalJSON()
|
|
|
|
|
|
|
|
blockMissing := make(chan bool)
|
|
|
|
|
|
|
|
replyHandlers.Lock()
|
|
|
|
replyHandlers.m[n] = func(result interface{}, err *btcjson.Error) bool {
|
|
|
|
blockMissing <- err != nil && err.Code == btcjson.ErrBlockNotFound.Code
|
|
|
|
|
|
|
|
// No additional replies expected, remove handler.
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
replyHandlers.Unlock()
|
|
|
|
|
|
|
|
btcdMsgs <- mcmd
|
|
|
|
|
|
|
|
if <-blockMissing {
|
|
|
|
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
|
|
|
}
|