Files
lightwalletd/frontend/service.go
T
DanSandClaude Opus 4.8 cbda810849 frontend: guard nil Block in GetTransaction (empty TxFilter crash)
An empty TxFilter (Hash==nil, Block==nil) fell through to 'if txf.Block.Hash'
which dereferenced a nil Block and panicked the server (grpc-go v1.24.0 has no
handler recover) -- one unauthenticated request killed the process. Guard
txf.Block before dereferencing and return InvalidArgument for a request that
carries neither a txid nor a usable block filter.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-30 10:39:41 -05:00

412 lines
14 KiB
Go

package frontend
import (
"context"
"encoding/hex"
"encoding/json"
"errors"
"regexp"
"strconv"
"strings"
"time"
"github.com/btcsuite/btcd/rpcclient"
"github.com/sirupsen/logrus"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"git.hush.is/hush/lightwalletd/common"
"git.hush.is/hush/lightwalletd/walletrpc"
)
var (
ErrUnspecified = errors.New("request for unspecified identifier")
)
// the service type
type SqlStreamer struct {
cache *common.BlockCache
client *rpcclient.Client
log *logrus.Entry
}
func NewSQLiteStreamer(client *rpcclient.Client, cache *common.BlockCache, log *logrus.Entry) (walletrpc.CompactTxStreamerServer, error) {
return &SqlStreamer{cache, client, log}, nil
}
func (s *SqlStreamer) GracefulStop() error {
return nil
}
func (s *SqlStreamer) GetCache() *common.BlockCache {
return s.cache
}
func (s *SqlStreamer) GetLatestBlock(ctx context.Context, placeholder *walletrpc.ChainSpec) (*walletrpc.BlockID, error) {
latestBlock := s.cache.GetLatestBlock()
s.log.WithFields(logrus.Fields{
"latestBlock": latestBlock,
}).Info("GetLatestBlock called")
if latestBlock == -1 {
return nil, errors.New("Cache is empty. Server is probably not yet ready.")
}
// TODO: also return block hashes here
return &walletrpc.BlockID{Height: uint64(latestBlock)}, nil
}
func (s *SqlStreamer) GetAddressTxids(addressBlockFilter *walletrpc.TransparentAddressBlockFilter, resp walletrpc.CompactTxStreamer_GetAddressTxidsServer) error {
var err error
var errCode int64
// Test to make sure Address is a single t address
match, err := regexp.Match("^R[a-zA-Z0-9]{33}$", []byte(addressBlockFilter.Address))
if err != nil || !match {
s.log.Errorf("Unrecognized address: %s", addressBlockFilter.Address)
return nil
}
// Reject a missing range before dereferencing it (same nil-panic class as
// GetBlockRange) and bound the span.
if addressBlockFilter.Range == nil || addressBlockFilter.Range.Start == nil || addressBlockFilter.Range.End == nil {
return status.Error(codes.InvalidArgument, "GetAddressTxids: missing range (Start and End are required)")
}
if addressBlockFilter.Range.End.Height < addressBlockFilter.Range.Start.Height {
return status.Error(codes.InvalidArgument, "GetAddressTxids: end height is below start height")
}
if addressBlockFilter.Range.End.Height-addressBlockFilter.Range.Start.Height+1 > maxBlockRangeSpan {
return status.Errorf(codes.InvalidArgument, "GetAddressTxids: span exceeds the maximum of %d blocks", maxBlockRangeSpan)
}
params := make([]json.RawMessage, 1)
st := "{\"addresses\": [\"" + addressBlockFilter.Address + "\"]," +
"\"start\": " + strconv.FormatUint(addressBlockFilter.Range.Start.Height, 10) +
", \"end\": " + strconv.FormatUint(addressBlockFilter.Range.End.Height, 10) + "}"
params[0] = json.RawMessage(st)
result, rpcErr := s.client.RawRequest("getaddresstxids", params)
// For some reason, the error responses are not JSON
if rpcErr != nil {
s.log.Errorf("Got error: %s", rpcErr.Error())
errParts := strings.SplitN(rpcErr.Error(), ":", 2)
errCode, err = strconv.ParseInt(errParts[0], 10, 32)
//Check to see if we are requesting a height the dragonxd doesn't have yet
if err == nil && errCode == -8 {
return nil
}
return nil
}
var txids []string
err = json.Unmarshal(result, &txids)
if err != nil {
s.log.Errorf("Got error: %s", err.Error())
return nil
}
timeout, cancel := context.WithTimeout(resp.Context(), 30*time.Second)
defer cancel()
for _, txidstr := range txids {
txid, _ := hex.DecodeString(txidstr)
// Txid is read as a string, which is in big-endian order. But when converting
// to bytes, it should be little-endian
for left, right := 0, len(txid)-1; left < right; left, right = left+1, right-1 {
txid[left], txid[right] = txid[right], txid[left]
}
tx, err := s.GetTransaction(timeout, &walletrpc.TxFilter{Hash: txid})
if err != nil {
s.log.Errorf("Got error: %s", err.Error())
return nil
}
resp.Send(tx)
}
return nil
}
func (s *SqlStreamer) GetBlock(ctx context.Context, id *walletrpc.BlockID) (*walletrpc.CompactBlock, error) {
if id.Height == 0 && id.Hash == nil {
return nil, ErrUnspecified
}
// Precedence: a hash is more specific than a height. If we have it, use it first.
if id.Hash != nil {
// TODO: Get block by hash
return nil, errors.New("GetBlock by Hash is not yet implemented")
} else {
cBlock, err := common.GetBlock(s.client, s.cache, int(id.Height))
if err != nil {
return nil, err
}
return cBlock, err
}
}
// maxBlockRangeSpan bounds how many blocks one GetBlockRange / GetAddressTxids
// request may walk. Honest wallet syncs are far below this; the cap stops an
// attacker-sized request from driving one backend RPC per uncached height.
const maxBlockRangeSpan = 10000
func (s *SqlStreamer) GetBlockRange(span *walletrpc.BlockRange, resp walletrpc.CompactTxStreamer_GetBlockRangeServer) error {
// Reject a missing range before dereferencing it. An empty BlockRange
// (nil Start/End) would otherwise nil-panic and take the whole process
// down, since grpc-go does not recover handler panics per call.
if span == nil || span.Start == nil || span.End == nil {
return status.Error(codes.InvalidArgument, "GetBlockRange: missing range (Start and End are required)")
}
start, end := int(span.Start.Height), int(span.End.Height)
if end < start {
return status.Error(codes.InvalidArgument, "GetBlockRange: end height is below start height")
}
if end-start+1 > maxBlockRangeSpan {
return status.Errorf(codes.InvalidArgument, "GetBlockRange: span of %d blocks exceeds the maximum of %d", end-start+1, maxBlockRangeSpan)
}
s.log.WithFields(logrus.Fields{
"start": span.Start.Height,
"end": span.End.Height,
}).Info("GetBlockRange called")
blockChan := make(chan walletrpc.CompactBlock)
errChan := make(chan error)
go common.GetBlockRange(s.client, s.cache, blockChan, errChan, start, end)
blockCount := 0
for {
select {
case err := <-errChan:
if err != nil {
s.log.WithFields(logrus.Fields{
"start": span.Start.Height,
"end": span.End.Height,
"blocksSent": blockCount,
"error": err,
}).Error("GetBlockRange error")
} else {
s.log.WithFields(logrus.Fields{
"start": span.Start.Height,
"end": span.End.Height,
"blocksSent": blockCount,
}).Info("GetBlockRange completed")
}
return err
case cBlock := <-blockChan:
err := resp.Send(&cBlock)
if err != nil {
s.log.WithFields(logrus.Fields{
"start": span.Start.Height,
"end": span.End.Height,
"blocksSent": blockCount,
"error": err,
}).Error("GetBlockRange send error")
return err
}
blockCount++
}
}
return nil
}
func (s *SqlStreamer) GetTransaction(ctx context.Context, txf *walletrpc.TxFilter) (*walletrpc.RawTransaction, error) {
var txBytes []byte
var txHeight float64
if txf.Hash != nil {
txid := txf.Hash
for left, right := 0, len(txid)-1; left < right; left, right = left+1, right-1 {
txid[left], txid[right] = txid[right], txid[left]
}
leHashString := hex.EncodeToString(txid)
// First call to get the raw transaction bytes
params := make([]json.RawMessage, 1)
params[0] = json.RawMessage("\"" + leHashString + "\"")
result, rpcErr := s.client.RawRequest("getrawtransaction", params)
var err error
// For some reason, the error responses are not JSON
if rpcErr != nil {
s.log.Errorf("Got error: %s", rpcErr.Error())
errParts := strings.SplitN(rpcErr.Error(), ":", 2)
parsedCode, parseErr := strconv.ParseInt(errParts[0], 10, 32)
// -5 (RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction")
// and -8 (a height the node doesn't have yet) both mean the transaction is not
// available -> NotFound, so a client can tell it apart from a server failure.
// Return a real gRPC status instead of the parsed-away (nil) error, which would
// otherwise marshal a typed nil and surface to the client as Internal.
if parseErr == nil && (parsedCode == -5 || parsedCode == -8) {
return nil, status.Error(codes.NotFound, "transaction not found")
}
return nil, status.Errorf(codes.Internal, "backend RPC error: %s", rpcErr.Error())
}
var txhex string
err = json.Unmarshal(result, &txhex)
if err != nil {
return nil, err
}
txBytes, err = hex.DecodeString(txhex)
if err != nil {
return nil, err
}
// Second call to get height
params = make([]json.RawMessage, 2)
params[0] = json.RawMessage("\"" + leHashString + "\"")
params[1] = json.RawMessage("1")
result, rpcErr = s.client.RawRequest("getrawtransaction", params)
// For some reason, the error responses are not JSON
if rpcErr != nil {
s.log.Errorf("Got error: %s", rpcErr.Error())
errParts := strings.SplitN(rpcErr.Error(), ":", 2)
parsedCode, parseErr := strconv.ParseInt(errParts[0], 10, 32)
// -5 (RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction")
// and -8 (a height the node doesn't have yet) both mean the transaction is not
// available -> NotFound, so a client can tell it apart from a server failure.
// Return a real gRPC status instead of the parsed-away (nil) error, which would
// otherwise marshal a typed nil and surface to the client as Internal.
if parseErr == nil && (parsedCode == -5 || parsedCode == -8) {
return nil, status.Error(codes.NotFound, "transaction not found")
}
return nil, status.Errorf(codes.Internal, "backend RPC error: %s", rpcErr.Error())
}
var txinfo interface{}
err = json.Unmarshal(result, &txinfo)
if err != nil {
return nil, err
}
txHeight = txinfo.(map[string]interface{})["height"].(float64)
return &walletrpc.RawTransaction{Data: txBytes, Height: uint64(txHeight)}, nil
}
// txf.Block may be nil (an empty TxFilter); guard it before dereferencing, or a single
// empty request panics the server (grpc-go v1.24.0 has no handler recover).
if txf.Block != nil && txf.Block.Hash != nil {
s.log.Error("Can't GetTransaction with a blockhash+num. Please call GetTransaction with txid")
return nil, status.Error(codes.InvalidArgument, "Can't GetTransaction with a blockhash+num. Please call GetTransaction with txid")
}
// Neither a txid (Hash) nor a usable block filter was supplied.
return nil, status.Error(codes.InvalidArgument, "GetTransaction: a txid (Hash) is required")
}
// GetLightdInfo gets the LightWalletD (this server) info
func (s *SqlStreamer) GetLightdInfo(ctx context.Context, in *walletrpc.Empty) (*walletrpc.LightdInfo, error) {
saplingHeight, blockHeight, chainName, consensusBranchId, difficulty, longestchain, notarized, err := common.GetSaplingInfo(s.client)
s.log.WithFields(logrus.Fields{
"saplingHeight": saplingHeight,
"blockHeight": blockHeight,
"chainName": chainName,
"consensusBranchId": consensusBranchId,
}).Info("GetLightdInfo called")
if err != nil {
s.log.WithFields(logrus.Fields{
"error": err,
}).Warn("Unable to get sapling activation height")
return nil, err
}
// TODO these are called Error but they aren't at the moment.
// A success will return code 0 and message txhash.
return &walletrpc.LightdInfo{
Version: "0.1.1-dragonxlightd",
Vendor: "DragonX LightWalletD",
TaddrSupport: true,
ChainName: chainName,
SaplingActivationHeight: uint64(saplingHeight),
ConsensusBranchId: consensusBranchId,
BlockHeight: uint64(blockHeight),
Difficulty: uint64(difficulty),
Longestchain: uint64(longestchain),
Notarized: uint64(notarized),
}, nil
}
// GetCoinsupply gets the Coinsupply info
func (s *SqlStreamer) GetCoinsupply(ctx context.Context, in *walletrpc.Empty) (*walletrpc.Coinsupply, error) {
result, coin, height, supply, zfunds, total, err := common.GetCoinsupply(s.client)
if err != nil {
s.log.WithFields(logrus.Fields{
"error": err,
}).Warn("Unable to get Coinsupply")
return nil, err
}
// TODO these are called Error but they aren't at the moment.
// A success will return code 0 and message txhash.
return &walletrpc.Coinsupply{
Result: result,
Coin: coin,
Height: uint64(height),
Supply: uint64(supply),
Zfunds: uint64(zfunds),
Total: uint64(total),
}, nil
}
// SendTransaction forwards raw transaction bytes to a dragonxd instance over JSON-RPC
func (s *SqlStreamer) SendTransaction(ctx context.Context, rawtx *walletrpc.RawTransaction) (*walletrpc.SendResponse, error) {
// sendrawtransaction "hexstring" ( allowhighfees )
//
// Submits raw transaction (serialized, hex-encoded) to local node and network.
//
// Also see createrawtransaction and signrawtransaction calls.
//
// Arguments:
// 1. "hexstring" (string, required) The hex string of the raw transaction)
// 2. allowhighfees (boolean, optional, default=false) Allow high fees
//
// Result:
// "hex" (string) The transaction hash in hex
// Construct raw JSON-RPC params
params := make([]json.RawMessage, 1)
txHexString := hex.EncodeToString(rawtx.Data)
params[0] = json.RawMessage("\"" + txHexString + "\"")
result, rpcErr := s.client.RawRequest("sendrawtransaction", params)
var err error
var errCode int64
var errMsg string
// For some reason, the error responses are not JSON
if rpcErr != nil {
errParts := strings.SplitN(rpcErr.Error(), ":", 2)
errMsg = strings.TrimSpace(errParts[1])
errCode, err = strconv.ParseInt(errParts[0], 10, 32)
if err != nil {
// This should never happen. We can't panic here, but it's that class of error.
// This is why we need integration testing to work better than regtest currently does. TODO.
return nil, errors.New("SendTransaction couldn't parse error code")
}
} else {
errMsg = string(result)
}
// TODO these are called Error but they aren't at the moment.
// A success will return code 0 and message txhash.
return &walletrpc.SendResponse{
ErrorCode: int32(errCode),
ErrorMessage: errMsg,
}, nil
}