2015-05-01 08:28:01 +02:00
|
|
|
// Copyright (c) 2013-2015 The btcsuite developers
|
2013-12-31 20:15:44 +01:00
|
|
|
// Use of this source code is governed by an ISC
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"container/list"
|
2014-01-22 21:10:04 +01:00
|
|
|
"crypto/subtle"
|
|
|
|
"encoding/base64"
|
2014-01-08 17:40:27 +01:00
|
|
|
"encoding/hex"
|
2013-12-31 20:15:44 +01:00
|
|
|
"encoding/json"
|
2014-02-24 15:10:59 +01:00
|
|
|
"errors"
|
2013-12-31 20:15:44 +01:00
|
|
|
"fmt"
|
2014-07-02 15:50:08 +02:00
|
|
|
"io"
|
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
|
2015-04-06 06:15:49 +02:00
|
|
|
"github.com/btcsuite/btcd/btcjson"
|
2015-01-27 22:38:23 +01:00
|
|
|
"github.com/btcsuite/btcd/database"
|
2015-01-30 19:14:33 +01:00
|
|
|
"github.com/btcsuite/btcd/txscript"
|
2015-02-05 22:16:39 +01:00
|
|
|
"github.com/btcsuite/btcd/wire"
|
2015-01-15 17:30:38 +01:00
|
|
|
"github.com/btcsuite/btcutil"
|
2015-01-16 16:10:29 +01:00
|
|
|
"github.com/btcsuite/fastsha256"
|
2015-03-04 04:05:26 +01:00
|
|
|
"github.com/btcsuite/golangcrypto/ripemd160"
|
2015-01-16 00:20:30 +01:00
|
|
|
"github.com/btcsuite/websocket"
|
2013-12-31 20:15:44 +01:00
|
|
|
)
|
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
const (
|
|
|
|
// websocketSendBufferSize is the number of elements the send channel
|
|
|
|
// can queue before blocking. Note that this only applies to requests
|
|
|
|
// handled directly in the websocket client input handler or the async
|
2016-02-25 18:17:12 +01:00
|
|
|
// handler since notifications have their own queuing mechanism
|
2014-02-19 00:23:33 +01:00
|
|
|
// independent of the send channel buffer.
|
|
|
|
websocketSendBufferSize = 50
|
|
|
|
)
|
2014-01-08 17:40:27 +01:00
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
// timeZeroVal is simply the zero value for a time.Time and is used to avoid
|
|
|
|
// creating multiple instances.
|
|
|
|
var timeZeroVal time.Time
|
2014-01-14 21:59:31 +01:00
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
// wsCommandHandler describes a callback function used to handle a specific
|
|
|
|
// command.
|
2015-02-21 05:34:57 +01:00
|
|
|
type wsCommandHandler func(*wsClient, interface{}) (interface{}, error)
|
2013-12-31 21:48:50 +01:00
|
|
|
|
|
|
|
// wsHandlers maps RPC command strings to appropriate websocket handler
|
2015-02-21 05:34:57 +01:00
|
|
|
// functions. This is set by init because help references wsHandlers and thus
|
|
|
|
// causes a dependency loop.
|
|
|
|
var wsHandlers map[string]wsCommandHandler
|
|
|
|
var wsHandlersBeforeInit = map[string]wsCommandHandler{
|
2015-03-03 21:37:02 +01:00
|
|
|
"help": handleWebsocketHelp,
|
|
|
|
"notifyblocks": handleNotifyBlocks,
|
|
|
|
"notifynewtransactions": handleNotifyNewTransactions,
|
|
|
|
"notifyreceived": handleNotifyReceived,
|
|
|
|
"notifyspent": handleNotifySpent,
|
2015-09-15 20:03:48 +02:00
|
|
|
"session": handleSession,
|
2015-03-03 21:37:02 +01:00
|
|
|
"stopnotifyblocks": handleStopNotifyBlocks,
|
|
|
|
"stopnotifynewtransactions": handleStopNotifyNewTransactions,
|
|
|
|
"stopnotifyspent": handleStopNotifySpent,
|
|
|
|
"stopnotifyreceived": handleStopNotifyReceived,
|
|
|
|
"rescan": handleRescan,
|
2013-12-31 21:48:50 +01:00
|
|
|
}
|
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
// wsAsyncHandlers holds the websocket commands which should be run
|
|
|
|
// asynchronously to the main input handler goroutine. This allows long-running
|
|
|
|
// operations to run concurrently (and one at a time) while still responding
|
|
|
|
// to the majority of normal requests which can be answered quickly.
|
2014-07-02 16:45:17 +02:00
|
|
|
var wsAsyncHandlers = map[string]struct{}{
|
2016-02-25 17:47:46 +01:00
|
|
|
"rescan": {},
|
2014-02-19 00:23:33 +01:00
|
|
|
}
|
2013-12-31 20:15:44 +01:00
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
// WebsocketHandler handles a new websocket client by creating a new wsClient,
|
|
|
|
// starting it, and blocking until the connection closes. Since it blocks, it
|
|
|
|
// must be run in a separate goroutine. It should be invoked from the websocket
|
|
|
|
// server handler which runs each new connection in a new goroutine thereby
|
|
|
|
// satisfying the requirement.
|
|
|
|
func (s *rpcServer) WebsocketHandler(conn *websocket.Conn, remoteAddr string,
|
2015-03-30 19:45:31 +02:00
|
|
|
authenticated bool, isAdmin bool) {
|
2013-12-31 20:15:44 +01:00
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
// Clear the read deadline that was set before the websocket hijacked
|
|
|
|
// the connection.
|
|
|
|
conn.SetReadDeadline(timeZeroVal)
|
|
|
|
|
|
|
|
// Limit max number of websocket clients.
|
|
|
|
rpcsLog.Infof("New websocket client %s", remoteAddr)
|
2014-02-19 04:05:42 +01:00
|
|
|
if s.ntfnMgr.NumClients()+1 > cfg.RPCMaxWebsockets {
|
2014-02-19 00:23:33 +01:00
|
|
|
rpcsLog.Infof("Max websocket clients exceeded [%d] - "+
|
2014-02-19 04:05:42 +01:00
|
|
|
"disconnecting client %s", cfg.RPCMaxWebsockets,
|
2014-02-19 00:23:33 +01:00
|
|
|
remoteAddr)
|
|
|
|
conn.Close()
|
|
|
|
return
|
|
|
|
}
|
2013-12-31 20:15:44 +01:00
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
// Create a new websocket client to handle the new websocket connection
|
|
|
|
// and wait for it to shutdown. Once it has shutdown (and hence
|
|
|
|
// disconnected), remove it and any notifications it registered for.
|
2015-09-15 20:03:48 +02:00
|
|
|
client, err := newWebsocketClient(s, conn, remoteAddr, authenticated, isAdmin)
|
|
|
|
if err != nil {
|
|
|
|
rpcsLog.Errorf("Failed to serve client %s: %v", remoteAddr, err)
|
|
|
|
conn.Close()
|
|
|
|
return
|
|
|
|
}
|
2014-02-19 00:23:33 +01:00
|
|
|
s.ntfnMgr.AddClient(client)
|
|
|
|
client.Start()
|
|
|
|
client.WaitForShutdown()
|
|
|
|
s.ntfnMgr.RemoveClient(client)
|
|
|
|
rpcsLog.Infof("Disconnected websocket client %s", remoteAddr)
|
|
|
|
}
|
2013-12-31 20:15:44 +01:00
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
// wsNotificationManager is a connection and notification manager used for
|
|
|
|
// websockets. It allows websocket clients to register for notifications they
|
|
|
|
// are interested in. When an event happens elsewhere in the code such as
|
|
|
|
// transactions being added to the memory pool or block connects/disconnects,
|
|
|
|
// the notification manager is provided with the relevant details needed to
|
|
|
|
// figure out which websocket clients need to be notified based on what they
|
|
|
|
// have registered for and notifies them accordingly. It is also used to keep
|
|
|
|
// track of all connected websocket clients.
|
|
|
|
type wsNotificationManager struct {
|
|
|
|
// server is the RPC server the notification manager is associated with.
|
|
|
|
server *rpcServer
|
|
|
|
|
2014-03-04 17:15:25 +01:00
|
|
|
// queueNotification queues a notification for handling.
|
|
|
|
queueNotification chan interface{}
|
|
|
|
|
|
|
|
// notificationMsgs feeds notificationHandler with notifications
|
|
|
|
// and client (un)registeration requests from a queue as well as
|
|
|
|
// registeration and unregisteration requests from clients.
|
|
|
|
notificationMsgs chan interface{}
|
|
|
|
|
|
|
|
// Access channel for current number of connected clients.
|
|
|
|
numClients chan int
|
|
|
|
|
|
|
|
// Shutdown handling
|
|
|
|
wg sync.WaitGroup
|
|
|
|
quit chan struct{}
|
|
|
|
}
|
|
|
|
|
|
|
|
// queueHandler manages a queue of empty interfaces, reading from in and
|
|
|
|
// sending the oldest unsent to out. This handler stops when either of the
|
|
|
|
// in or quit channels are closed, and closes out before returning, without
|
|
|
|
// waiting to send any variables still remaining in the queue.
|
|
|
|
func queueHandler(in <-chan interface{}, out chan<- interface{}, quit <-chan struct{}) {
|
|
|
|
var q []interface{}
|
|
|
|
var dequeue chan<- interface{}
|
|
|
|
skipQueue := out
|
|
|
|
var next interface{}
|
|
|
|
out:
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case n, ok := <-in:
|
|
|
|
if !ok {
|
|
|
|
// Sender closed input channel.
|
|
|
|
break out
|
|
|
|
}
|
|
|
|
|
|
|
|
// Either send to out immediately if skipQueue is
|
|
|
|
// non-nil (queue is empty) and reader is ready,
|
|
|
|
// or append to the queue and send later.
|
|
|
|
select {
|
|
|
|
case skipQueue <- n:
|
|
|
|
default:
|
|
|
|
q = append(q, n)
|
|
|
|
dequeue = out
|
|
|
|
skipQueue = nil
|
|
|
|
next = q[0]
|
|
|
|
}
|
|
|
|
|
|
|
|
case dequeue <- next:
|
|
|
|
copy(q, q[1:])
|
|
|
|
q[len(q)-1] = nil // avoid leak
|
|
|
|
q = q[:len(q)-1]
|
|
|
|
if len(q) == 0 {
|
|
|
|
dequeue = nil
|
|
|
|
skipQueue = out
|
2014-07-25 15:20:58 +02:00
|
|
|
} else {
|
|
|
|
next = q[0]
|
2014-03-04 17:15:25 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
case <-quit:
|
|
|
|
break out
|
|
|
|
}
|
|
|
|
}
|
|
|
|
close(out)
|
|
|
|
}
|
|
|
|
|
|
|
|
// queueHandler maintains a queue of notifications and notification handler
|
|
|
|
// control messages.
|
|
|
|
func (m *wsNotificationManager) queueHandler() {
|
|
|
|
queueHandler(m.queueNotification, m.notificationMsgs, m.quit)
|
|
|
|
m.wg.Done()
|
|
|
|
}
|
|
|
|
|
|
|
|
// NotifyBlockConnected passes a block newly-connected to the best chain
|
|
|
|
// to the notification manager for block and transaction notification
|
|
|
|
// processing.
|
|
|
|
func (m *wsNotificationManager) NotifyBlockConnected(block *btcutil.Block) {
|
2014-03-22 00:07:36 +01:00
|
|
|
// As NotifyBlockConnected will be called by the block manager
|
|
|
|
// and the RPC server may no longer be running, use a select
|
2016-02-25 18:17:12 +01:00
|
|
|
// statement to unblock enqueuing the notification once the RPC
|
2014-03-22 00:07:36 +01:00
|
|
|
// server has begun shutting down.
|
|
|
|
select {
|
|
|
|
case m.queueNotification <- (*notificationBlockConnected)(block):
|
|
|
|
case <-m.quit:
|
|
|
|
}
|
2014-03-04 17:15:25 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// NotifyBlockDisconnected passes a block disconnected from the best chain
|
|
|
|
// to the notification manager for block notification processing.
|
|
|
|
func (m *wsNotificationManager) NotifyBlockDisconnected(block *btcutil.Block) {
|
2014-03-22 00:07:36 +01:00
|
|
|
// As NotifyBlockDisconnected will be called by the block manager
|
|
|
|
// and the RPC server may no longer be running, use a select
|
2016-02-25 18:17:12 +01:00
|
|
|
// statement to unblock enqueuing the notification once the RPC
|
2014-03-22 00:07:36 +01:00
|
|
|
// server has begun shutting down.
|
|
|
|
select {
|
|
|
|
case m.queueNotification <- (*notificationBlockDisconnected)(block):
|
|
|
|
case <-m.quit:
|
|
|
|
}
|
2014-03-04 17:15:25 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// NotifyMempoolTx passes a transaction accepted by mempool to the
|
|
|
|
// notification manager for transaction notification processing. If
|
|
|
|
// isNew is true, the tx is is a new transaction, rather than one
|
|
|
|
// added to the mempool during a reorg.
|
|
|
|
func (m *wsNotificationManager) NotifyMempoolTx(tx *btcutil.Tx, isNew bool) {
|
2014-03-22 00:07:36 +01:00
|
|
|
n := ¬ificationTxAcceptedByMempool{
|
2014-03-04 17:15:25 +01:00
|
|
|
isNew: isNew,
|
|
|
|
tx: tx,
|
|
|
|
}
|
2014-03-22 00:07:36 +01:00
|
|
|
|
|
|
|
// As NotifyMempoolTx will be called by mempool and the RPC server
|
|
|
|
// may no longer be running, use a select statement to unblock
|
2016-02-25 18:17:12 +01:00
|
|
|
// enqueuing the notification once the RPC server has begun
|
2014-03-22 00:07:36 +01:00
|
|
|
// shutting down.
|
|
|
|
select {
|
|
|
|
case m.queueNotification <- n:
|
|
|
|
case <-m.quit:
|
|
|
|
}
|
2014-03-04 17:15:25 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// Notification types
|
|
|
|
type notificationBlockConnected btcutil.Block
|
|
|
|
type notificationBlockDisconnected btcutil.Block
|
|
|
|
type notificationTxAcceptedByMempool struct {
|
|
|
|
isNew bool
|
|
|
|
tx *btcutil.Tx
|
|
|
|
}
|
|
|
|
|
|
|
|
// Notification control requests
|
|
|
|
type notificationRegisterClient wsClient
|
|
|
|
type notificationUnregisterClient wsClient
|
|
|
|
type notificationRegisterBlocks wsClient
|
|
|
|
type notificationUnregisterBlocks wsClient
|
|
|
|
type notificationRegisterNewMempoolTxs wsClient
|
|
|
|
type notificationUnregisterNewMempoolTxs wsClient
|
|
|
|
type notificationRegisterSpent struct {
|
|
|
|
wsc *wsClient
|
2015-02-19 20:51:44 +01:00
|
|
|
ops []*wire.OutPoint
|
2014-03-04 17:15:25 +01:00
|
|
|
}
|
|
|
|
type notificationUnregisterSpent struct {
|
|
|
|
wsc *wsClient
|
2015-02-05 22:16:39 +01:00
|
|
|
op *wire.OutPoint
|
2014-03-04 17:15:25 +01:00
|
|
|
}
|
|
|
|
type notificationRegisterAddr struct {
|
2015-02-19 20:51:44 +01:00
|
|
|
wsc *wsClient
|
|
|
|
addrs []string
|
2014-03-04 17:15:25 +01:00
|
|
|
}
|
|
|
|
type notificationUnregisterAddr struct {
|
|
|
|
wsc *wsClient
|
|
|
|
addr string
|
|
|
|
}
|
|
|
|
|
|
|
|
// notificationHandler reads notifications and control messages from the queue
|
|
|
|
// handler and processes one at a time.
|
|
|
|
func (m *wsNotificationManager) notificationHandler() {
|
2014-02-19 00:23:33 +01:00
|
|
|
// clients is a map of all currently connected websocket clients.
|
2014-07-02 17:31:10 +02:00
|
|
|
clients := make(map[chan struct{}]*wsClient)
|
2014-02-19 00:23:33 +01:00
|
|
|
|
|
|
|
// Maps used to hold lists of websocket clients to be notified on
|
|
|
|
// certain events. Each websocket client also keeps maps for the events
|
|
|
|
// which have multiple triggers to make removal from these lists on
|
|
|
|
// connection close less horrendously expensive.
|
2014-03-04 17:15:25 +01:00
|
|
|
//
|
|
|
|
// Where possible, the quit channel is used as the unique id for a client
|
|
|
|
// since it is quite a bit more efficient than using the entire struct.
|
2014-07-02 17:31:10 +02:00
|
|
|
blockNotifications := make(map[chan struct{}]*wsClient)
|
|
|
|
txNotifications := make(map[chan struct{}]*wsClient)
|
2015-02-05 22:16:39 +01:00
|
|
|
watchedOutPoints := make(map[wire.OutPoint]map[chan struct{}]*wsClient)
|
2014-07-02 17:31:10 +02:00
|
|
|
watchedAddrs := make(map[string]map[chan struct{}]*wsClient)
|
2014-03-04 17:15:25 +01:00
|
|
|
|
|
|
|
out:
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case n, ok := <-m.notificationMsgs:
|
|
|
|
if !ok {
|
|
|
|
// queueHandler quit.
|
|
|
|
break out
|
|
|
|
}
|
|
|
|
switch n := n.(type) {
|
|
|
|
case *notificationBlockConnected:
|
|
|
|
block := (*btcutil.Block)(n)
|
|
|
|
|
|
|
|
// Skip iterating through all txs if no
|
|
|
|
// tx notification requests exist.
|
2015-06-18 04:19:51 +02:00
|
|
|
if len(watchedOutPoints) != 0 || len(watchedAddrs) != 0 {
|
|
|
|
for _, tx := range block.Transactions() {
|
|
|
|
m.notifyForTx(watchedOutPoints,
|
|
|
|
watchedAddrs, tx, block)
|
|
|
|
}
|
2014-03-04 17:15:25 +01:00
|
|
|
}
|
|
|
|
|
2015-06-18 04:19:51 +02:00
|
|
|
if len(blockNotifications) != 0 {
|
|
|
|
m.notifyBlockConnected(blockNotifications,
|
|
|
|
block)
|
2014-03-04 17:15:25 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
case *notificationBlockDisconnected:
|
|
|
|
m.notifyBlockDisconnected(blockNotifications,
|
|
|
|
(*btcutil.Block)(n))
|
|
|
|
|
|
|
|
case *notificationTxAcceptedByMempool:
|
|
|
|
if n.isNew && len(txNotifications) != 0 {
|
|
|
|
m.notifyForNewTx(txNotifications, n.tx)
|
|
|
|
}
|
|
|
|
m.notifyForTx(watchedOutPoints, watchedAddrs, n.tx, nil)
|
|
|
|
|
|
|
|
case *notificationRegisterBlocks:
|
|
|
|
wsc := (*wsClient)(n)
|
|
|
|
blockNotifications[wsc.quit] = wsc
|
|
|
|
|
2014-03-05 03:36:48 +01:00
|
|
|
case *notificationUnregisterBlocks:
|
|
|
|
wsc := (*wsClient)(n)
|
|
|
|
delete(blockNotifications, wsc.quit)
|
|
|
|
|
2014-03-04 17:15:25 +01:00
|
|
|
case *notificationRegisterClient:
|
|
|
|
wsc := (*wsClient)(n)
|
|
|
|
clients[wsc.quit] = wsc
|
|
|
|
|
|
|
|
case *notificationUnregisterClient:
|
|
|
|
wsc := (*wsClient)(n)
|
|
|
|
// Remove any requests made by the client as well as
|
|
|
|
// the client itself.
|
|
|
|
delete(blockNotifications, wsc.quit)
|
|
|
|
delete(txNotifications, wsc.quit)
|
|
|
|
for k := range wsc.spentRequests {
|
|
|
|
op := k
|
|
|
|
m.removeSpentRequest(watchedOutPoints, wsc, &op)
|
|
|
|
}
|
|
|
|
for addr := range wsc.addrRequests {
|
|
|
|
m.removeAddrRequest(watchedAddrs, wsc, addr)
|
|
|
|
}
|
|
|
|
delete(clients, wsc.quit)
|
|
|
|
|
|
|
|
case *notificationRegisterSpent:
|
2015-02-19 20:51:44 +01:00
|
|
|
m.addSpentRequests(watchedOutPoints, n.wsc, n.ops)
|
2014-03-04 17:15:25 +01:00
|
|
|
|
|
|
|
case *notificationUnregisterSpent:
|
|
|
|
m.removeSpentRequest(watchedOutPoints, n.wsc, n.op)
|
|
|
|
|
|
|
|
case *notificationRegisterAddr:
|
2015-02-19 20:51:44 +01:00
|
|
|
m.addAddrRequests(watchedAddrs, n.wsc, n.addrs)
|
2014-03-04 17:15:25 +01:00
|
|
|
|
|
|
|
case *notificationUnregisterAddr:
|
|
|
|
m.removeAddrRequest(watchedAddrs, n.wsc, n.addr)
|
|
|
|
|
2014-03-05 03:36:48 +01:00
|
|
|
case *notificationRegisterNewMempoolTxs:
|
|
|
|
wsc := (*wsClient)(n)
|
|
|
|
txNotifications[wsc.quit] = wsc
|
|
|
|
|
|
|
|
case *notificationUnregisterNewMempoolTxs:
|
|
|
|
wsc := (*wsClient)(n)
|
|
|
|
delete(txNotifications, wsc.quit)
|
|
|
|
|
2014-03-04 17:15:25 +01:00
|
|
|
default:
|
|
|
|
rpcsLog.Warn("Unhandled notification type")
|
|
|
|
}
|
|
|
|
|
|
|
|
case m.numClients <- len(clients):
|
|
|
|
|
|
|
|
case <-m.quit:
|
|
|
|
// RPC server shutting down.
|
|
|
|
break out
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, c := range clients {
|
|
|
|
c.Disconnect()
|
|
|
|
}
|
|
|
|
m.wg.Done()
|
2013-12-31 20:15:44 +01:00
|
|
|
}
|
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
// NumClients returns the number of clients actively being served.
|
2014-03-22 00:07:36 +01:00
|
|
|
func (m *wsNotificationManager) NumClients() (n int) {
|
|
|
|
select {
|
|
|
|
case n = <-m.numClients:
|
|
|
|
case <-m.quit: // Use default n (0) if server has shut down.
|
|
|
|
}
|
|
|
|
return
|
2014-01-17 22:00:46 +01:00
|
|
|
}
|
|
|
|
|
2014-03-04 17:15:25 +01:00
|
|
|
// RegisterBlockUpdates requests block update notifications to the passed
|
2014-02-19 00:23:33 +01:00
|
|
|
// websocket client.
|
2014-03-04 17:15:25 +01:00
|
|
|
func (m *wsNotificationManager) RegisterBlockUpdates(wsc *wsClient) {
|
|
|
|
m.queueNotification <- (*notificationRegisterBlocks)(wsc)
|
2014-02-08 23:15:17 +01:00
|
|
|
}
|
|
|
|
|
2014-03-04 17:15:25 +01:00
|
|
|
// UnregisterBlockUpdates removes block update notifications for the passed
|
2014-02-19 00:23:33 +01:00
|
|
|
// websocket client.
|
2014-03-04 17:15:25 +01:00
|
|
|
func (m *wsNotificationManager) UnregisterBlockUpdates(wsc *wsClient) {
|
|
|
|
m.queueNotification <- (*notificationUnregisterBlocks)(wsc)
|
2014-02-19 00:23:33 +01:00
|
|
|
}
|
2013-12-31 20:15:44 +01:00
|
|
|
|
2014-03-04 17:15:25 +01:00
|
|
|
// notifyBlockConnected notifies websocket clients that have registered for
|
2014-02-19 00:23:33 +01:00
|
|
|
// block updates when a block is connected to the main chain.
|
2014-07-02 17:31:10 +02:00
|
|
|
func (*wsNotificationManager) notifyBlockConnected(clients map[chan struct{}]*wsClient,
|
2014-03-04 17:15:25 +01:00
|
|
|
block *btcutil.Block) {
|
2014-02-12 04:39:11 +01:00
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
// Notify interested websocket clients about the connected block.
|
2015-04-17 07:44:15 +02:00
|
|
|
ntfn := btcjson.NewBlockConnectedNtfn(block.Sha().String(),
|
2015-06-18 17:49:45 +02:00
|
|
|
int32(block.Height()), block.MsgBlock().Header.Timestamp.Unix())
|
2015-02-21 05:34:57 +01:00
|
|
|
marshalledJSON, err := btcjson.MarshalCmd(nil, ntfn)
|
2014-02-19 00:23:33 +01:00
|
|
|
if err != nil {
|
|
|
|
rpcsLog.Error("Failed to marshal block connected notification: "+
|
|
|
|
"%v", err)
|
|
|
|
return
|
2013-12-31 20:15:44 +01:00
|
|
|
}
|
2014-03-04 17:15:25 +01:00
|
|
|
for _, wsc := range clients {
|
2014-02-19 00:23:33 +01:00
|
|
|
wsc.QueueNotification(marshalledJSON)
|
2013-12-31 20:15:44 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-03-04 17:15:25 +01:00
|
|
|
// notifyBlockDisconnected notifies websocket clients that have registered for
|
2014-02-19 00:23:33 +01:00
|
|
|
// block updates when a block is disconnected from the main chain (due to a
|
|
|
|
// reorganize).
|
2014-07-02 17:31:10 +02:00
|
|
|
func (*wsNotificationManager) notifyBlockDisconnected(clients map[chan struct{}]*wsClient, block *btcutil.Block) {
|
2014-03-04 17:15:25 +01:00
|
|
|
// Skip notification creation if no clients have requested block
|
|
|
|
// connected/disconnected notifications.
|
|
|
|
if len(clients) == 0 {
|
2014-02-12 04:39:11 +01:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
// Notify interested websocket clients about the disconnected block.
|
2015-04-17 07:44:15 +02:00
|
|
|
ntfn := btcjson.NewBlockDisconnectedNtfn(block.Sha().String(),
|
2015-06-18 17:49:45 +02:00
|
|
|
int32(block.Height()), block.MsgBlock().Header.Timestamp.Unix())
|
2015-02-21 05:34:57 +01:00
|
|
|
marshalledJSON, err := btcjson.MarshalCmd(nil, ntfn)
|
2014-02-19 00:23:33 +01:00
|
|
|
if err != nil {
|
|
|
|
rpcsLog.Error("Failed to marshal block disconnected "+
|
|
|
|
"notification: %v", err)
|
|
|
|
return
|
2013-12-31 20:15:44 +01:00
|
|
|
}
|
2014-03-04 17:15:25 +01:00
|
|
|
for _, wsc := range clients {
|
2014-02-19 00:23:33 +01:00
|
|
|
wsc.QueueNotification(marshalledJSON)
|
2013-12-31 20:15:44 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-03-04 17:15:25 +01:00
|
|
|
// RegisterNewMempoolTxsUpdates requests notifications to the passed websocket
|
|
|
|
// client when new transactions are added to the memory pool.
|
|
|
|
func (m *wsNotificationManager) RegisterNewMempoolTxsUpdates(wsc *wsClient) {
|
|
|
|
m.queueNotification <- (*notificationRegisterNewMempoolTxs)(wsc)
|
2013-12-31 20:15:44 +01:00
|
|
|
}
|
|
|
|
|
2014-03-04 17:15:25 +01:00
|
|
|
// UnregisterNewMempoolTxsUpdates removes notifications to the passed websocket
|
|
|
|
// client when new transaction are added to the memory pool.
|
|
|
|
func (m *wsNotificationManager) UnregisterNewMempoolTxsUpdates(wsc *wsClient) {
|
|
|
|
m.queueNotification <- (*notificationUnregisterNewMempoolTxs)(wsc)
|
2014-02-19 00:23:33 +01:00
|
|
|
}
|
2013-12-31 20:15:44 +01:00
|
|
|
|
2014-09-08 21:19:47 +02:00
|
|
|
// notifyForNewTx notifies websocket clients that have registered for updates
|
2014-02-19 00:23:33 +01:00
|
|
|
// when a new transaction is added to the memory pool.
|
2014-07-02 17:31:10 +02:00
|
|
|
func (m *wsNotificationManager) notifyForNewTx(clients map[chan struct{}]*wsClient, tx *btcutil.Tx) {
|
2014-03-04 17:15:25 +01:00
|
|
|
txShaStr := tx.Sha().String()
|
2014-02-19 00:23:33 +01:00
|
|
|
mtx := tx.MsgTx()
|
|
|
|
|
|
|
|
var amount int64
|
|
|
|
for _, txOut := range mtx.TxOut {
|
|
|
|
amount += txOut.Value
|
2013-12-31 20:15:44 +01:00
|
|
|
}
|
|
|
|
|
2015-02-21 05:34:57 +01:00
|
|
|
ntfn := btcjson.NewTxAcceptedNtfn(txShaStr, btcutil.Amount(amount).ToBTC())
|
|
|
|
marshalledJSON, err := btcjson.MarshalCmd(nil, ntfn)
|
2014-02-19 00:23:33 +01:00
|
|
|
if err != nil {
|
|
|
|
rpcsLog.Errorf("Failed to marshal tx notification: %s", err.Error())
|
|
|
|
return
|
2013-12-31 20:15:44 +01:00
|
|
|
}
|
|
|
|
|
2015-02-21 05:34:57 +01:00
|
|
|
var verboseNtfn *btcjson.TxAcceptedVerboseNtfn
|
2014-02-19 00:23:33 +01:00
|
|
|
var marshalledJSONVerbose []byte
|
2014-03-04 17:15:25 +01:00
|
|
|
for _, wsc := range clients {
|
2014-02-19 00:23:33 +01:00
|
|
|
if wsc.verboseTxUpdates {
|
2015-02-21 05:34:57 +01:00
|
|
|
if marshalledJSONVerbose != nil {
|
|
|
|
wsc.QueueNotification(marshalledJSONVerbose)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
net := m.server.server.chainParams
|
2015-07-28 21:55:35 +02:00
|
|
|
rawTx, err := createTxRawResult(net, mtx, txShaStr, nil,
|
|
|
|
"", 0, 0)
|
2015-02-21 05:34:57 +01:00
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
2014-02-19 00:23:33 +01:00
|
|
|
|
2015-02-21 05:34:57 +01:00
|
|
|
verboseNtfn = btcjson.NewTxAcceptedVerboseNtfn(*rawTx)
|
|
|
|
marshalledJSONVerbose, err = btcjson.MarshalCmd(nil,
|
|
|
|
verboseNtfn)
|
|
|
|
if err != nil {
|
|
|
|
rpcsLog.Errorf("Failed to marshal verbose tx "+
|
|
|
|
"notification: %s", err.Error())
|
|
|
|
return
|
2014-02-19 00:23:33 +01:00
|
|
|
}
|
|
|
|
wsc.QueueNotification(marshalledJSONVerbose)
|
|
|
|
} else {
|
|
|
|
wsc.QueueNotification(marshalledJSON)
|
|
|
|
}
|
2013-12-31 20:15:44 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-02-19 20:51:44 +01:00
|
|
|
// RegisterSpentRequests requests a notification when each of the passed
|
|
|
|
// outpoints is confirmed spent (contained in a block connected to the main
|
|
|
|
// chain) for the passed websocket client. The request is automatically
|
|
|
|
// removed once the notification has been sent.
|
|
|
|
func (m *wsNotificationManager) RegisterSpentRequests(wsc *wsClient, ops []*wire.OutPoint) {
|
2014-03-04 17:15:25 +01:00
|
|
|
m.queueNotification <- ¬ificationRegisterSpent{
|
|
|
|
wsc: wsc,
|
2015-02-19 20:51:44 +01:00
|
|
|
ops: ops,
|
2014-03-04 17:15:25 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-02-19 20:51:44 +01:00
|
|
|
// addSpentRequests modifies a map of watched outpoints to sets of websocket
|
|
|
|
// clients to add a new request watch all of the outpoints in ops and create
|
|
|
|
// and send a notification when spent to the websocket client wsc.
|
|
|
|
func (*wsNotificationManager) addSpentRequests(opMap map[wire.OutPoint]map[chan struct{}]*wsClient,
|
|
|
|
wsc *wsClient, ops []*wire.OutPoint) {
|
2014-03-04 17:15:25 +01:00
|
|
|
|
2015-02-19 20:51:44 +01:00
|
|
|
for _, op := range ops {
|
|
|
|
// Track the request in the client as well so it can be quickly
|
|
|
|
// be removed on disconnect.
|
|
|
|
wsc.spentRequests[*op] = struct{}{}
|
2014-02-19 00:23:33 +01:00
|
|
|
|
2015-02-19 20:51:44 +01:00
|
|
|
// Add the client to the list to notify when the outpoint is seen.
|
|
|
|
// Create the list as needed.
|
|
|
|
cmap, ok := opMap[*op]
|
|
|
|
if !ok {
|
|
|
|
cmap = make(map[chan struct{}]*wsClient)
|
|
|
|
opMap[*op] = cmap
|
|
|
|
}
|
|
|
|
cmap[wsc.quit] = wsc
|
2014-02-19 00:23:33 +01:00
|
|
|
}
|
2013-12-31 20:15:44 +01:00
|
|
|
}
|
|
|
|
|
2014-03-04 17:15:25 +01:00
|
|
|
// UnregisterSpentRequest removes a request from the passed websocket client
|
|
|
|
// to be notified when the passed outpoint is confirmed spent (contained in a
|
|
|
|
// block connected to the main chain).
|
2015-02-05 22:16:39 +01:00
|
|
|
func (m *wsNotificationManager) UnregisterSpentRequest(wsc *wsClient, op *wire.OutPoint) {
|
2014-03-04 17:15:25 +01:00
|
|
|
m.queueNotification <- ¬ificationUnregisterSpent{
|
|
|
|
wsc: wsc,
|
|
|
|
op: op,
|
|
|
|
}
|
2014-02-24 15:10:59 +01:00
|
|
|
}
|
|
|
|
|
2014-03-04 17:15:25 +01:00
|
|
|
// removeSpentRequest modifies a map of watched outpoints to remove the
|
|
|
|
// websocket client wsc from the set of clients to be notified when a
|
|
|
|
// watched outpoint is spent. If wsc is the last client, the outpoint
|
|
|
|
// key is removed from the map.
|
2015-02-05 22:16:39 +01:00
|
|
|
func (*wsNotificationManager) removeSpentRequest(ops map[wire.OutPoint]map[chan struct{}]*wsClient,
|
|
|
|
wsc *wsClient, op *wire.OutPoint) {
|
2014-03-04 17:15:25 +01:00
|
|
|
|
2014-02-19 16:13:49 +01:00
|
|
|
// Remove the request tracking from the client.
|
|
|
|
delete(wsc.spentRequests, *op)
|
|
|
|
|
|
|
|
// Remove the client from the list to notify.
|
2014-03-04 17:15:25 +01:00
|
|
|
notifyMap, ok := ops[*op]
|
2014-02-12 04:39:11 +01:00
|
|
|
if !ok {
|
2014-02-19 00:23:33 +01:00
|
|
|
rpcsLog.Warnf("Attempt to remove nonexistent spent request "+
|
|
|
|
"for websocket client %s", wsc.addr)
|
2014-02-12 04:39:11 +01:00
|
|
|
return
|
|
|
|
}
|
2014-02-19 00:23:33 +01:00
|
|
|
delete(notifyMap, wsc.quit)
|
|
|
|
|
2014-03-04 17:15:25 +01:00
|
|
|
// Remove the map entry altogether if there are
|
|
|
|
// no more clients interested in it.
|
2014-02-19 00:23:33 +01:00
|
|
|
if len(notifyMap) == 0 {
|
2014-03-04 17:15:25 +01:00
|
|
|
delete(ops, *op)
|
2014-02-19 00:23:33 +01:00
|
|
|
}
|
2013-12-31 20:15:44 +01:00
|
|
|
}
|
|
|
|
|
2014-02-24 15:10:59 +01:00
|
|
|
// txHexString returns the serialized transaction encoded in hexadecimal.
|
|
|
|
func txHexString(tx *btcutil.Tx) string {
|
2014-03-20 20:33:09 +01:00
|
|
|
buf := bytes.NewBuffer(make([]byte, 0, tx.MsgTx().SerializeSize()))
|
2014-02-24 15:10:59 +01:00
|
|
|
// Ignore Serialize's error, as writing to a bytes.buffer cannot fail.
|
2014-03-20 20:33:09 +01:00
|
|
|
tx.MsgTx().Serialize(buf)
|
2014-02-24 15:10:59 +01:00
|
|
|
return hex.EncodeToString(buf.Bytes())
|
|
|
|
}
|
|
|
|
|
2014-03-04 17:15:25 +01:00
|
|
|
// blockDetails creates a BlockDetails struct to include in btcws notifications
|
|
|
|
// from a block and a transaction's block index.
|
2015-02-21 05:34:57 +01:00
|
|
|
func blockDetails(block *btcutil.Block, txIndex int) *btcjson.BlockDetails {
|
2014-03-04 17:15:25 +01:00
|
|
|
if block == nil {
|
|
|
|
return nil
|
|
|
|
}
|
2015-02-21 05:34:57 +01:00
|
|
|
return &btcjson.BlockDetails{
|
2014-03-04 17:15:25 +01:00
|
|
|
Height: int32(block.Height()),
|
2015-04-17 07:44:15 +02:00
|
|
|
Hash: block.Sha().String(),
|
2014-03-04 17:15:25 +01:00
|
|
|
Index: txIndex,
|
|
|
|
Time: block.MsgBlock().Header.Timestamp.Unix(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// newRedeemingTxNotification returns a new marshalled redeemingtx notification
|
|
|
|
// with the passed parameters.
|
|
|
|
func newRedeemingTxNotification(txHex string, index int, block *btcutil.Block) ([]byte, error) {
|
|
|
|
// Create and marshal the notification.
|
2015-02-27 01:35:46 +01:00
|
|
|
ntfn := btcjson.NewRedeemingTxNtfn(txHex, blockDetails(block, index))
|
2015-02-21 05:34:57 +01:00
|
|
|
return btcjson.MarshalCmd(nil, ntfn)
|
2014-03-04 17:15:25 +01:00
|
|
|
}
|
|
|
|
|
2014-02-24 15:10:59 +01:00
|
|
|
// notifyForTxOuts examines each transaction output, notifying interested
|
|
|
|
// websocket clients of the transaction if an output spends to a watched
|
|
|
|
// address. A spent notification request is automatically registered for
|
|
|
|
// the client for each matching output.
|
2015-02-05 22:16:39 +01:00
|
|
|
func (m *wsNotificationManager) notifyForTxOuts(ops map[wire.OutPoint]map[chan struct{}]*wsClient,
|
2014-07-02 17:31:10 +02:00
|
|
|
addrs map[string]map[chan struct{}]*wsClient, tx *btcutil.Tx, block *btcutil.Block) {
|
2014-03-04 17:15:25 +01:00
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
// Nothing to do if nobody is listening for address notifications.
|
2014-03-04 17:15:25 +01:00
|
|
|
if len(addrs) == 0 {
|
2014-02-19 00:23:33 +01:00
|
|
|
return
|
2014-01-17 20:04:57 +01:00
|
|
|
}
|
|
|
|
|
2014-02-24 15:10:59 +01:00
|
|
|
txHex := ""
|
2014-07-02 17:31:10 +02:00
|
|
|
wscNotified := make(map[chan struct{}]struct{})
|
2014-02-24 15:10:59 +01:00
|
|
|
for i, txOut := range tx.MsgTx().TxOut {
|
2015-01-30 19:14:33 +01:00
|
|
|
_, txAddrs, _, err := txscript.ExtractPkScriptAddrs(
|
2015-02-06 06:18:27 +01:00
|
|
|
txOut.PkScript, m.server.server.chainParams)
|
2014-02-19 00:23:33 +01:00
|
|
|
if err != nil {
|
|
|
|
continue
|
|
|
|
}
|
2014-01-22 21:10:04 +01:00
|
|
|
|
2014-03-04 17:15:25 +01:00
|
|
|
for _, txAddr := range txAddrs {
|
|
|
|
cmap, ok := addrs[txAddr.EncodeAddress()]
|
2014-02-19 00:23:33 +01:00
|
|
|
if !ok {
|
|
|
|
continue
|
|
|
|
}
|
2014-01-22 21:10:04 +01:00
|
|
|
|
2014-02-24 15:10:59 +01:00
|
|
|
if txHex == "" {
|
|
|
|
txHex = txHexString(tx)
|
2014-02-19 00:23:33 +01:00
|
|
|
}
|
2015-02-27 01:35:46 +01:00
|
|
|
ntfn := btcjson.NewRecvTxNtfn(txHex, blockDetails(block,
|
2015-02-21 05:34:57 +01:00
|
|
|
tx.Index()))
|
2014-02-08 23:15:17 +01:00
|
|
|
|
2015-02-21 05:34:57 +01:00
|
|
|
marshalledJSON, err := btcjson.MarshalCmd(nil, ntfn)
|
2014-02-19 00:23:33 +01:00
|
|
|
if err != nil {
|
|
|
|
rpcsLog.Errorf("Failed to marshal processedtx notification: %v", err)
|
2014-02-24 15:10:59 +01:00
|
|
|
continue
|
2014-02-19 00:23:33 +01:00
|
|
|
}
|
2014-02-08 23:15:17 +01:00
|
|
|
|
2015-02-19 20:51:44 +01:00
|
|
|
op := []*wire.OutPoint{wire.NewOutPoint(tx.Sha(), uint32(i))}
|
2014-02-24 15:10:59 +01:00
|
|
|
for wscQuit, wsc := range cmap {
|
2015-02-19 20:51:44 +01:00
|
|
|
m.addSpentRequests(ops, wsc, op)
|
2014-02-24 15:10:59 +01:00
|
|
|
|
2014-07-02 16:45:17 +02:00
|
|
|
if _, ok := wscNotified[wscQuit]; !ok {
|
|
|
|
wscNotified[wscQuit] = struct{}{}
|
2014-02-24 15:10:59 +01:00
|
|
|
wsc.QueueNotification(marshalledJSON)
|
|
|
|
}
|
2014-02-19 00:23:33 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2014-01-08 17:40:27 +01:00
|
|
|
|
2014-03-04 17:15:25 +01:00
|
|
|
// notifyForTx examines the inputs and outputs of the passed transaction,
|
2014-02-24 15:10:59 +01:00
|
|
|
// notifying websocket clients of outputs spending to a watched address
|
|
|
|
// and inputs spending a watched outpoint.
|
2015-02-05 22:16:39 +01:00
|
|
|
func (m *wsNotificationManager) notifyForTx(ops map[wire.OutPoint]map[chan struct{}]*wsClient,
|
2014-07-02 17:31:10 +02:00
|
|
|
addrs map[string]map[chan struct{}]*wsClient, tx *btcutil.Tx, block *btcutil.Block) {
|
2013-12-31 20:15:44 +01:00
|
|
|
|
2014-03-04 17:15:25 +01:00
|
|
|
if len(ops) != 0 {
|
|
|
|
m.notifyForTxIns(ops, tx, block)
|
|
|
|
}
|
|
|
|
if len(addrs) != 0 {
|
|
|
|
m.notifyForTxOuts(ops, addrs, tx, block)
|
|
|
|
}
|
2013-12-31 20:15:44 +01:00
|
|
|
}
|
|
|
|
|
2014-02-24 15:10:59 +01:00
|
|
|
// notifyForTxIns examines the inputs of the passed transaction and sends
|
|
|
|
// interested websocket clients a redeemingtx notification if any inputs
|
|
|
|
// spend a watched output. If block is non-nil, any matching spent
|
|
|
|
// requests are removed.
|
2015-02-05 22:16:39 +01:00
|
|
|
func (m *wsNotificationManager) notifyForTxIns(ops map[wire.OutPoint]map[chan struct{}]*wsClient,
|
2014-03-04 17:15:25 +01:00
|
|
|
tx *btcutil.Tx, block *btcutil.Block) {
|
|
|
|
|
|
|
|
// Nothing to do if nobody is watching outpoints.
|
|
|
|
if len(ops) == 0 {
|
2014-02-19 00:23:33 +01:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2014-02-24 15:10:59 +01:00
|
|
|
txHex := ""
|
2014-07-02 17:31:10 +02:00
|
|
|
wscNotified := make(map[chan struct{}]struct{})
|
2014-02-19 00:23:33 +01:00
|
|
|
for _, txIn := range tx.MsgTx().TxIn {
|
2014-10-01 17:34:30 +02:00
|
|
|
prevOut := &txIn.PreviousOutPoint
|
2014-03-04 17:15:25 +01:00
|
|
|
if cmap, ok := ops[*prevOut]; ok {
|
2014-02-24 15:10:59 +01:00
|
|
|
if txHex == "" {
|
|
|
|
txHex = txHexString(tx)
|
|
|
|
}
|
|
|
|
marshalledJSON, err := newRedeemingTxNotification(txHex, tx.Index(), block)
|
|
|
|
if err != nil {
|
|
|
|
rpcsLog.Warnf("Failed to marshal redeemingtx notification: %v", err)
|
2014-02-19 00:23:33 +01:00
|
|
|
continue
|
|
|
|
}
|
2014-02-24 15:10:59 +01:00
|
|
|
for wscQuit, wsc := range cmap {
|
|
|
|
if block != nil {
|
2014-03-04 17:15:25 +01:00
|
|
|
m.removeSpentRequest(ops, wsc, prevOut)
|
2014-02-24 15:10:59 +01:00
|
|
|
}
|
|
|
|
|
2014-07-02 16:45:17 +02:00
|
|
|
if _, ok := wscNotified[wscQuit]; !ok {
|
|
|
|
wscNotified[wscQuit] = struct{}{}
|
2014-02-24 15:10:59 +01:00
|
|
|
wsc.QueueNotification(marshalledJSON)
|
|
|
|
}
|
2014-02-19 00:23:33 +01:00
|
|
|
}
|
|
|
|
}
|
2013-12-31 20:15:44 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-02-19 20:51:44 +01:00
|
|
|
// RegisterTxOutAddressRequests requests notifications to the passed websocket
|
2014-03-04 17:15:25 +01:00
|
|
|
// client when a transaction output spends to the passed address.
|
2015-02-19 20:51:44 +01:00
|
|
|
func (m *wsNotificationManager) RegisterTxOutAddressRequests(wsc *wsClient, addrs []string) {
|
2014-03-04 17:15:25 +01:00
|
|
|
m.queueNotification <- ¬ificationRegisterAddr{
|
2015-02-19 20:51:44 +01:00
|
|
|
wsc: wsc,
|
|
|
|
addrs: addrs,
|
2014-02-24 15:10:59 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-02-19 20:51:44 +01:00
|
|
|
// addAddrRequests adds the websocket client wsc to the address to client set
|
|
|
|
// addrMap so wsc will be notified for any mempool or block transaction outputs
|
|
|
|
// spending to any of the addresses in addrs.
|
|
|
|
func (*wsNotificationManager) addAddrRequests(addrMap map[string]map[chan struct{}]*wsClient,
|
|
|
|
wsc *wsClient, addrs []string) {
|
2014-02-19 00:23:33 +01:00
|
|
|
|
2015-02-19 20:51:44 +01:00
|
|
|
for _, addr := range addrs {
|
|
|
|
// Track the request in the client as well so it can be quickly be
|
|
|
|
// removed on disconnect.
|
|
|
|
wsc.addrRequests[addr] = struct{}{}
|
2014-02-19 00:23:33 +01:00
|
|
|
|
2015-02-19 20:51:44 +01:00
|
|
|
// Add the client to the set of clients to notify when the
|
|
|
|
// outpoint is seen. Create map as needed.
|
|
|
|
cmap, ok := addrMap[addr]
|
|
|
|
if !ok {
|
|
|
|
cmap = make(map[chan struct{}]*wsClient)
|
|
|
|
addrMap[addr] = cmap
|
|
|
|
}
|
|
|
|
cmap[wsc.quit] = wsc
|
2014-02-19 00:23:33 +01:00
|
|
|
}
|
2014-01-17 22:00:46 +01:00
|
|
|
}
|
|
|
|
|
2014-03-04 17:15:25 +01:00
|
|
|
// UnregisterTxOutAddressRequest removes a request from the passed websocket
|
|
|
|
// client to be notified when a transaction spends to the passed address.
|
|
|
|
func (m *wsNotificationManager) UnregisterTxOutAddressRequest(wsc *wsClient, addr string) {
|
|
|
|
m.queueNotification <- ¬ificationUnregisterAddr{
|
|
|
|
wsc: wsc,
|
|
|
|
addr: addr,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// removeAddrRequest removes the websocket client wsc from the address to
|
|
|
|
// client set addrs so it will no longer receive notification updates for
|
|
|
|
// any transaction outputs send to addr.
|
2014-07-02 17:31:10 +02:00
|
|
|
func (*wsNotificationManager) removeAddrRequest(addrs map[string]map[chan struct{}]*wsClient,
|
2014-03-04 17:15:25 +01:00
|
|
|
wsc *wsClient, addr string) {
|
|
|
|
|
2014-02-19 16:13:49 +01:00
|
|
|
// Remove the request tracking from the client.
|
|
|
|
delete(wsc.addrRequests, addr)
|
|
|
|
|
|
|
|
// Remove the client from the list to notify.
|
2014-03-04 17:15:25 +01:00
|
|
|
cmap, ok := addrs[addr]
|
2013-12-31 21:39:17 +01:00
|
|
|
if !ok {
|
2014-02-19 00:23:33 +01:00
|
|
|
rpcsLog.Warnf("Attempt to remove nonexistent addr request "+
|
|
|
|
"<%s> for websocket client %s", addr, wsc.addr)
|
|
|
|
return
|
2013-12-31 21:39:17 +01:00
|
|
|
}
|
2014-03-04 17:15:25 +01:00
|
|
|
delete(cmap, wsc.quit)
|
2014-01-03 19:22:28 +01:00
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
// Remove the map entry altogether if there are no more clients
|
|
|
|
// interested in it.
|
2014-03-04 17:15:25 +01:00
|
|
|
if len(cmap) == 0 {
|
|
|
|
delete(addrs, addr)
|
2013-12-31 21:39:17 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
// AddClient adds the passed websocket client to the notification manager.
|
|
|
|
func (m *wsNotificationManager) AddClient(wsc *wsClient) {
|
2014-03-04 17:15:25 +01:00
|
|
|
m.queueNotification <- (*notificationRegisterClient)(wsc)
|
2013-12-31 21:39:17 +01:00
|
|
|
}
|
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
// RemoveClient removes the passed websocket client and all notifications
|
|
|
|
// registered for it.
|
|
|
|
func (m *wsNotificationManager) RemoveClient(wsc *wsClient) {
|
2014-03-04 17:31:44 +01:00
|
|
|
select {
|
|
|
|
case m.queueNotification <- (*notificationUnregisterClient)(wsc):
|
|
|
|
case <-m.quit:
|
|
|
|
}
|
2014-03-04 17:15:25 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// Start starts the goroutines required for the manager to queue and process
|
|
|
|
// websocket client notifications.
|
|
|
|
func (m *wsNotificationManager) Start() {
|
|
|
|
m.wg.Add(2)
|
|
|
|
go m.queueHandler()
|
|
|
|
go m.notificationHandler()
|
2014-02-19 00:23:33 +01:00
|
|
|
}
|
2013-12-31 20:15:44 +01:00
|
|
|
|
2014-03-04 17:15:25 +01:00
|
|
|
// WaitForShutdown blocks until all notification manager goroutines have
|
|
|
|
// finished.
|
|
|
|
func (m *wsNotificationManager) WaitForShutdown() {
|
|
|
|
m.wg.Wait()
|
|
|
|
}
|
|
|
|
|
|
|
|
// Shutdown shuts down the manager, stopping the notification queue and
|
|
|
|
// notification handler goroutines.
|
2014-02-19 00:23:33 +01:00
|
|
|
func (m *wsNotificationManager) Shutdown() {
|
2014-03-04 17:15:25 +01:00
|
|
|
close(m.quit)
|
2014-02-19 00:23:33 +01:00
|
|
|
}
|
2013-12-31 20:15:44 +01:00
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
// newWsNotificationManager returns a new notification manager ready for use.
|
|
|
|
// See wsNotificationManager for more details.
|
|
|
|
func newWsNotificationManager(server *rpcServer) *wsNotificationManager {
|
|
|
|
return &wsNotificationManager{
|
2014-03-04 17:15:25 +01:00
|
|
|
server: server,
|
|
|
|
queueNotification: make(chan interface{}),
|
|
|
|
notificationMsgs: make(chan interface{}),
|
|
|
|
numClients: make(chan int),
|
|
|
|
quit: make(chan struct{}),
|
2014-02-19 00:23:33 +01:00
|
|
|
}
|
|
|
|
}
|
2013-12-31 20:15:44 +01:00
|
|
|
|
2014-09-08 21:19:47 +02:00
|
|
|
// wsResponse houses a message to send to a connected websocket client as
|
2014-02-19 00:23:33 +01:00
|
|
|
// well as a channel to reply on when the message is sent.
|
|
|
|
type wsResponse struct {
|
|
|
|
msg []byte
|
|
|
|
doneChan chan bool
|
|
|
|
}
|
2014-01-14 21:59:31 +01:00
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
// wsClient provides an abstraction for handling a websocket client. The
|
|
|
|
// overall data flow is split into 3 main goroutines, a possible 4th goroutine
|
|
|
|
// for long-running operations (only started if request is made), and a
|
|
|
|
// websocket manager which is used to allow things such as broadcasting
|
|
|
|
// requested notifications to all connected websocket clients. Inbound
|
|
|
|
// messages are read via the inHandler goroutine and generally dispatched to
|
|
|
|
// their own handler. However, certain potentially long-running operations such
|
|
|
|
// as rescans, are sent to the asyncHander goroutine and are limited to one at a
|
|
|
|
// time. There are two outbound message types - one for responding to client
|
|
|
|
// requests and another for async notifications. Responses to client requests
|
|
|
|
// use SendMessage which employs a buffered channel thereby limiting the number
|
|
|
|
// of outstanding requests that can be made. Notifications are sent via
|
|
|
|
// QueueNotification which implements a queue via notificationQueueHandler to
|
|
|
|
// ensure sending notifications from other subsystems can't block. Ultimately,
|
|
|
|
// all messages are sent via the outHandler.
|
|
|
|
type wsClient struct {
|
2014-02-25 06:57:36 +01:00
|
|
|
sync.Mutex
|
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
// server is the RPC server that is servicing the client.
|
|
|
|
server *rpcServer
|
|
|
|
|
|
|
|
// conn is the underlying websocket connection.
|
|
|
|
conn *websocket.Conn
|
|
|
|
|
2014-02-25 06:57:36 +01:00
|
|
|
// disconnected indicated whether or not the websocket client is
|
|
|
|
// disconnected.
|
|
|
|
disconnected bool
|
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
// addr is the remote address of the client.
|
|
|
|
addr string
|
2014-01-14 21:59:31 +01:00
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
// authenticated specifies whether a client has been authenticated
|
|
|
|
// and therefore is allowed to communicated over the websocket.
|
|
|
|
authenticated bool
|
2014-01-14 21:59:31 +01:00
|
|
|
|
2015-03-30 19:45:31 +02:00
|
|
|
// isAdmin specifies whether a client may change the state of the server;
|
|
|
|
// false means its access is only to the limited set of RPC calls.
|
|
|
|
isAdmin bool
|
|
|
|
|
2015-09-15 20:03:48 +02:00
|
|
|
// sessionID is a random ID generated for each client when connected.
|
|
|
|
// These IDs may be queried by a client using the session RPC. A change
|
|
|
|
// to the session ID indicates that the client reconnected.
|
|
|
|
sessionID uint64
|
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
// verboseTxUpdates specifies whether a client has requested verbose
|
|
|
|
// information about all new transactions.
|
|
|
|
verboseTxUpdates bool
|
2014-01-14 21:59:31 +01:00
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
// addrRequests is a set of addresses the caller has requested to be
|
|
|
|
// notified about. It is maintained here so all requests can be removed
|
|
|
|
// when a wallet disconnects. Owned by the notification manager.
|
|
|
|
addrRequests map[string]struct{}
|
2014-01-14 21:59:31 +01:00
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
// spentRequests is a set of unspent Outpoints a wallet has requested
|
|
|
|
// notifications for when they are spent by a processed transaction.
|
|
|
|
// Owned by the notification manager.
|
2015-02-05 22:16:39 +01:00
|
|
|
spentRequests map[wire.OutPoint]struct{}
|
2014-01-14 21:59:31 +01:00
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
// Networking infrastructure.
|
|
|
|
asyncStarted bool
|
2015-02-21 05:34:57 +01:00
|
|
|
asyncChan chan *parsedRPCCmd
|
2014-02-19 00:23:33 +01:00
|
|
|
ntfnChan chan []byte
|
|
|
|
sendChan chan wsResponse
|
2014-07-02 17:31:10 +02:00
|
|
|
quit chan struct{}
|
2014-02-19 00:23:33 +01:00
|
|
|
wg sync.WaitGroup
|
|
|
|
}
|
2014-01-14 21:59:31 +01:00
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
// handleMessage is the main handler for incoming requests. It enforces
|
|
|
|
// authentication, parses the incoming json, looks up and executes handlers
|
2015-02-21 05:34:57 +01:00
|
|
|
// (including pass through for standard RPC commands), and sends the appropriate
|
2014-02-19 00:23:33 +01:00
|
|
|
// response. It also detects commands which are marked as long-running and
|
|
|
|
// sends them off to the asyncHander for processing.
|
2014-06-07 07:35:34 +02:00
|
|
|
func (c *wsClient) handleMessage(msg []byte) {
|
2014-02-19 00:23:33 +01:00
|
|
|
if !c.authenticated {
|
|
|
|
// Disconnect immediately if the provided command fails to
|
|
|
|
// parse when the client is not already authenticated.
|
2015-02-21 05:34:57 +01:00
|
|
|
var request btcjson.Request
|
|
|
|
if err := json.Unmarshal(msg, &request); err != nil {
|
|
|
|
c.Disconnect()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
parsedCmd := parseCmd(&request)
|
|
|
|
if parsedCmd.err != nil {
|
2014-02-19 00:23:33 +01:00
|
|
|
c.Disconnect()
|
|
|
|
return
|
2014-01-14 21:59:31 +01:00
|
|
|
}
|
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
// Disconnect immediately if the first command is not
|
|
|
|
// authenticate when not already authenticated.
|
2015-02-21 05:34:57 +01:00
|
|
|
authCmd, ok := parsedCmd.cmd.(*btcjson.AuthenticateCmd)
|
2014-02-19 00:23:33 +01:00
|
|
|
if !ok {
|
|
|
|
rpcsLog.Warnf("Unauthenticated websocket message " +
|
|
|
|
"received")
|
|
|
|
c.Disconnect()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check credentials.
|
|
|
|
login := authCmd.Username + ":" + authCmd.Passphrase
|
|
|
|
auth := "Basic " + base64.StdEncoding.EncodeToString([]byte(login))
|
2014-05-01 17:36:41 +02:00
|
|
|
authSha := fastsha256.Sum256([]byte(auth))
|
2014-02-19 00:23:33 +01:00
|
|
|
cmp := subtle.ConstantTimeCompare(authSha[:], c.server.authsha[:])
|
2015-03-30 19:45:31 +02:00
|
|
|
limitcmp := subtle.ConstantTimeCompare(authSha[:], c.server.limitauthsha[:])
|
|
|
|
if cmp != 1 && limitcmp != 1 {
|
2014-02-19 00:23:33 +01:00
|
|
|
rpcsLog.Warnf("Auth failure.")
|
|
|
|
c.Disconnect()
|
|
|
|
return
|
2014-01-21 00:07:17 +01:00
|
|
|
}
|
2014-02-19 00:23:33 +01:00
|
|
|
c.authenticated = true
|
2015-03-30 19:45:31 +02:00
|
|
|
c.isAdmin = cmp == 1
|
2014-02-19 00:23:33 +01:00
|
|
|
|
|
|
|
// Marshal and send response.
|
2015-02-21 05:34:57 +01:00
|
|
|
reply, err := createMarshalledReply(parsedCmd.id, nil, nil)
|
2014-02-19 00:23:33 +01:00
|
|
|
if err != nil {
|
|
|
|
rpcsLog.Errorf("Failed to marshal authenticate reply: "+
|
|
|
|
"%v", err.Error())
|
|
|
|
return
|
2014-01-21 00:07:17 +01:00
|
|
|
}
|
2014-02-19 00:23:33 +01:00
|
|
|
c.SendMessage(reply, nil)
|
|
|
|
return
|
2013-12-31 20:15:44 +01:00
|
|
|
}
|
|
|
|
|
2015-02-21 05:34:57 +01:00
|
|
|
// Attempt to parse the raw message into a JSON-RPC request.
|
|
|
|
var request btcjson.Request
|
|
|
|
if err := json.Unmarshal(msg, &request); err != nil {
|
|
|
|
jsonErr := &btcjson.RPCError{
|
|
|
|
Code: btcjson.ErrRPCParse.Code,
|
|
|
|
Message: "Failed to parse request: " + err.Error(),
|
2014-02-19 00:23:33 +01:00
|
|
|
}
|
2013-12-31 20:15:44 +01:00
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
// Marshal and send response.
|
2015-02-21 05:34:57 +01:00
|
|
|
reply, err := createMarshalledReply(nil, nil, jsonErr)
|
2014-02-19 00:23:33 +01:00
|
|
|
if err != nil {
|
|
|
|
rpcsLog.Errorf("Failed to marshal parse failure "+
|
|
|
|
"reply: %v", err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
c.SendMessage(reply, nil)
|
|
|
|
return
|
2014-01-22 21:10:04 +01:00
|
|
|
}
|
2015-02-21 05:34:57 +01:00
|
|
|
// Requests with no ID (notifications) must not have a response per the
|
|
|
|
// JSON-RPC spec.
|
|
|
|
if request.ID == nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2015-03-30 19:45:31 +02:00
|
|
|
// Check if the user is limited and disconnect client if unauthorized
|
|
|
|
if !c.isAdmin {
|
|
|
|
if _, ok := rpcLimited[request.Method]; !ok {
|
|
|
|
jsonErr := &btcjson.RPCError{
|
|
|
|
Code: btcjson.ErrRPCInvalidParams.Code,
|
|
|
|
Message: "limited user not authorized for this method",
|
|
|
|
}
|
|
|
|
// Marshal and send response.
|
|
|
|
reply, err := createMarshalledReply(request.ID, nil, jsonErr)
|
|
|
|
if err != nil {
|
|
|
|
rpcsLog.Errorf("Failed to marshal parse failure "+
|
|
|
|
"reply: %v", err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
c.SendMessage(reply, nil)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-02-21 05:34:57 +01:00
|
|
|
// Attempt to parse the JSON-RPC request into a known concrete command.
|
|
|
|
cmd := parseCmd(&request)
|
|
|
|
if cmd.err != nil {
|
|
|
|
// Marshal and send response.
|
|
|
|
reply, err := createMarshalledReply(cmd.id, nil, cmd.err)
|
|
|
|
if err != nil {
|
|
|
|
rpcsLog.Errorf("Failed to marshal parse failure "+
|
|
|
|
"reply: %v", err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
c.SendMessage(reply, nil)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
rpcsLog.Debugf("Received command <%s> from %s", cmd.method, c.addr)
|
2014-02-19 00:23:33 +01:00
|
|
|
|
|
|
|
// Disconnect if already authenticated and another authenticate command
|
|
|
|
// is received.
|
2015-02-21 05:34:57 +01:00
|
|
|
if _, ok := cmd.cmd.(*btcjson.AuthenticateCmd); ok {
|
2014-02-19 00:23:33 +01:00
|
|
|
rpcsLog.Warnf("Websocket client %s is already authenticated",
|
|
|
|
c.addr)
|
|
|
|
c.Disconnect()
|
|
|
|
return
|
2014-01-22 21:10:04 +01:00
|
|
|
}
|
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
// When the command is marked as a long-running command, send it off
|
|
|
|
// to the asyncHander goroutine for processing.
|
2015-02-21 05:34:57 +01:00
|
|
|
if _, ok := wsAsyncHandlers[cmd.method]; ok {
|
2014-02-19 00:23:33 +01:00
|
|
|
// Start up the async goroutine for handling long-running
|
|
|
|
// requests asynchonrously if needed.
|
|
|
|
if !c.asyncStarted {
|
|
|
|
rpcsLog.Tracef("Starting async handler for %s", c.addr)
|
|
|
|
c.wg.Add(1)
|
|
|
|
go c.asyncHandler()
|
|
|
|
c.asyncStarted = true
|
|
|
|
}
|
|
|
|
c.asyncChan <- cmd
|
|
|
|
return
|
2014-01-22 21:10:04 +01:00
|
|
|
}
|
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
// Lookup the websocket extension for the command and if it doesn't
|
|
|
|
// exist fallback to handling the command as a standard command.
|
2015-02-21 05:34:57 +01:00
|
|
|
wsHandler, ok := wsHandlers[cmd.method]
|
2014-02-19 00:23:33 +01:00
|
|
|
if !ok {
|
|
|
|
// No websocket-specific handler so handle like a legacy
|
|
|
|
// RPC connection.
|
2015-02-21 05:34:57 +01:00
|
|
|
result, jsonErr := c.server.standardCmdResult(cmd, nil)
|
|
|
|
reply, err := createMarshalledReply(cmd.id, result, jsonErr)
|
2014-02-19 00:23:33 +01:00
|
|
|
if err != nil {
|
|
|
|
rpcsLog.Errorf("Failed to marshal reply for <%s> "+
|
2015-02-21 05:34:57 +01:00
|
|
|
"command: %v", cmd.method, err)
|
2014-02-19 00:23:33 +01:00
|
|
|
return
|
|
|
|
}
|
2015-02-21 05:34:57 +01:00
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
c.SendMessage(reply, nil)
|
|
|
|
return
|
|
|
|
}
|
2014-01-22 21:10:04 +01:00
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
// Invoke the handler and marshal and send response.
|
2015-02-21 05:34:57 +01:00
|
|
|
result, jsonErr := wsHandler(c, cmd.cmd)
|
|
|
|
reply, err := createMarshalledReply(cmd.id, result, jsonErr)
|
2014-02-19 00:23:33 +01:00
|
|
|
if err != nil {
|
|
|
|
rpcsLog.Errorf("Failed to marshal reply for <%s> command: %v",
|
2015-02-21 05:34:57 +01:00
|
|
|
cmd.method, err)
|
2014-02-19 00:23:33 +01:00
|
|
|
return
|
|
|
|
}
|
|
|
|
c.SendMessage(reply, nil)
|
2013-12-31 20:15:44 +01:00
|
|
|
}
|
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
// inHandler handles all incoming messages for the websocket connection. It
|
|
|
|
// must be run as a goroutine.
|
|
|
|
func (c *wsClient) inHandler() {
|
|
|
|
out:
|
|
|
|
for {
|
|
|
|
// Break out of the loop once the quit channel has been closed.
|
|
|
|
// Use a non-blocking select here so we fall through otherwise.
|
|
|
|
select {
|
|
|
|
case <-c.quit:
|
|
|
|
break out
|
|
|
|
default:
|
|
|
|
}
|
2013-12-31 20:15:44 +01:00
|
|
|
|
2014-06-07 07:35:34 +02:00
|
|
|
_, msg, err := c.conn.ReadMessage()
|
|
|
|
if err != nil {
|
2014-02-19 00:23:33 +01:00
|
|
|
// Log the error if it's not due to disconnecting.
|
|
|
|
if err != io.EOF {
|
|
|
|
rpcsLog.Errorf("Websocket receive error from "+
|
|
|
|
"%s: %v", c.addr, err)
|
|
|
|
}
|
|
|
|
break out
|
|
|
|
}
|
|
|
|
c.handleMessage(msg)
|
2013-12-31 20:15:44 +01:00
|
|
|
}
|
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
// Ensure the connection is closed.
|
|
|
|
c.Disconnect()
|
|
|
|
c.wg.Done()
|
|
|
|
rpcsLog.Tracef("Websocket client input handler done for %s", c.addr)
|
2013-12-31 20:15:44 +01:00
|
|
|
}
|
|
|
|
|
2016-02-25 18:17:12 +01:00
|
|
|
// notificationQueueHandler handles the queuing of outgoing notifications for
|
2014-02-19 00:23:33 +01:00
|
|
|
// the websocket client. This runs as a muxer for various sources of input to
|
2016-02-25 18:17:12 +01:00
|
|
|
// ensure that queuing up notifications to be sent will not block. Otherwise,
|
2014-02-19 00:23:33 +01:00
|
|
|
// slow clients could bog down the other systems (such as the mempool or block
|
2016-02-25 18:17:12 +01:00
|
|
|
// manager) which are queuing the data. The data is passed on to outHandler to
|
2014-02-19 00:23:33 +01:00
|
|
|
// actually be written. It must be run as a goroutine.
|
|
|
|
func (c *wsClient) notificationQueueHandler() {
|
|
|
|
ntfnSentChan := make(chan bool, 1) // nonblocking sync
|
|
|
|
|
|
|
|
// pendingNtfns is used as a queue for notifications that are ready to
|
|
|
|
// be sent once there are no outstanding notifications currently being
|
|
|
|
// sent. The waiting flag is used over simply checking for items in the
|
|
|
|
// pending list to ensure cleanup knows what has and hasn't been sent
|
|
|
|
// to the outHandler. Currently no special cleanup is needed, however
|
|
|
|
// if something like a done channel is added to notifications in the
|
|
|
|
// future, not knowing what has and hasn't been sent to the outHandler
|
|
|
|
// (and thus who should respond to the done channel) would be
|
|
|
|
// problematic without using this approach.
|
|
|
|
pendingNtfns := list.New()
|
|
|
|
waiting := false
|
|
|
|
out:
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
// This channel is notified when a message is being queued to
|
|
|
|
// be sent across the network socket. It will either send the
|
|
|
|
// message immediately if a send is not already in progress, or
|
|
|
|
// queue the message to be sent once the other pending messages
|
|
|
|
// are sent.
|
|
|
|
case msg := <-c.ntfnChan:
|
|
|
|
if !waiting {
|
|
|
|
c.SendMessage(msg, ntfnSentChan)
|
|
|
|
} else {
|
|
|
|
pendingNtfns.PushBack(msg)
|
|
|
|
}
|
|
|
|
waiting = true
|
|
|
|
|
|
|
|
// This channel is notified when a notification has been sent
|
|
|
|
// across the network socket.
|
|
|
|
case <-ntfnSentChan:
|
|
|
|
// No longer waiting if there are no more messages in
|
|
|
|
// the pending messages queue.
|
|
|
|
next := pendingNtfns.Front()
|
|
|
|
if next == nil {
|
|
|
|
waiting = false
|
|
|
|
continue
|
|
|
|
}
|
2014-01-14 19:15:22 +01:00
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
// Notify the outHandler about the next item to
|
|
|
|
// asynchronously send.
|
|
|
|
msg := pendingNtfns.Remove(next).([]byte)
|
|
|
|
c.SendMessage(msg, ntfnSentChan)
|
2013-12-31 20:15:44 +01:00
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
case <-c.quit:
|
|
|
|
break out
|
|
|
|
}
|
2014-01-14 21:59:31 +01:00
|
|
|
}
|
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
// Drain any wait channels before exiting so nothing is left waiting
|
|
|
|
// around to send.
|
|
|
|
cleanup:
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-c.ntfnChan:
|
|
|
|
case <-ntfnSentChan:
|
|
|
|
default:
|
|
|
|
break cleanup
|
2013-12-31 20:15:44 +01:00
|
|
|
}
|
2014-02-19 00:23:33 +01:00
|
|
|
}
|
|
|
|
c.wg.Done()
|
|
|
|
rpcsLog.Tracef("Websocket client notification queue handler done "+
|
|
|
|
"for %s", c.addr)
|
|
|
|
}
|
2013-12-31 20:15:44 +01:00
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
// outHandler handles all outgoing messages for the websocket connection. It
|
|
|
|
// must be run as a goroutine. It uses a buffered channel to serialize output
|
|
|
|
// messages while allowing the sender to continue running asynchronously. It
|
|
|
|
// must be run as a goroutine.
|
|
|
|
func (c *wsClient) outHandler() {
|
|
|
|
out:
|
2013-12-31 20:15:44 +01:00
|
|
|
for {
|
2014-02-19 00:23:33 +01:00
|
|
|
// Send any messages ready for send until the quit channel is
|
|
|
|
// closed.
|
2013-12-31 20:15:44 +01:00
|
|
|
select {
|
2014-02-19 00:23:33 +01:00
|
|
|
case r := <-c.sendChan:
|
2014-06-07 07:35:34 +02:00
|
|
|
err := c.conn.WriteMessage(websocket.TextMessage, r.msg)
|
2014-01-14 19:15:22 +01:00
|
|
|
if err != nil {
|
2014-02-19 00:23:33 +01:00
|
|
|
c.Disconnect()
|
|
|
|
break out
|
2014-01-14 19:15:22 +01:00
|
|
|
}
|
2014-02-19 00:23:33 +01:00
|
|
|
if r.doneChan != nil {
|
|
|
|
r.doneChan <- true
|
2013-12-31 20:15:44 +01:00
|
|
|
}
|
2014-01-14 19:15:22 +01:00
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
case <-c.quit:
|
|
|
|
break out
|
|
|
|
}
|
|
|
|
}
|
2014-01-15 03:45:42 +01:00
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
// Drain any wait channels before exiting so nothing is left waiting
|
|
|
|
// around to send.
|
|
|
|
cleanup:
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case r := <-c.sendChan:
|
|
|
|
if r.doneChan != nil {
|
|
|
|
r.doneChan <- false
|
2014-01-14 19:15:22 +01:00
|
|
|
}
|
2014-02-19 00:23:33 +01:00
|
|
|
default:
|
|
|
|
break cleanup
|
2013-12-31 20:15:44 +01:00
|
|
|
}
|
|
|
|
}
|
2014-02-19 00:23:33 +01:00
|
|
|
c.wg.Done()
|
|
|
|
rpcsLog.Tracef("Websocket client output handler done for %s", c.addr)
|
2013-12-31 20:15:44 +01:00
|
|
|
}
|
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
// asyncHandler handles all long-running requests such as rescans which are
|
|
|
|
// not run directly in the inHandler routine unlike most requests. This allows
|
|
|
|
// normal quick requests to continue to be processed and responded to even while
|
|
|
|
// lengthy operations are underway. Only one long-running operation is
|
|
|
|
// permitted at a time, so multiple long-running requests are queued and
|
|
|
|
// serialized. It must be run as a goroutine. Also, this goroutine is not
|
|
|
|
// started until/if the first long-running request is made.
|
|
|
|
func (c *wsClient) asyncHandler() {
|
2014-07-02 17:31:10 +02:00
|
|
|
asyncHandlerDoneChan := make(chan struct{}, 1) // nonblocking sync
|
2014-02-19 00:23:33 +01:00
|
|
|
pendingCmds := list.New()
|
|
|
|
waiting := false
|
|
|
|
|
|
|
|
// runHandler runs the handler for the passed command and sends the
|
|
|
|
// reply.
|
2015-02-21 05:34:57 +01:00
|
|
|
runHandler := func(parsedCmd *parsedRPCCmd) {
|
|
|
|
wsHandler, ok := wsHandlers[parsedCmd.method]
|
2014-02-19 00:23:33 +01:00
|
|
|
if !ok {
|
|
|
|
rpcsLog.Warnf("No handler for command <%s>",
|
2015-02-21 05:34:57 +01:00
|
|
|
parsedCmd.method)
|
2014-02-19 00:23:33 +01:00
|
|
|
return
|
|
|
|
}
|
2014-01-14 21:59:31 +01:00
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
// Invoke the handler and marshal and send response.
|
2015-02-21 05:34:57 +01:00
|
|
|
result, jsonErr := wsHandler(c, parsedCmd.cmd)
|
|
|
|
reply, err := createMarshalledReply(parsedCmd.id, result,
|
|
|
|
jsonErr)
|
2014-02-19 00:23:33 +01:00
|
|
|
if err != nil {
|
|
|
|
rpcsLog.Errorf("Failed to marshal reply for <%s> "+
|
2015-02-21 05:34:57 +01:00
|
|
|
"command: %v", parsedCmd.method, err)
|
2014-02-19 00:23:33 +01:00
|
|
|
return
|
2013-12-31 20:15:44 +01:00
|
|
|
}
|
2014-02-19 00:23:33 +01:00
|
|
|
c.SendMessage(reply, nil)
|
|
|
|
}
|
2013-12-31 20:15:44 +01:00
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
out:
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case cmd := <-c.asyncChan:
|
|
|
|
if !waiting {
|
|
|
|
c.wg.Add(1)
|
2015-02-21 05:34:57 +01:00
|
|
|
go func(cmd *parsedRPCCmd) {
|
2014-02-19 00:23:33 +01:00
|
|
|
runHandler(cmd)
|
2014-07-02 17:31:10 +02:00
|
|
|
asyncHandlerDoneChan <- struct{}{}
|
2014-02-19 00:23:33 +01:00
|
|
|
c.wg.Done()
|
|
|
|
}(cmd)
|
|
|
|
} else {
|
|
|
|
pendingCmds.PushBack(cmd)
|
|
|
|
}
|
|
|
|
waiting = true
|
|
|
|
|
|
|
|
case <-asyncHandlerDoneChan:
|
|
|
|
// No longer waiting if there are no more messages in
|
|
|
|
// the pending messages queue.
|
|
|
|
next := pendingCmds.Front()
|
|
|
|
if next == nil {
|
|
|
|
waiting = false
|
|
|
|
continue
|
2014-01-22 21:10:04 +01:00
|
|
|
}
|
2014-01-14 21:59:31 +01:00
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
// Notify the outHandler about the next item to
|
|
|
|
// asynchronously send.
|
|
|
|
element := pendingCmds.Remove(next)
|
|
|
|
c.wg.Add(1)
|
2015-02-21 05:34:57 +01:00
|
|
|
go func(cmd *parsedRPCCmd) {
|
2014-02-19 00:23:33 +01:00
|
|
|
runHandler(cmd)
|
2014-07-02 17:31:10 +02:00
|
|
|
asyncHandlerDoneChan <- struct{}{}
|
2014-02-19 00:23:33 +01:00
|
|
|
c.wg.Done()
|
2015-02-21 05:34:57 +01:00
|
|
|
}(element.(*parsedRPCCmd))
|
2014-02-19 00:23:33 +01:00
|
|
|
|
|
|
|
case <-c.quit:
|
|
|
|
break out
|
|
|
|
}
|
2014-01-14 21:59:31 +01:00
|
|
|
}
|
2014-01-22 21:10:04 +01:00
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
// Drain any wait channels before exiting so nothing is left waiting
|
|
|
|
// around to send.
|
|
|
|
cleanup:
|
|
|
|
for {
|
2014-01-22 21:10:04 +01:00
|
|
|
select {
|
2014-02-19 00:23:33 +01:00
|
|
|
case <-c.asyncChan:
|
|
|
|
case <-asyncHandlerDoneChan:
|
2014-01-22 21:10:04 +01:00
|
|
|
default:
|
2014-02-19 00:23:33 +01:00
|
|
|
break cleanup
|
2014-01-22 21:10:04 +01:00
|
|
|
}
|
2014-02-19 00:23:33 +01:00
|
|
|
}
|
2014-01-22 21:10:04 +01:00
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
c.wg.Done()
|
|
|
|
rpcsLog.Tracef("Websocket client async handler done for %s", c.addr)
|
2013-12-31 20:15:44 +01:00
|
|
|
}
|
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
// SendMessage sends the passed json to the websocket client. It is backed
|
|
|
|
// by a buffered channel, so it will not block until the send channel is full.
|
|
|
|
// Note however that QueueNotification must be used for sending async
|
|
|
|
// notifications instead of the this function. This approach allows a limit to
|
|
|
|
// the number of outstanding requests a client can make without preventing or
|
|
|
|
// blocking on async notifications.
|
|
|
|
func (c *wsClient) SendMessage(marshalledJSON []byte, doneChan chan bool) {
|
2014-02-25 06:57:36 +01:00
|
|
|
// Don't send the message if disconnected.
|
|
|
|
if c.Disconnected() {
|
2014-02-19 00:23:33 +01:00
|
|
|
if doneChan != nil {
|
|
|
|
doneChan <- false
|
|
|
|
}
|
2013-12-31 20:15:44 +01:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
c.sendChan <- wsResponse{msg: marshalledJSON, doneChan: doneChan}
|
|
|
|
}
|
|
|
|
|
2014-02-24 15:10:59 +01:00
|
|
|
// ErrClientQuit describes the error where a client send is not processed due
|
|
|
|
// to the client having already been disconnected or dropped.
|
|
|
|
var ErrClientQuit = errors.New("client quit")
|
|
|
|
|
2014-07-09 08:37:55 +02:00
|
|
|
// QueueNotification queues the passed notification to be sent to the websocket
|
2014-02-19 00:23:33 +01:00
|
|
|
// client. This function, as the name implies, is only intended for
|
|
|
|
// notifications since it has additional logic to prevent other subsystems, such
|
|
|
|
// as the memory pool and block manager, from blocking even when the send
|
|
|
|
// channel is full.
|
2014-02-24 15:10:59 +01:00
|
|
|
//
|
|
|
|
// If the client is in the process of shutting down, this function returns
|
|
|
|
// ErrClientQuit. This is intended to be checked by long-running notification
|
|
|
|
// handlers to stop processing if there is no more work needed to be done.
|
|
|
|
func (c *wsClient) QueueNotification(marshalledJSON []byte) error {
|
2014-02-25 06:57:36 +01:00
|
|
|
// Don't queue the message if disconnected.
|
|
|
|
if c.Disconnected() {
|
2014-02-24 15:10:59 +01:00
|
|
|
return ErrClientQuit
|
2014-01-17 22:00:46 +01:00
|
|
|
}
|
2013-12-31 20:15:44 +01:00
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
c.ntfnChan <- marshalledJSON
|
2014-02-24 15:10:59 +01:00
|
|
|
return nil
|
2014-02-19 00:23:33 +01:00
|
|
|
}
|
|
|
|
|
2014-02-25 06:57:36 +01:00
|
|
|
// Disconnected returns whether or not the websocket client is disconnected.
|
|
|
|
func (c *wsClient) Disconnected() bool {
|
|
|
|
c.Lock()
|
|
|
|
defer c.Unlock()
|
|
|
|
|
|
|
|
return c.disconnected
|
|
|
|
}
|
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
// Disconnect disconnects the websocket client.
|
|
|
|
func (c *wsClient) Disconnect() {
|
2014-02-25 06:57:36 +01:00
|
|
|
c.Lock()
|
|
|
|
defer c.Unlock()
|
|
|
|
|
|
|
|
// Nothing to do if already disconnected.
|
|
|
|
if c.disconnected {
|
2014-02-19 00:23:33 +01:00
|
|
|
return
|
2013-12-31 20:15:44 +01:00
|
|
|
}
|
2014-02-19 00:23:33 +01:00
|
|
|
|
|
|
|
rpcsLog.Tracef("Disconnecting websocket client %s", c.addr)
|
|
|
|
close(c.quit)
|
|
|
|
c.conn.Close()
|
2014-02-25 06:57:36 +01:00
|
|
|
c.disconnected = true
|
2013-12-31 20:15:44 +01:00
|
|
|
}
|
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
// Start begins processing input and output messages.
|
|
|
|
func (c *wsClient) Start() {
|
|
|
|
rpcsLog.Tracef("Starting websocket client %s", c.addr)
|
2014-02-10 16:34:26 +01:00
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
// Start processing input and output.
|
|
|
|
c.wg.Add(3)
|
|
|
|
go c.inHandler()
|
|
|
|
go c.notificationQueueHandler()
|
|
|
|
go c.outHandler()
|
|
|
|
}
|
|
|
|
|
|
|
|
// WaitForShutdown blocks until the websocket client goroutines are stopped
|
|
|
|
// and the connection is closed.
|
|
|
|
func (c *wsClient) WaitForShutdown() {
|
|
|
|
c.wg.Wait()
|
|
|
|
}
|
|
|
|
|
|
|
|
// newWebsocketClient returns a new websocket client given the notification
|
|
|
|
// manager, websocket connection, remote address, and whether or not the client
|
|
|
|
// has already been authenticated (via HTTP Basic access authentication). The
|
|
|
|
// returned client is ready to start. Once started, the client will process
|
2016-02-25 18:17:12 +01:00
|
|
|
// incoming and outgoing messages in separate goroutines complete with queuing
|
2014-02-19 00:23:33 +01:00
|
|
|
// and asynchrous handling for long-running operations.
|
|
|
|
func newWebsocketClient(server *rpcServer, conn *websocket.Conn,
|
2015-09-15 20:03:48 +02:00
|
|
|
remoteAddr string, authenticated bool, isAdmin bool) (*wsClient, error) {
|
2014-02-19 00:23:33 +01:00
|
|
|
|
2015-09-15 20:03:48 +02:00
|
|
|
sessionID, err := wire.RandomUint64()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
client := &wsClient{
|
2014-02-19 00:23:33 +01:00
|
|
|
conn: conn,
|
|
|
|
addr: remoteAddr,
|
|
|
|
authenticated: authenticated,
|
2015-03-30 19:45:31 +02:00
|
|
|
isAdmin: isAdmin,
|
2015-09-15 20:03:48 +02:00
|
|
|
sessionID: sessionID,
|
2014-02-19 00:23:33 +01:00
|
|
|
server: server,
|
|
|
|
addrRequests: make(map[string]struct{}),
|
2015-02-05 22:16:39 +01:00
|
|
|
spentRequests: make(map[wire.OutPoint]struct{}),
|
2015-02-21 05:34:57 +01:00
|
|
|
ntfnChan: make(chan []byte, 1), // nonblocking sync
|
|
|
|
asyncChan: make(chan *parsedRPCCmd, 1), // nonblocking sync
|
2014-02-19 00:23:33 +01:00
|
|
|
sendChan: make(chan wsResponse, websocketSendBufferSize),
|
2014-07-02 17:31:10 +02:00
|
|
|
quit: make(chan struct{}),
|
2014-02-19 00:23:33 +01:00
|
|
|
}
|
2015-09-15 20:03:48 +02:00
|
|
|
return client, nil
|
2014-02-19 00:23:33 +01:00
|
|
|
}
|
|
|
|
|
2015-02-21 05:34:57 +01:00
|
|
|
// handleWebsocketHelp implements the help command for websocket connections.
|
|
|
|
func handleWebsocketHelp(wsc *wsClient, icmd interface{}) (interface{}, error) {
|
|
|
|
cmd, ok := icmd.(*btcjson.HelpCmd)
|
|
|
|
if !ok {
|
|
|
|
return nil, btcjson.ErrRPCInternal
|
|
|
|
}
|
|
|
|
|
|
|
|
// Provide a usage overview of all commands when no specific command
|
|
|
|
// was specified.
|
|
|
|
var command string
|
|
|
|
if cmd.Command != nil {
|
|
|
|
command = *cmd.Command
|
|
|
|
}
|
|
|
|
if command == "" {
|
|
|
|
usage, err := wsc.server.helpCacher.rpcUsage(true)
|
|
|
|
if err != nil {
|
|
|
|
context := "Failed to generate RPC usage"
|
|
|
|
return nil, internalRPCError(err.Error(), context)
|
|
|
|
}
|
|
|
|
return usage, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check that the command asked for is supported and implemented.
|
|
|
|
// Search the list of websocket handlers as well as the main list of
|
|
|
|
// handlers since help should only be provided for those cases.
|
|
|
|
valid := true
|
|
|
|
if _, ok := rpcHandlers[command]; !ok {
|
|
|
|
if _, ok := wsHandlers[command]; !ok {
|
|
|
|
valid = false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if !valid {
|
|
|
|
return nil, &btcjson.RPCError{
|
|
|
|
Code: btcjson.ErrRPCInvalidParameter,
|
|
|
|
Message: "Unknown command: " + command,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Get the help for the command.
|
|
|
|
help, err := wsc.server.helpCacher.rpcMethodHelp(command)
|
|
|
|
if err != nil {
|
|
|
|
context := "Failed to generate help"
|
|
|
|
return nil, internalRPCError(err.Error(), context)
|
|
|
|
}
|
|
|
|
return help, nil
|
|
|
|
}
|
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
// handleNotifyBlocks implements the notifyblocks command extension for
|
|
|
|
// websocket connections.
|
2015-02-21 05:34:57 +01:00
|
|
|
func handleNotifyBlocks(wsc *wsClient, icmd interface{}) (interface{}, error) {
|
2014-03-04 17:15:25 +01:00
|
|
|
wsc.server.ntfnMgr.RegisterBlockUpdates(wsc)
|
2014-02-19 00:23:33 +01:00
|
|
|
return nil, nil
|
|
|
|
}
|
2014-01-08 17:40:27 +01:00
|
|
|
|
2015-09-15 20:03:48 +02:00
|
|
|
// handleSession implements the session command extension for websocket
|
|
|
|
// connections.
|
|
|
|
func handleSession(wsc *wsClient, icmd interface{}) (interface{}, error) {
|
|
|
|
return &btcjson.SessionResult{SessionID: wsc.sessionID}, nil
|
|
|
|
}
|
|
|
|
|
2015-03-03 21:37:02 +01:00
|
|
|
// handleStopNotifyBlocks implements the stopnotifyblocks command extension for
|
|
|
|
// websocket connections.
|
|
|
|
func handleStopNotifyBlocks(wsc *wsClient, icmd interface{}) (interface{}, error) {
|
|
|
|
wsc.server.ntfnMgr.UnregisterBlockUpdates(wsc)
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
// handleNotifySpent implements the notifyspent command extension for
|
|
|
|
// websocket connections.
|
2015-02-21 05:34:57 +01:00
|
|
|
func handleNotifySpent(wsc *wsClient, icmd interface{}) (interface{}, error) {
|
|
|
|
cmd, ok := icmd.(*btcjson.NotifySpentCmd)
|
2014-02-19 00:23:33 +01:00
|
|
|
if !ok {
|
2015-02-21 05:34:57 +01:00
|
|
|
return nil, btcjson.ErrRPCInternal
|
2014-02-19 00:23:33 +01:00
|
|
|
}
|
2014-01-08 17:40:27 +01:00
|
|
|
|
2015-03-03 21:37:02 +01:00
|
|
|
outpoints, err := deserializeOutpoints(cmd.OutPoints)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
2014-05-06 15:30:36 +02:00
|
|
|
}
|
2015-03-03 21:37:02 +01:00
|
|
|
|
2015-02-19 20:51:44 +01:00
|
|
|
wsc.server.ntfnMgr.RegisterSpentRequests(wsc, outpoints)
|
2014-02-19 00:23:33 +01:00
|
|
|
return nil, nil
|
2013-12-31 20:15:44 +01:00
|
|
|
}
|
|
|
|
|
2014-04-15 07:29:49 +02:00
|
|
|
// handleNotifyNewTransations implements the notifynewtransactions command
|
|
|
|
// extension for websocket connections.
|
2015-02-21 05:34:57 +01:00
|
|
|
func handleNotifyNewTransactions(wsc *wsClient, icmd interface{}) (interface{}, error) {
|
|
|
|
cmd, ok := icmd.(*btcjson.NotifyNewTransactionsCmd)
|
2014-02-19 00:23:33 +01:00
|
|
|
if !ok {
|
2015-02-21 05:34:57 +01:00
|
|
|
return nil, btcjson.ErrRPCInternal
|
2013-12-31 20:15:44 +01:00
|
|
|
}
|
|
|
|
|
2015-02-21 05:34:57 +01:00
|
|
|
wsc.verboseTxUpdates = cmd.Verbose != nil && *cmd.Verbose
|
2014-03-04 17:15:25 +01:00
|
|
|
wsc.server.ntfnMgr.RegisterNewMempoolTxsUpdates(wsc)
|
2014-02-19 00:23:33 +01:00
|
|
|
return nil, nil
|
|
|
|
}
|
2014-02-10 16:34:26 +01:00
|
|
|
|
2015-03-03 21:37:02 +01:00
|
|
|
// handleStopNotifyNewTransations implements the stopnotifynewtransactions
|
|
|
|
// command extension for websocket connections.
|
|
|
|
func handleStopNotifyNewTransactions(wsc *wsClient, icmd interface{}) (interface{}, error) {
|
|
|
|
wsc.server.ntfnMgr.UnregisterNewMempoolTxsUpdates(wsc)
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
|
2014-04-15 02:11:08 +02:00
|
|
|
// handleNotifyReceived implements the notifyreceived command extension for
|
2014-02-19 00:23:33 +01:00
|
|
|
// websocket connections.
|
2015-02-21 05:34:57 +01:00
|
|
|
func handleNotifyReceived(wsc *wsClient, icmd interface{}) (interface{}, error) {
|
|
|
|
cmd, ok := icmd.(*btcjson.NotifyReceivedCmd)
|
2014-02-19 00:23:33 +01:00
|
|
|
if !ok {
|
2015-02-21 05:34:57 +01:00
|
|
|
return nil, btcjson.ErrRPCInternal
|
2014-01-17 20:11:49 +01:00
|
|
|
}
|
|
|
|
|
2015-02-19 20:51:44 +01:00
|
|
|
// Decode addresses to validate input, but the strings slice is used
|
|
|
|
// directly if these are all ok.
|
2015-03-03 21:37:02 +01:00
|
|
|
err := checkAddressValidity(cmd.Addresses)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
wsc.server.ntfnMgr.RegisterTxOutAddressRequests(wsc, cmd.Addresses)
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// handleStopNotifySpent implements the stopnotifyspent command extension for
|
|
|
|
// websocket connections.
|
|
|
|
func handleStopNotifySpent(wsc *wsClient, icmd interface{}) (interface{}, error) {
|
|
|
|
cmd, ok := icmd.(*btcjson.StopNotifySpentCmd)
|
|
|
|
if !ok {
|
|
|
|
return nil, btcjson.ErrRPCInternal
|
|
|
|
}
|
|
|
|
|
|
|
|
outpoints, err := deserializeOutpoints(cmd.OutPoints)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, outpoint := range outpoints {
|
|
|
|
wsc.server.ntfnMgr.UnregisterSpentRequest(wsc, outpoint)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// handleStopNotifyReceived implements the stopnotifyreceived command extension
|
|
|
|
// for websocket connections.
|
|
|
|
func handleStopNotifyReceived(wsc *wsClient, icmd interface{}) (interface{}, error) {
|
|
|
|
cmd, ok := icmd.(*btcjson.StopNotifyReceivedCmd)
|
|
|
|
if !ok {
|
|
|
|
return nil, btcjson.ErrRPCInternal
|
|
|
|
}
|
|
|
|
|
|
|
|
// Decode addresses to validate input, but the strings slice is used
|
|
|
|
// directly if these are all ok.
|
|
|
|
err := checkAddressValidity(cmd.Addresses)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2015-02-19 20:51:44 +01:00
|
|
|
for _, addr := range cmd.Addresses {
|
2015-03-03 21:37:02 +01:00
|
|
|
wsc.server.ntfnMgr.UnregisterTxOutAddressRequest(wsc, addr)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// checkAddressValidity checks the validity of each address in the passed
|
|
|
|
// string slice. It does this by attempting to decode each address using the
|
|
|
|
// current active network parameters. If any single address fails to decode
|
|
|
|
// properly, the function returns an error. Otherwise, nil is returned.
|
|
|
|
func checkAddressValidity(addrs []string) error {
|
|
|
|
for _, addr := range addrs {
|
2015-02-19 20:51:44 +01:00
|
|
|
_, err := btcutil.DecodeAddress(addr, activeNetParams.Params)
|
2014-01-08 03:30:01 +01:00
|
|
|
if err != nil {
|
2015-03-03 21:37:02 +01:00
|
|
|
return &btcjson.RPCError{
|
2015-02-21 05:34:57 +01:00
|
|
|
Code: btcjson.ErrRPCInvalidAddressOrKey,
|
|
|
|
Message: fmt.Sprintf("Invalid address or key: %v",
|
|
|
|
addr),
|
2014-02-19 00:23:33 +01:00
|
|
|
}
|
2013-12-31 20:15:44 +01:00
|
|
|
}
|
2014-02-19 00:23:33 +01:00
|
|
|
}
|
2015-03-03 21:37:02 +01:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// deserializeOutpoints deserializes each serialized outpoint.
|
|
|
|
func deserializeOutpoints(serializedOuts []btcjson.OutPoint) ([]*wire.OutPoint, error) {
|
|
|
|
outpoints := make([]*wire.OutPoint, 0, len(serializedOuts))
|
|
|
|
for i := range serializedOuts {
|
|
|
|
blockHash, err := wire.NewShaHashFromStr(serializedOuts[i].Hash)
|
|
|
|
if err != nil {
|
|
|
|
return nil, rpcDecodeHexError(serializedOuts[i].Hash)
|
|
|
|
}
|
|
|
|
index := serializedOuts[i].Index
|
|
|
|
outpoints = append(outpoints, wire.NewOutPoint(blockHash, index))
|
|
|
|
}
|
|
|
|
|
|
|
|
return outpoints, nil
|
2014-02-19 00:23:33 +01:00
|
|
|
}
|
|
|
|
|
2014-03-21 14:25:00 +01:00
|
|
|
type rescanKeys struct {
|
|
|
|
fallbacks map[string]struct{}
|
|
|
|
pubKeyHashes map[[ripemd160.Size]byte]struct{}
|
|
|
|
scriptHashes map[[ripemd160.Size]byte]struct{}
|
2015-08-02 23:21:27 +02:00
|
|
|
compressedPubKeys map[[33]byte]struct{}
|
|
|
|
uncompressedPubKeys map[[65]byte]struct{}
|
2015-02-05 22:16:39 +01:00
|
|
|
unspent map[wire.OutPoint]struct{}
|
2014-03-21 14:25:00 +01:00
|
|
|
}
|
|
|
|
|
2015-02-19 20:51:44 +01:00
|
|
|
// unspentSlice returns a slice of currently-unspent outpoints for the rescan
|
|
|
|
// lookup keys. This is primarily intended to be used to register outpoints
|
|
|
|
// for continuous notifications after a rescan has completed.
|
|
|
|
func (r *rescanKeys) unspentSlice() []*wire.OutPoint {
|
|
|
|
ops := make([]*wire.OutPoint, 0, len(r.unspent))
|
|
|
|
for op := range r.unspent {
|
|
|
|
opCopy := op
|
|
|
|
ops = append(ops, &opCopy)
|
|
|
|
}
|
|
|
|
return ops
|
|
|
|
}
|
|
|
|
|
2014-07-17 07:41:43 +02:00
|
|
|
// ErrRescanReorg defines the error that is returned when an unrecoverable
|
|
|
|
// reorganize is detected during a rescan.
|
2015-02-21 05:34:57 +01:00
|
|
|
var ErrRescanReorg = btcjson.RPCError{
|
|
|
|
Code: btcjson.ErrRPCDatabase,
|
2014-07-17 07:41:43 +02:00
|
|
|
Message: "Reorganize",
|
|
|
|
}
|
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
// rescanBlock rescans all transactions in a single block. This is a helper
|
|
|
|
// function for handleRescan.
|
2014-03-21 14:25:00 +01:00
|
|
|
func rescanBlock(wsc *wsClient, lookups *rescanKeys, blk *btcutil.Block) {
|
2014-02-19 00:23:33 +01:00
|
|
|
for _, tx := range blk.Transactions() {
|
2014-02-24 15:10:59 +01:00
|
|
|
// Hexadecimal representation of this tx. Only created if
|
|
|
|
// needed, and reused for later notifications if already made.
|
|
|
|
var txHex string
|
|
|
|
|
|
|
|
// All inputs and outputs must be iterated through to correctly
|
|
|
|
// modify the unspent map, however, just a single notification
|
|
|
|
// for any matching transaction inputs or outputs should be
|
|
|
|
// created and sent.
|
|
|
|
spentNotified := false
|
|
|
|
recvNotified := false
|
|
|
|
|
|
|
|
for _, txin := range tx.MsgTx().TxIn {
|
2014-10-01 17:34:30 +02:00
|
|
|
if _, ok := lookups.unspent[txin.PreviousOutPoint]; ok {
|
|
|
|
delete(lookups.unspent, txin.PreviousOutPoint)
|
2014-02-24 15:10:59 +01:00
|
|
|
|
|
|
|
if spentNotified {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
if txHex == "" {
|
|
|
|
txHex = txHexString(tx)
|
|
|
|
}
|
|
|
|
marshalledJSON, err := newRedeemingTxNotification(txHex, tx.Index(), blk)
|
|
|
|
if err != nil {
|
|
|
|
rpcsLog.Errorf("Failed to marshal redeemingtx notification: %v", err)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
err = wsc.QueueNotification(marshalledJSON)
|
|
|
|
// Stop the rescan early if the websocket client
|
|
|
|
// disconnected.
|
|
|
|
if err == ErrClientQuit {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
spentNotified = true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
for txOutIdx, txout := range tx.MsgTx().TxOut {
|
2015-01-30 19:14:33 +01:00
|
|
|
_, addrs, _, _ := txscript.ExtractPkScriptAddrs(
|
2015-02-06 06:18:27 +01:00
|
|
|
txout.PkScript, wsc.server.server.chainParams)
|
2014-02-19 00:23:33 +01:00
|
|
|
|
|
|
|
for _, addr := range addrs {
|
2014-03-21 14:25:00 +01:00
|
|
|
switch a := addr.(type) {
|
|
|
|
case *btcutil.AddressPubKeyHash:
|
2014-04-20 22:51:04 +02:00
|
|
|
if _, ok := lookups.pubKeyHashes[*a.Hash160()]; !ok {
|
2014-03-21 14:25:00 +01:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
case *btcutil.AddressScriptHash:
|
2014-04-20 22:51:04 +02:00
|
|
|
if _, ok := lookups.scriptHashes[*a.Hash160()]; !ok {
|
2014-03-21 14:25:00 +01:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
case *btcutil.AddressPubKey:
|
2014-04-25 16:02:23 +02:00
|
|
|
found := false
|
|
|
|
switch sa := a.ScriptAddress(); len(sa) {
|
2014-03-21 14:25:00 +01:00
|
|
|
case 33: // Compressed
|
2014-04-25 16:02:23 +02:00
|
|
|
var key [33]byte
|
|
|
|
copy(key[:], sa)
|
2015-08-02 23:21:27 +02:00
|
|
|
if _, ok := lookups.compressedPubKeys[key]; ok {
|
2014-04-25 16:02:23 +02:00
|
|
|
found = true
|
2014-03-21 14:25:00 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
case 65: // Uncompressed
|
2014-04-25 16:02:23 +02:00
|
|
|
var key [65]byte
|
|
|
|
copy(key[:], sa)
|
2015-08-02 23:21:27 +02:00
|
|
|
if _, ok := lookups.uncompressedPubKeys[key]; ok {
|
2014-04-25 16:02:23 +02:00
|
|
|
found = true
|
2014-03-21 14:25:00 +01:00
|
|
|
}
|
|
|
|
|
2014-04-25 16:02:23 +02:00
|
|
|
default:
|
|
|
|
rpcsLog.Warnf("Skipping rescanned pubkey of unknown "+
|
|
|
|
"serialized length %d", len(sa))
|
2014-03-21 14:25:00 +01:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2014-04-25 16:02:23 +02:00
|
|
|
// If the transaction output pays to the pubkey of
|
|
|
|
// a rescanned P2PKH address, include it as well.
|
|
|
|
if !found {
|
|
|
|
pkh := a.AddressPubKeyHash()
|
|
|
|
if _, ok := lookups.pubKeyHashes[*pkh.Hash160()]; !ok {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-03-21 14:25:00 +01:00
|
|
|
default:
|
|
|
|
// A new address type must have been added. Encode as a
|
|
|
|
// payment address string and check the fallback map.
|
|
|
|
addrStr := addr.EncodeAddress()
|
|
|
|
_, ok := lookups.fallbacks[addrStr]
|
|
|
|
if !ok {
|
|
|
|
continue
|
|
|
|
}
|
2014-02-19 00:23:33 +01:00
|
|
|
}
|
2013-12-31 20:15:44 +01:00
|
|
|
|
2015-02-05 22:16:39 +01:00
|
|
|
outpoint := wire.OutPoint{
|
2014-04-25 16:02:23 +02:00
|
|
|
Hash: *tx.Sha(),
|
|
|
|
Index: uint32(txOutIdx),
|
|
|
|
}
|
2014-03-21 14:25:00 +01:00
|
|
|
lookups.unspent[outpoint] = struct{}{}
|
2014-02-24 15:10:59 +01:00
|
|
|
|
|
|
|
if recvNotified {
|
|
|
|
continue
|
2014-02-19 00:23:33 +01:00
|
|
|
}
|
|
|
|
|
2014-02-24 15:10:59 +01:00
|
|
|
if txHex == "" {
|
|
|
|
txHex = txHexString(tx)
|
2014-02-19 00:23:33 +01:00
|
|
|
}
|
2015-02-21 05:34:57 +01:00
|
|
|
ntfn := btcjson.NewRecvTxNtfn(txHex,
|
2015-02-27 01:35:46 +01:00
|
|
|
blockDetails(blk, tx.Index()))
|
2014-02-24 15:10:59 +01:00
|
|
|
|
2015-02-21 05:34:57 +01:00
|
|
|
marshalledJSON, err := btcjson.MarshalCmd(nil, ntfn)
|
2014-02-19 00:23:33 +01:00
|
|
|
if err != nil {
|
2014-02-24 15:10:59 +01:00
|
|
|
rpcsLog.Errorf("Failed to marshal recvtx notification: %v", err)
|
2014-02-19 00:23:33 +01:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2014-02-24 15:10:59 +01:00
|
|
|
err = wsc.QueueNotification(marshalledJSON)
|
2014-02-19 00:23:33 +01:00
|
|
|
// Stop the rescan early if the websocket client
|
|
|
|
// disconnected.
|
2014-02-24 15:10:59 +01:00
|
|
|
if err == ErrClientQuit {
|
2014-02-19 00:23:33 +01:00
|
|
|
return
|
2013-12-31 20:15:44 +01:00
|
|
|
}
|
2014-02-24 15:10:59 +01:00
|
|
|
recvNotified = true
|
2013-12-31 20:15:44 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2014-02-08 23:15:17 +01:00
|
|
|
|
2014-07-17 07:41:43 +02:00
|
|
|
// recoverFromReorg attempts to recover from a detected reorganize during a
|
|
|
|
// rescan. It fetches a new range of block shas from the database and
|
|
|
|
// verifies that the new range of blocks is on the same fork as a previous
|
|
|
|
// range of blocks. If this condition does not hold true, the JSON-RPC error
|
|
|
|
// for an unrecoverable reorganize is returned.
|
2015-08-08 04:20:49 +02:00
|
|
|
func recoverFromReorg(db database.Db, minBlock, maxBlock int32,
|
2015-02-21 05:34:57 +01:00
|
|
|
lastBlock *wire.ShaHash) ([]wire.ShaHash, error) {
|
2014-07-17 07:41:43 +02:00
|
|
|
|
|
|
|
hashList, err := db.FetchHeightRange(minBlock, maxBlock)
|
|
|
|
if err != nil {
|
|
|
|
rpcsLog.Errorf("Error looking up block range: %v", err)
|
2015-02-21 05:34:57 +01:00
|
|
|
return nil, &btcjson.RPCError{
|
|
|
|
Code: btcjson.ErrRPCDatabase,
|
|
|
|
Message: "Database error: " + err.Error(),
|
|
|
|
}
|
2014-07-17 07:41:43 +02:00
|
|
|
}
|
|
|
|
if lastBlock == nil || len(hashList) == 0 {
|
|
|
|
return hashList, nil
|
|
|
|
}
|
|
|
|
blk, err := db.FetchBlockBySha(&hashList[0])
|
|
|
|
if err != nil {
|
|
|
|
rpcsLog.Errorf("Error looking up possibly reorged block: %v",
|
|
|
|
err)
|
2015-02-21 05:34:57 +01:00
|
|
|
return nil, &btcjson.RPCError{
|
|
|
|
Code: btcjson.ErrRPCDatabase,
|
|
|
|
Message: "Database error: " + err.Error(),
|
|
|
|
}
|
2014-07-17 07:41:43 +02:00
|
|
|
}
|
|
|
|
jsonErr := descendantBlock(lastBlock, blk)
|
|
|
|
if jsonErr != nil {
|
|
|
|
return nil, jsonErr
|
|
|
|
}
|
|
|
|
return hashList, nil
|
|
|
|
}
|
|
|
|
|
2016-02-25 18:17:12 +01:00
|
|
|
// descendantBlock returns the appropriate JSON-RPC error if a current block
|
2015-02-19 20:51:44 +01:00
|
|
|
// fetched during a reorganize is not a direct child of the parent block hash.
|
2015-02-21 05:34:57 +01:00
|
|
|
func descendantBlock(prevHash *wire.ShaHash, curBlock *btcutil.Block) error {
|
2015-02-19 20:51:44 +01:00
|
|
|
curHash := &curBlock.MsgBlock().Header.PrevBlock
|
|
|
|
if !prevHash.IsEqual(curHash) {
|
2014-07-17 07:41:43 +02:00
|
|
|
rpcsLog.Errorf("Stopping rescan for reorged block %v "+
|
2015-02-19 20:51:44 +01:00
|
|
|
"(replaced by block %v)", prevHash, curHash)
|
2014-07-17 07:41:43 +02:00
|
|
|
return &ErrRescanReorg
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
// handleRescan implements the rescan command extension for websocket
|
|
|
|
// connections.
|
2014-07-17 07:41:43 +02:00
|
|
|
//
|
|
|
|
// NOTE: This does not smartly handle reorgs, and fixing requires database
|
|
|
|
// changes (for safe, concurrent access to full block ranges, and support
|
|
|
|
// for other chains than the best chain). It will, however, detect whether
|
|
|
|
// a reorg removed a block that was previously processed, and result in the
|
|
|
|
// handler erroring. Clients must handle this by finding a block still in
|
|
|
|
// the chain (perhaps from a rescanprogress notification) to resume their
|
|
|
|
// rescan.
|
2015-02-21 05:34:57 +01:00
|
|
|
func handleRescan(wsc *wsClient, icmd interface{}) (interface{}, error) {
|
|
|
|
cmd, ok := icmd.(*btcjson.RescanCmd)
|
2014-02-19 00:23:33 +01:00
|
|
|
if !ok {
|
2015-02-21 05:34:57 +01:00
|
|
|
return nil, btcjson.ErrRPCInternal
|
2014-02-19 00:23:33 +01:00
|
|
|
}
|
2014-02-08 23:15:17 +01:00
|
|
|
|
2015-02-05 22:16:39 +01:00
|
|
|
outpoints := make([]*wire.OutPoint, 0, len(cmd.OutPoints))
|
2014-04-11 03:41:36 +02:00
|
|
|
for i := range cmd.OutPoints {
|
2015-02-05 22:16:39 +01:00
|
|
|
blockHash, err := wire.NewShaHashFromStr(cmd.OutPoints[i].Hash)
|
2014-04-11 03:41:36 +02:00
|
|
|
if err != nil {
|
2015-02-21 05:34:57 +01:00
|
|
|
return nil, rpcDecodeHexError(cmd.OutPoints[i].Hash)
|
2014-04-11 03:41:36 +02:00
|
|
|
}
|
|
|
|
index := cmd.OutPoints[i].Index
|
2015-02-05 22:16:39 +01:00
|
|
|
outpoints = append(outpoints, wire.NewOutPoint(blockHash, index))
|
2014-04-11 03:41:36 +02:00
|
|
|
}
|
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
numAddrs := len(cmd.Addresses)
|
|
|
|
if numAddrs == 1 {
|
|
|
|
rpcsLog.Info("Beginning rescan for 1 address")
|
|
|
|
} else {
|
|
|
|
rpcsLog.Infof("Beginning rescan for %d addresses", numAddrs)
|
2014-02-08 23:15:17 +01:00
|
|
|
}
|
|
|
|
|
2014-03-21 14:25:00 +01:00
|
|
|
// Build lookup maps.
|
|
|
|
lookups := rescanKeys{
|
|
|
|
fallbacks: map[string]struct{}{},
|
|
|
|
pubKeyHashes: map[[ripemd160.Size]byte]struct{}{},
|
|
|
|
scriptHashes: map[[ripemd160.Size]byte]struct{}{},
|
2015-08-02 23:21:27 +02:00
|
|
|
compressedPubKeys: map[[33]byte]struct{}{},
|
|
|
|
uncompressedPubKeys: map[[65]byte]struct{}{},
|
2015-02-05 22:16:39 +01:00
|
|
|
unspent: map[wire.OutPoint]struct{}{},
|
2014-03-21 14:25:00 +01:00
|
|
|
}
|
|
|
|
var compressedPubkey [33]byte
|
|
|
|
var uncompressedPubkey [65]byte
|
2014-03-21 21:43:31 +01:00
|
|
|
for _, addrStr := range cmd.Addresses {
|
2014-05-28 00:44:55 +02:00
|
|
|
addr, err := btcutil.DecodeAddress(addrStr, activeNetParams.Params)
|
2014-03-21 14:25:00 +01:00
|
|
|
if err != nil {
|
2015-02-21 05:34:57 +01:00
|
|
|
jsonErr := btcjson.RPCError{
|
|
|
|
Code: btcjson.ErrRPCInvalidAddressOrKey,
|
|
|
|
Message: "Rescan address " + addrStr + ": " +
|
|
|
|
err.Error(),
|
2014-03-21 14:25:00 +01:00
|
|
|
}
|
|
|
|
return nil, &jsonErr
|
|
|
|
}
|
|
|
|
switch a := addr.(type) {
|
|
|
|
case *btcutil.AddressPubKeyHash:
|
2014-04-20 22:51:04 +02:00
|
|
|
lookups.pubKeyHashes[*a.Hash160()] = struct{}{}
|
2014-03-21 14:25:00 +01:00
|
|
|
|
|
|
|
case *btcutil.AddressScriptHash:
|
2014-04-20 22:51:04 +02:00
|
|
|
lookups.scriptHashes[*a.Hash160()] = struct{}{}
|
2014-03-21 14:25:00 +01:00
|
|
|
|
|
|
|
case *btcutil.AddressPubKey:
|
|
|
|
pubkeyBytes := a.ScriptAddress()
|
|
|
|
switch len(pubkeyBytes) {
|
|
|
|
case 33: // Compressed
|
|
|
|
copy(compressedPubkey[:], pubkeyBytes)
|
2015-08-02 23:21:27 +02:00
|
|
|
lookups.compressedPubKeys[compressedPubkey] = struct{}{}
|
2014-03-21 14:25:00 +01:00
|
|
|
|
|
|
|
case 65: // Uncompressed
|
|
|
|
copy(uncompressedPubkey[:], pubkeyBytes)
|
2015-08-02 23:21:27 +02:00
|
|
|
lookups.uncompressedPubKeys[uncompressedPubkey] = struct{}{}
|
2014-03-21 14:25:00 +01:00
|
|
|
|
|
|
|
default:
|
2015-02-21 05:34:57 +01:00
|
|
|
jsonErr := btcjson.RPCError{
|
|
|
|
Code: btcjson.ErrRPCInvalidAddressOrKey,
|
2014-03-21 14:25:00 +01:00
|
|
|
Message: "Pubkey " + addrStr + " is of unknown length",
|
|
|
|
}
|
|
|
|
return nil, &jsonErr
|
|
|
|
}
|
|
|
|
|
|
|
|
default:
|
|
|
|
// A new address type must have been added. Use encoded
|
|
|
|
// payment address string as a fallback until a fast path
|
|
|
|
// is added.
|
|
|
|
lookups.fallbacks[addrStr] = struct{}{}
|
|
|
|
}
|
|
|
|
}
|
2014-04-11 03:41:36 +02:00
|
|
|
for _, outpoint := range outpoints {
|
2014-03-21 21:43:31 +01:00
|
|
|
lookups.unspent[*outpoint] = struct{}{}
|
|
|
|
}
|
2014-03-21 14:25:00 +01:00
|
|
|
|
2014-07-17 07:41:43 +02:00
|
|
|
db := wsc.server.server.db
|
|
|
|
|
2015-02-05 22:16:39 +01:00
|
|
|
minBlockSha, err := wire.NewShaHashFromStr(cmd.BeginBlock)
|
2014-07-17 07:41:43 +02:00
|
|
|
if err != nil {
|
2015-02-21 05:34:57 +01:00
|
|
|
return nil, rpcDecodeHexError(cmd.BeginBlock)
|
2014-07-17 07:41:43 +02:00
|
|
|
}
|
|
|
|
minBlock, err := db.FetchBlockHeightBySha(minBlockSha)
|
|
|
|
if err != nil {
|
2015-02-21 05:34:57 +01:00
|
|
|
return nil, &btcjson.RPCError{
|
|
|
|
Code: btcjson.ErrRPCBlockNotFound,
|
|
|
|
Message: "Error getting block: " + err.Error(),
|
|
|
|
}
|
2014-07-17 07:41:43 +02:00
|
|
|
}
|
|
|
|
|
2015-01-27 22:38:23 +01:00
|
|
|
maxBlock := database.AllShas
|
2015-02-21 05:34:57 +01:00
|
|
|
if cmd.EndBlock != nil {
|
|
|
|
maxBlockSha, err := wire.NewShaHashFromStr(*cmd.EndBlock)
|
2014-07-17 07:41:43 +02:00
|
|
|
if err != nil {
|
2015-02-21 05:34:57 +01:00
|
|
|
return nil, rpcDecodeHexError(*cmd.EndBlock)
|
2014-07-17 07:41:43 +02:00
|
|
|
}
|
|
|
|
maxBlock, err = db.FetchBlockHeightBySha(maxBlockSha)
|
|
|
|
if err != nil {
|
2015-02-21 05:34:57 +01:00
|
|
|
return nil, &btcjson.RPCError{
|
|
|
|
Code: btcjson.ErrRPCBlockNotFound,
|
|
|
|
Message: "Error getting block: " + err.Error(),
|
|
|
|
}
|
2014-07-17 07:41:43 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-02-19 20:51:44 +01:00
|
|
|
// lastBlock and lastBlockHash track the previously-rescanned block.
|
|
|
|
// They equal nil when no previous blocks have been rescanned.
|
2014-07-17 07:41:43 +02:00
|
|
|
var lastBlock *btcutil.Block
|
2015-02-19 20:51:44 +01:00
|
|
|
var lastBlockHash *wire.ShaHash
|
2014-02-08 23:15:17 +01:00
|
|
|
|
2014-03-24 19:29:50 +01:00
|
|
|
// A ticker is created to wait at least 10 seconds before notifying the
|
|
|
|
// websocket client of the current progress completed by the rescan.
|
|
|
|
ticker := time.NewTicker(10 * time.Second)
|
|
|
|
defer ticker.Stop()
|
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
// FetchHeightRange may not return a complete list of block shas for
|
|
|
|
// the given range, so fetch range as many times as necessary.
|
2014-07-17 07:41:43 +02:00
|
|
|
fetchRange:
|
2014-03-24 19:29:50 +01:00
|
|
|
for minBlock < maxBlock {
|
2014-02-19 00:23:33 +01:00
|
|
|
hashList, err := db.FetchHeightRange(minBlock, maxBlock)
|
|
|
|
if err != nil {
|
|
|
|
rpcsLog.Errorf("Error looking up block range: %v", err)
|
2015-02-21 05:34:57 +01:00
|
|
|
return nil, &btcjson.RPCError{
|
|
|
|
Code: btcjson.ErrRPCDatabase,
|
|
|
|
Message: "Database error: " + err.Error(),
|
|
|
|
}
|
2014-02-19 00:23:33 +01:00
|
|
|
}
|
|
|
|
if len(hashList) == 0 {
|
2015-02-19 20:51:44 +01:00
|
|
|
// The rescan is finished if no blocks hashes for this
|
|
|
|
// range were successfully fetched and a stop block
|
|
|
|
// was provided.
|
|
|
|
if maxBlock != database.AllShas {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
|
|
|
|
// If the rescan is through the current block, set up
|
|
|
|
// the client to continue to receive notifications
|
|
|
|
// regarding all rescanned addresses and the current set
|
|
|
|
// of unspent outputs.
|
|
|
|
//
|
|
|
|
// This is done safely by temporarily grabbing exclusive
|
|
|
|
// access of the block manager. If no more blocks have
|
|
|
|
// been attached between this pause and the fetch above,
|
|
|
|
// then it is safe to register the websocket client for
|
|
|
|
// continuous notifications if necessary. Otherwise,
|
|
|
|
// continue the fetch loop again to rescan the new
|
|
|
|
// blocks (or error due to an irrecoverable reorganize).
|
|
|
|
pauseGuard := wsc.server.server.blockManager.Pause()
|
|
|
|
curHash, _, err := db.NewestSha()
|
|
|
|
again := true
|
|
|
|
if err == nil && (lastBlockHash == nil || *lastBlockHash == *curHash) {
|
|
|
|
again = false
|
|
|
|
n := wsc.server.ntfnMgr
|
|
|
|
n.RegisterSpentRequests(wsc, lookups.unspentSlice())
|
|
|
|
n.RegisterTxOutAddressRequests(wsc, cmd.Addresses)
|
|
|
|
}
|
|
|
|
close(pauseGuard)
|
|
|
|
if err != nil {
|
|
|
|
rpcsLog.Errorf("Error fetching best block "+
|
|
|
|
"hash: %v", err)
|
2015-02-21 05:34:57 +01:00
|
|
|
return nil, &btcjson.RPCError{
|
|
|
|
Code: btcjson.ErrRPCDatabase,
|
|
|
|
Message: "Database error: " +
|
|
|
|
err.Error(),
|
|
|
|
}
|
2015-02-19 20:51:44 +01:00
|
|
|
}
|
|
|
|
if again {
|
|
|
|
continue
|
|
|
|
}
|
2014-02-19 00:23:33 +01:00
|
|
|
break
|
|
|
|
}
|
|
|
|
|
2014-07-17 07:41:43 +02:00
|
|
|
loopHashList:
|
2014-02-19 00:23:33 +01:00
|
|
|
for i := range hashList {
|
|
|
|
blk, err := db.FetchBlockBySha(&hashList[i])
|
|
|
|
if err != nil {
|
2014-07-17 07:41:43 +02:00
|
|
|
// Only handle reorgs if a block could not be
|
|
|
|
// found for the hash.
|
2015-01-27 22:38:23 +01:00
|
|
|
if err != database.ErrBlockShaMissing {
|
2014-07-17 07:41:43 +02:00
|
|
|
rpcsLog.Errorf("Error looking up "+
|
|
|
|
"block: %v", err)
|
2015-02-21 05:34:57 +01:00
|
|
|
return nil, &btcjson.RPCError{
|
|
|
|
Code: btcjson.ErrRPCDatabase,
|
|
|
|
Message: "Database error: " +
|
|
|
|
err.Error(),
|
|
|
|
}
|
2014-07-17 07:41:43 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// If an absolute max block was specified, don't
|
|
|
|
// attempt to handle the reorg.
|
2015-01-27 22:38:23 +01:00
|
|
|
if maxBlock != database.AllShas {
|
2014-07-17 07:41:43 +02:00
|
|
|
rpcsLog.Errorf("Stopping rescan for "+
|
|
|
|
"reorged block %v",
|
|
|
|
cmd.EndBlock)
|
|
|
|
return nil, &ErrRescanReorg
|
|
|
|
}
|
|
|
|
|
|
|
|
// If the lookup for the previously valid block
|
|
|
|
// hash failed, there may have been a reorg.
|
|
|
|
// Fetch a new range of block hashes and verify
|
|
|
|
// that the previously processed block (if there
|
|
|
|
// was any) still exists in the database. If it
|
|
|
|
// doesn't, we error.
|
|
|
|
//
|
|
|
|
// A goto is used to branch executation back to
|
|
|
|
// before the range was evaluated, as it must be
|
|
|
|
// reevaluated for the new hashList.
|
2015-08-08 04:20:49 +02:00
|
|
|
minBlock += int32(i)
|
2015-02-21 05:34:57 +01:00
|
|
|
hashList, err = recoverFromReorg(db, minBlock,
|
2015-02-19 20:51:44 +01:00
|
|
|
maxBlock, lastBlockHash)
|
2015-02-21 05:34:57 +01:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
2014-07-17 07:41:43 +02:00
|
|
|
}
|
|
|
|
if len(hashList) == 0 {
|
|
|
|
break fetchRange
|
|
|
|
}
|
|
|
|
goto loopHashList
|
|
|
|
}
|
2015-02-19 20:51:44 +01:00
|
|
|
if i == 0 && lastBlockHash != nil {
|
2014-07-17 07:41:43 +02:00
|
|
|
// Ensure the new hashList is on the same fork
|
|
|
|
// as the last block from the old hashList.
|
2015-02-19 20:51:44 +01:00
|
|
|
jsonErr := descendantBlock(lastBlockHash, blk)
|
2014-07-17 07:41:43 +02:00
|
|
|
if jsonErr != nil {
|
|
|
|
return nil, jsonErr
|
|
|
|
}
|
2014-02-19 00:23:33 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// A select statement is used to stop rescans if the
|
|
|
|
// client requesting the rescan has disconnected.
|
|
|
|
select {
|
|
|
|
case <-wsc.quit:
|
2014-03-24 19:29:50 +01:00
|
|
|
rpcsLog.Debugf("Stopped rescan at height %v "+
|
|
|
|
"for disconnected client", blk.Height())
|
2014-02-19 00:23:33 +01:00
|
|
|
return nil, nil
|
|
|
|
default:
|
2014-03-21 14:25:00 +01:00
|
|
|
rescanBlock(wsc, &lookups, blk)
|
2014-07-17 07:41:43 +02:00
|
|
|
lastBlock = blk
|
2015-04-17 07:44:15 +02:00
|
|
|
lastBlockHash = blk.Sha()
|
2014-02-08 23:15:17 +01:00
|
|
|
}
|
2014-02-19 00:23:33 +01:00
|
|
|
|
2014-03-24 19:29:50 +01:00
|
|
|
// Periodically notify the client of the progress
|
|
|
|
// completed. Continue with next block if no progress
|
|
|
|
// notification is needed yet.
|
|
|
|
select {
|
|
|
|
case <-ticker.C: // fallthrough
|
|
|
|
default:
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2015-02-21 05:34:57 +01:00
|
|
|
n := btcjson.NewRescanProgressNtfn(hashList[i].String(),
|
2014-07-17 07:41:43 +02:00
|
|
|
int32(blk.Height()),
|
|
|
|
blk.MsgBlock().Header.Timestamp.Unix())
|
2015-02-21 05:34:57 +01:00
|
|
|
mn, err := btcjson.MarshalCmd(nil, n)
|
2014-03-24 19:29:50 +01:00
|
|
|
if err != nil {
|
|
|
|
rpcsLog.Errorf("Failed to marshal rescan "+
|
|
|
|
"progress notification: %v", err)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
if err = wsc.QueueNotification(mn); err == ErrClientQuit {
|
|
|
|
// Finished if the client disconnected.
|
|
|
|
rpcsLog.Debugf("Stopped rescan at height %v "+
|
|
|
|
"for disconnected client", blk.Height())
|
|
|
|
return nil, nil
|
|
|
|
}
|
2014-02-19 00:23:33 +01:00
|
|
|
}
|
2014-03-24 19:29:50 +01:00
|
|
|
|
2015-08-08 04:20:49 +02:00
|
|
|
minBlock += int32(len(hashList))
|
2014-02-08 23:15:17 +01:00
|
|
|
}
|
2014-02-19 00:23:33 +01:00
|
|
|
|
2014-06-16 16:57:20 +02:00
|
|
|
// Notify websocket client of the finished rescan. Due to how btcd
|
|
|
|
// asynchronously queues notifications to not block calling code,
|
|
|
|
// there is no guarantee that any of the notifications created during
|
|
|
|
// rescan (such as rescanprogress, recvtx and redeemingtx) will be
|
|
|
|
// received before the rescan RPC returns. Therefore, another method
|
2015-02-19 20:51:44 +01:00
|
|
|
// is needed to safely inform clients that all rescan notifications have
|
2014-06-16 16:57:20 +02:00
|
|
|
// been sent.
|
2015-02-21 05:34:57 +01:00
|
|
|
n := btcjson.NewRescanFinishedNtfn(lastBlockHash.String(),
|
2014-07-17 07:41:43 +02:00
|
|
|
int32(lastBlock.Height()),
|
|
|
|
lastBlock.MsgBlock().Header.Timestamp.Unix())
|
2015-02-21 05:34:57 +01:00
|
|
|
if mn, err := btcjson.MarshalCmd(nil, n); err != nil {
|
2014-06-16 16:57:20 +02:00
|
|
|
rpcsLog.Errorf("Failed to marshal rescan finished "+
|
|
|
|
"notification: %v", err)
|
|
|
|
} else {
|
|
|
|
// The rescan is finished, so we don't care whether the client
|
|
|
|
// has disconnected at this point, so discard error.
|
|
|
|
_ = wsc.QueueNotification(mn)
|
|
|
|
}
|
|
|
|
|
2014-02-19 00:23:33 +01:00
|
|
|
rpcsLog.Info("Finished rescan")
|
|
|
|
return nil, nil
|
2014-02-08 23:15:17 +01:00
|
|
|
}
|
2015-02-21 05:34:57 +01:00
|
|
|
|
|
|
|
func init() {
|
|
|
|
wsHandlers = wsHandlersBeforeInit
|
|
|
|
}
|