Skip to content
Merged
72 changes: 72 additions & 0 deletions cmd/htnwallet/daemon/server/address_listing_slots_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ package server

import (
"context"
"fmt"
"runtime"
"strings"
"testing"
"time"

Expand All @@ -13,6 +16,8 @@ import (
"github.com/HoosatNetwork/HTND/v2/infrastructure/network/netadapter/server/grpcserver/protowire"
"github.com/HoosatNetwork/HTND/v2/infrastructure/network/rpcclient"
"github.com/HoosatNetwork/HTND/v2/version"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)

func TestShowAddressesWithOccupiedNodeSlots(t *testing.T) {
Expand Down Expand Up @@ -72,3 +77,70 @@ func TestShowAddressesWithOccupiedNodeSlots(t *testing.T) {
t.Fatalf("explicit listing with both node slots occupied: %v, %v", addresses, err)
}
}

// A canceled listing's worker can keep the DAG-info route for up to 30 s. GetBalance must wait for the
// route before it takes s.lock, or NewAddress, which needs the write lock, waits with it. A caller that
// cancels stops waiting.
func TestGetBalanceWaitsForDAGInfoOutsideWalletLock(t *testing.T) {
for _, cancelRequest := range []bool{false, true} {
t.Run(fmt.Sprintf("canceled=%t", cancelRequest), func(t *testing.T) {
node := &usableAddressesNode{usable: map[string]bool{}}
s := newRescanTestServer(t, node, 0, 0)
s.rpcClient = usableAddressesNodeClient(t, node)
address := rescanTestAddress(external, 1)
node.pay(address)
s.addressSet[address] = &walletAddress{index: 1, keyChain: external}
s.nextSyncStartIndex = 1000
s.firstSyncDone.Store(true)

s.dagInfoRequests.init.Do(func() { s.dagInfoRequests.active = make(chan struct{}, 1) })
s.dagInfoRequests.active <- struct{}{} // the canceled listing's worker
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
done := make(chan error, 1)
go func() {
_, err := s.GetBalance(ctx, &pb.GetBalanceRequest{})
done <- err
}()
waitUntilGoroutineIn(t, "(*server).getBlockDAGInfo")
select {
case err := <-done:
t.Fatalf("GetBalance returned while the route was held: %v", err)
default:
}
if !s.lock.TryLock() {
t.Fatal("GetBalance held the wallet lock while it waited for the DAG-info route")
}
s.lock.Unlock()
if cancelRequest {
cancel()
select {
case err := <-done:
if status.Code(err) != codes.Canceled {
t.Fatalf("canceled GetBalance returned %v, want Canceled", err)
}
case <-time.After(5 * time.Second):
t.Fatal("GetBalance kept waiting for the route after its caller canceled")
}
<-s.dagInfoRequests.active
return
}
<-s.dagInfoRequests.active // the worker finishes
if err := <-done; err != nil {
t.Fatalf("GetBalance: %v", err)
}
})
}
}

// waitUntilGoroutineIn waits until some goroutine's stack contains function.
func waitUntilGoroutineIn(t *testing.T, function string) {
t.Helper()
buffer := make([]byte, 1<<20)
for deadline := time.Now().Add(10 * time.Second); time.Now().Before(deadline); time.Sleep(5 * time.Millisecond) {
if strings.Contains(string(buffer[:runtime.Stack(buffer, true)]), function) {
return
}
}
t.Fatalf("no goroutine reached %s", function)
}
14 changes: 9 additions & 5 deletions cmd/htnwallet/daemon/server/balance.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,15 @@ type (
// address before ML-DSA-44 is active (see isAddressSpendableAt). The total per address comes from the
// node's balance index. The full balance of a locked address is pending; other addresses use their UTXOs
// to account for coin maturity.
func (s *server) GetBalance(_ context.Context, _ *pb.GetBalanceRequest) (*pb.GetBalanceResponse, error) {
func (s *server) GetBalance(ctx context.Context, _ *pb.GetBalanceRequest) (*pb.GetBalanceResponse, error) {
// Wait for the shared DAG-info route before taking s.lock, so writers are not held behind it.
// An older DAA score only keeps more coins pending. The wait ends when the caller cancels.
dagInfoCtx, cancel := context.WithTimeout(ctx, maxAddressListingRPCTimeout)
defer cancel()
dagInfo, err := s.getBlockDAGInfo(dagInfoCtx)
if err != nil {
return nil, err
}
s.lock.RLock()
defer s.lock.RUnlock()

Expand All @@ -46,10 +54,6 @@ func (s *server) GetBalance(_ context.Context, _ *pb.GetBalanceRequest) (*pb.Get
}

if len(balancesMap) > 0 {
dagInfo, err := s.getBlockDAGInfo(context.Background())
if err != nil {
return nil, err
}
getUTXOsByAddressesResponse, err := s.rpcClient.GetUTXOsByAddresses(addresses, 0)
if err != nil {
return nil, err
Expand Down
7 changes: 4 additions & 3 deletions cmd/htnwallet/daemon/server/create_unsigned_transaction.go
Original file line number Diff line number Diff line change
Expand Up @@ -359,15 +359,16 @@ func (s *server) trackCompoundDestination(address util.Address) error {
}

// A cosigner can supply an empty address past this daemon's last-used index. Record it
// now so recent or old address scans can find the output even after a restart.
// now so recent or old address scans can find the output even after a restart. A failed
// save leaves the index unrecorded, so a retry saves it again.
external, internal := s.lastUsedIndexes()
if path.keyChain == libhtnwallet.ExternalKeychain && path.index > external {
if err := s.keysFile.SetLastUsedExternalIndex(path.index); err != nil {
if err := s.keysFile.ReserveExternalIndex(path.index); err != nil {
return err
}
}
if path.keyChain == libhtnwallet.InternalKeychain && path.index > internal {
if err := s.keysFile.SetLastUsedInternalIndex(path.index); err != nil {
if err := s.keysFile.ReserveInternalIndex(path.index); err != nil {
return err
}
}
Expand Down
37 changes: 19 additions & 18 deletions cmd/htnwallet/daemon/server/sync.go
Original file line number Diff line number Diff line change
Expand Up @@ -361,21 +361,24 @@ func (s *server) handoffFormerRecentBatches() {
continue
}
delete(s.recentBatchPolls, start)
// Keep the handoff and any ordinary old re-check. Each has its own
// deadline and a scan at or past both can satisfy them together.
pending := slices.IndexFunc(s.oldBatchRechecks, func(recheck oldBatchRecheck) bool {
return recheck.start == start && recheck.handedOff
})
if pending >= 0 {
if !poll.next.Before(s.oldBatchRechecks[pending].notBefore) {
continue
// Hand off the poll's next time, for addresses the node checked early in a slow poll, and
// its later verification deadline, for those it checked late. Each stays queued, next to any
// ordinary old re-check, until a scan that starts at or after it.
deadlines := []time.Time{poll.next}
if poll.verifyUntil.After(poll.next) {
deadlines = append(deadlines, poll.verifyUntil)
}
for _, deadline := range deadlines {
if slices.ContainsFunc(s.oldBatchRechecks, func(recheck oldBatchRecheck) bool {
return recheck.start == start && recheck.handedOff && recheck.notBefore.Equal(deadline)
}) {
continue // the same obligation is already queued
}
s.oldBatchRechecks = slices.Delete(s.oldBatchRechecks, pending, pending+1)
at := sort.Search(len(s.oldBatchRechecks), func(i int) bool {
return !s.oldBatchRechecks[i].notBefore.Before(deadline)
})
s.oldBatchRechecks = slices.Insert(s.oldBatchRechecks, at, oldBatchRecheck{start: start, notBefore: deadline, handedOff: true})
}
at := sort.Search(len(s.oldBatchRechecks), func(i int) bool {
return !s.oldBatchRechecks[i].notBefore.Before(poll.next)
})
s.oldBatchRechecks = slices.Insert(s.oldBatchRechecks, at, oldBatchRecheck{start: start, notBefore: poll.next, handedOff: true})
}
}

Expand Down Expand Up @@ -438,11 +441,9 @@ func (s *server) collectNextOldBatch() (scanned bool, err error) {
return false, err
}
s.nextRescanIndex = start + numIndexesToQueryForRecentAddresses
// Replace any ordinary re-check from the previous round. Keep a handed-off
// poll if this scan started too early to satisfy it.
s.oldBatchRechecks = slices.DeleteFunc(s.oldBatchRechecks, func(recheck oldBatchRecheck) bool {
return recheck.start == start && (!recheck.handedOff || !requestStarted.Before(recheck.notBefore))
})
// This scan satisfies only the re-checks already due when it started. One due later stays:
// this scan can be served the cached answer that re-check waits out.
s.finishBatchRechecks(start, requestStarted)
s.oldBatchRechecks = append(s.oldBatchRechecks, oldBatchRecheck{start: start, notBefore: s.clock().Add(oldBatchRecheckDelay)})
return true, nil
}
Expand Down
58 changes: 58 additions & 0 deletions cmd/htnwallet/daemon/server/sync_recent_handoff_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,3 +48,61 @@ func TestOldCursorKeepsPendingRecentHandoff(t *testing.T) {
})
}
}

// A batch that leaves the recent window during a slow poll's verification hands off both deadlines: the
// poll's next time finds a coin at an address the node checked early, and the verification deadline one
// at an address it checked late, past that check's cache entry.
func TestHandoffKeepsSlowPollDeadlines(t *testing.T) {
for _, tc := range []struct {
name string
check time.Duration
wantTick int
}{
{name: "early check", check: 0, wantTick: 32},
{name: "late check", check: 4 * time.Second, wantTick: 36},
} {
t.Run(tc.name, func(t *testing.T) {
node := newRecentTestNode()
s := newRescanTestServer(t, node, 6500, 22000)
collectRecentAt(t, s, node, -32*time.Second)
node.asked()

// Slow poll at t=0. Batch 5000 is the first batch polled: the node checks
// its addresses at tc.check and the reply arrives at t=5.
node.setCheckTime(recentTestEpoch.Add(tc.check))
s.now = func() time.Time {
node.mu.Lock()
defer node.mu.Unlock()
if node.calls == 0 {
return recentTestEpoch
}
return recentTestEpoch.Add(5 * time.Second)
}
mustCollectRecent(t, s)
poll := s.recentBatchPolls[5000]
if !poll.next.Equal(recentTestEpoch.Add(32*time.Second)) || !poll.verifyUntil.After(recentTestEpoch.Add(34*time.Second)) {
t.Fatalf("setup: batch 5000 poll = %+v, want next 32 s and verifyUntil past 34 s", poll)
}

address := rescanTestAddress(external, 5050)
node.pay(address) // after the node's negative, which it serves for 30 s
s.nextRescanIndex = 16000
s.rescanRoundEnd = 23000
if err := s.keysFile.SetLastUsedExternalIndex(8500); err != nil { // batch 5000 leaves the window
t.Fatal(err)
}
var discovered int
for tick := 6; tick <= 60; tick += 2 {
setRecentTestTime(s, node, time.Duration(tick)*time.Second)
mustTick(t, s)
if discovered == 0 && s.addressSet[address] != nil {
discovered = tick
}
}
if discovered != tc.wantTick {
t.Errorf("first discovery at %ds (0 means never), want %ds: the first tick after the negative expired",
discovered, tc.wantTick)
}
})
}
}
12 changes: 12 additions & 0 deletions cmd/htnwallet/daemon/server/sync_recent_regression_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,12 @@ func TestRecentPollAllowsForLateNodeCheck(t *testing.T) {
return recentTestEpoch.Add(3500 * time.Millisecond)
}
mustCollectRecent(t, s)
node.mu.Lock()
entry, cached := node.cache[address]
node.mu.Unlock()
if !cached || entry.usable || !entry.checkedAt.Equal(recentTestEpoch.Add(3*time.Second)) {
t.Fatalf("setup: the node's entry for the target is %+v (cached %t), want a negative checked at t=3", entry, cached)
}
node.pay(address)
collectRecentAt(t, s, node, 32*time.Second)
collectRecentAt(t, s, node, 34*time.Second)
Expand All @@ -68,6 +74,9 @@ func TestRecentSweepRetriesWarmNodeCache(t *testing.T) {
node.askAsAnotherClient(address)
node.pay(address)
collectRecentAt(t, s, node, 0)
if !node.wasAnswered(address) {
t.Fatal("setup: the initial scan did not ask the node about the target")
}
if s.addressSet[address] != nil {
t.Fatal("the initial scan should receive the shared cached negative")
}
Expand Down Expand Up @@ -308,6 +317,9 @@ func TestIncompleteFirstSweepRetriesSuccessfulPrefix(t *testing.T) {
if err := s.collectRecentAddresses(false); err == nil || !strings.Contains(err.Error(), "test scan failure") {
t.Fatalf("first sweep returned %v, want the second batch's RPC failure", err)
}
if !node.wasAnswered(rescanTestAddress(external, 0)) {
t.Fatal("setup: the node did not answer batch 0 before the sweep failed at batch 1000")
}
address := rescanTestAddress(external, 0)
node.pay(address)
node.failScanOf("")
Expand Down
6 changes: 6 additions & 0 deletions cmd/htnwallet/daemon/server/sync_recent_slow_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,12 @@ func TestSlowRecentPollFindsEarlyCheckedAddress(t *testing.T) {
return recentTestEpoch.Add(10 * time.Second)
}
mustCollectRecent(t, s)
node.mu.Lock()
entry, cached := node.cache[address]
node.mu.Unlock()
if !cached || entry.usable || !entry.checkedAt.Equal(recentTestEpoch) {
t.Fatalf("setup: the node's entry for the target is %+v (cached %t), want a negative checked at t=0", entry, cached)
}
node.pay(address)
var firstDiscovery time.Duration
for tick := 12 * time.Second; tick <= 44*time.Second; tick += 2 * time.Second {
Expand Down
Loading
Loading