diff --git a/cmd/htnwallet/daemon/server/address_listing_slots_test.go b/cmd/htnwallet/daemon/server/address_listing_slots_test.go index 6e686e24bc..eca7d37358 100644 --- a/cmd/htnwallet/daemon/server/address_listing_slots_test.go +++ b/cmd/htnwallet/daemon/server/address_listing_slots_test.go @@ -2,6 +2,9 @@ package server import ( "context" + "fmt" + "runtime" + "strings" "testing" "time" @@ -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) { @@ -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) +} diff --git a/cmd/htnwallet/daemon/server/balance.go b/cmd/htnwallet/daemon/server/balance.go index e57084fa33..f4bba99d73 100644 --- a/cmd/htnwallet/daemon/server/balance.go +++ b/cmd/htnwallet/daemon/server/balance.go @@ -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() @@ -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 diff --git a/cmd/htnwallet/daemon/server/create_unsigned_transaction.go b/cmd/htnwallet/daemon/server/create_unsigned_transaction.go index e62c60f07d..d75d89d12d 100644 --- a/cmd/htnwallet/daemon/server/create_unsigned_transaction.go +++ b/cmd/htnwallet/daemon/server/create_unsigned_transaction.go @@ -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 } } diff --git a/cmd/htnwallet/daemon/server/sync.go b/cmd/htnwallet/daemon/server/sync.go index 71e6006bd3..5b1f4de0c8 100644 --- a/cmd/htnwallet/daemon/server/sync.go +++ b/cmd/htnwallet/daemon/server/sync.go @@ -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}) } } @@ -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 } diff --git a/cmd/htnwallet/daemon/server/sync_recent_handoff_test.go b/cmd/htnwallet/daemon/server/sync_recent_handoff_test.go index 609550238e..78e83e91ce 100644 --- a/cmd/htnwallet/daemon/server/sync_recent_handoff_test.go +++ b/cmd/htnwallet/daemon/server/sync_recent_handoff_test.go @@ -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) + } + }) + } +} diff --git a/cmd/htnwallet/daemon/server/sync_recent_regression_test.go b/cmd/htnwallet/daemon/server/sync_recent_regression_test.go index 30845458ef..02824ecfb3 100644 --- a/cmd/htnwallet/daemon/server/sync_recent_regression_test.go +++ b/cmd/htnwallet/daemon/server/sync_recent_regression_test.go @@ -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) @@ -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") } @@ -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("") diff --git a/cmd/htnwallet/daemon/server/sync_recent_slow_test.go b/cmd/htnwallet/daemon/server/sync_recent_slow_test.go index 18186884a0..b173f3107b 100644 --- a/cmd/htnwallet/daemon/server/sync_recent_slow_test.go +++ b/cmd/htnwallet/daemon/server/sync_recent_slow_test.go @@ -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 { diff --git a/cmd/htnwallet/daemon/server/sync_rescan_test.go b/cmd/htnwallet/daemon/server/sync_rescan_test.go index 3fb5f7a207..658162a44d 100644 --- a/cmd/htnwallet/daemon/server/sync_rescan_test.go +++ b/cmd/htnwallet/daemon/server/sync_rescan_test.go @@ -30,6 +30,7 @@ type usableAddressesNode struct { calls int addresses int failAddress string + answered map[string]bool // addresses in GetUsableAddresses requests the node answered // When cacheTTL is set, each address's answer is kept for cacheTTL as the node does, on the clock now. cacheTTL time.Duration @@ -137,7 +138,11 @@ func (n *usableAddressesNode) MessageStream(stream protowire.RPC_MessageStreamSe response = &appmessage.GetUsableAddressesResponseMessage{Error: appmessage.RPCErrorf("test scan failure")} break } + if n.answered == nil { + n.answered = make(map[string]bool) + } for _, address := range message.Addresses { + n.answered[address] = true if n.isUsable(address) { usable = append(usable, address) } @@ -157,6 +162,13 @@ func (n *usableAddressesNode) MessageStream(stream protowire.RPC_MessageStreamSe } } +// wasAnswered reports whether the node answered a GetUsableAddresses request that held the address. +func (n *usableAddressesNode) wasAnswered(address string) bool { + n.mu.Lock() + defer n.mu.Unlock() + return n.answered[address] +} + // pay makes the addresses hold a coin. func (n *usableAddressesNode) pay(addresses ...string) { n.mu.Lock() @@ -572,6 +584,9 @@ func TestStaleNegativeAnswerIsRechecked(t *testing.T) { client := s.backgroundRPCClient s.backgroundRPCClient = closedRPCClient(t) queued := len(s.oldBatchRechecks) + if queued == 0 || s.oldBatchRechecks[0].start != 3000 { + t.Fatalf("the re-check of the batch at 3000 is not first in the queue: %+v", s.oldBatchRechecks) + } sync() if len(s.oldBatchRechecks) != queued || s.oldBatchRechecks[0].start != 3000 { t.Fatalf("a skipped re-check changed the queue from %d to %d entries", queued, len(s.oldBatchRechecks)) @@ -586,6 +601,36 @@ func TestStaleNegativeAnswerIsRechecked(t *testing.T) { now.Sub(staleScan), oldBatchRecheckDelay) } +// A round that comes back to a batch before its re-check is due can be served the answer the re-check waits +// out, so it must not move the re-check later. +func TestOldCursorRevisitKeepsPendingRecheck(t *testing.T) { + node := newRecentTestNode() + s := newRescanTestServer(t, node, 4500, 20) + collectRecentAt(t, s, node, -32*time.Second) // the first sweep + address := rescanTestAddress(external, 2050) + scanOldBatchAt := func(elapsed time.Duration) { + t.Helper() + setRecentTestTime(s, node, elapsed) + s.nextRescanIndex, s.rescanRoundEnd = 2000, 5500 + if scanned, err := s.collectNextOldBatch(); err != nil || !scanned || s.nextRescanIndex != 3000 { + t.Fatalf("old cursor at %s: scanned %t, %v, next index %d", elapsed, scanned, err, s.nextRescanIndex) + } + } + scanOldBatchAt(0) + node.pay(address) // after the node's t=0 negative, which it serves through t=30 + scanOldBatchAt(30 * time.Second) + if s.addressSet[address] != nil { + t.Fatal("setup: the t=30 visit should be served the t=0 negative") + } + setRecentTestTime(s, node, 32*time.Second) + if _, err := s.recheckOldBatch(); err != nil { + t.Fatal(err) + } + if s.addressSet[address] == nil { + t.Fatal("the t=30 visit moved the re-check due at t=32 later") + } +} + // TestDiscoveryReplacesUnscannableLastUsedIndex pins this case: the keys file records an external // last used index no address can have, the internal one is 0, and the far scan finds a coin at external // 10500. The discovery must become the external key chain's last used index, so that a later coin at @@ -669,6 +714,8 @@ func TestForcedSyncsLeaveNoRecheckBacklog(t *testing.T) { mustCollectRecent(t, s) node.asked() baseCalls, _ := baseSyncCost(s) + var due oldBatchRecheck // an old batch's re-check, followed through the burst + var coin string syncAfter := func(interval time.Duration, forced bool) { t.Helper() @@ -682,10 +729,25 @@ func TestForcedSyncsLeaveNoRecheckBacklog(t *testing.T) { t.Fatalf("a re-check due %s ago was left for a later sync", now.Sub(recheck.notBefore)) } } + if coin != "" && !now.Before(due.notBefore) && s.addressSet[coin] == nil { + t.Fatalf("the re-check of the batch at %d, due %s ago, was dropped without a scan", due.start, now.Sub(due.notBefore)) + } } for range 30 { syncAfter(2*time.Second, false) } + // Only that re-check scans the batch within the burst: the cursor has just left it. + for _, recheck := range s.oldBatchRechecks { + if !recheck.handedOff && recheck.start < 74000 && !s.recentBatchIsInWindow(recheck.start) { + due = recheck + break + } + } + if due.notBefore.IsZero() { + t.Fatal("setup: no old batch re-check queued before the burst") + } + coin = rescanTestAddress(internal, due.start+1) // below the internal last used index + node.pay(coin) for range 60 { // One broadcast per second for a minute. syncAfter(time.Second, true) } diff --git a/cmd/htnwallet/generate_mldsa44_keys.go b/cmd/htnwallet/generate_mldsa44_keys.go index 994ede413e..b1d1561ba4 100644 --- a/cmd/htnwallet/generate_mldsa44_keys.go +++ b/cmd/htnwallet/generate_mldsa44_keys.go @@ -1,6 +1,7 @@ package main import ( + "bytes" "fmt" "github.com/HoosatNetwork/HTND/v2/cmd/htnwallet/keys" @@ -41,11 +42,15 @@ func generateMLDSA44Keys(conf *generateMLDSA44KeysConfig) error { isMultisig := len(keysFile.ExtendedPublicKeys) > 1 if !isMultisig { if count <= keysFile.MLDSA44.Size() { + if err := keysFile.SyncDirectory(); err != nil { + return err + } fmt.Printf("The wallet already has ML-DSA-44 keys for at least %d indexes per key chain\n", keysFile.MLDSA44.Size()) return nil } if implicit { existing, missing := mldsa44PoolGrowth(keysFile.MLDSA44, count) + // Growth also derives the stored hashes again to check them; the storage limit bounds that. if err := checkImplicitMLDSA44Growth(count, existing+missing, missing); err != nil { return err } @@ -62,11 +67,17 @@ func generateMLDSA44Keys(conf *generateMLDSA44KeysConfig) error { } correctedLocalPool := false + replaced := 0 if !isMultisig { - keysFile.MLDSA44, err = keysFile.MLDSA44.Extend(mnemonics[0], count, false) + pool, matches, err := keysFile.MLDSA44.Rebuild(mnemonics[0], count, false) if err != nil { return err } + if !matches { + correctedLocalPool = true + replaced = mldsa44HashesReplaced(keysFile.MLDSA44, pool) + } + keysFile.MLDSA44 = pool } else { needed := make(map[string]string, len(mnemonics)) for _, mnemonic := range mnemonics { @@ -79,6 +90,9 @@ func generateMLDSA44Keys(conf *generateMLDSA44KeysConfig) error { } } if len(needed) == 0 { + if err := keysFile.SyncDirectory(); err != nil { + return err + } fmt.Printf("The local cosigners already have ML-DSA-44 keys for at least %d indexes per key chain\n", count) return nil } @@ -102,7 +116,7 @@ func generateMLDSA44Keys(conf *generateMLDSA44KeysConfig) error { keysFile.MLDSA44Cosigners = make(map[string]*keys.MLDSA44KeyPool, len(needed)) } for publicKey, mnemonic := range needed { - pool, matches, err := keysFile.MLDSA44Cosigners[publicKey].RebuildCosigner(mnemonic, count) + pool, matches, err := keysFile.MLDSA44Cosigners[publicKey].Rebuild(mnemonic, count, true) if err != nil { return err } @@ -121,6 +135,9 @@ func generateMLDSA44Keys(conf *generateMLDSA44KeysConfig) error { return err } fmt.Printf("Wrote ML-DSA-44 keys for at least %d indexes per key chain into %s\n", count, keysFile.Path()) + if replaced > 0 { + fmt.Printf("Replaced %d stored ML-DSA-44 key hashes that differed from the keys derived from the mnemonic.\n", replaced) + } if correctedLocalPool { fmt.Println("Rebuilt the stored ML-DSA-44 pool for this account from the mnemonic.") } @@ -130,6 +147,20 @@ func generateMLDSA44Keys(conf *generateMLDSA44KeysConfig) error { return nil } +// mldsa44HashesReplaced counts the stored hashes that a rebuilt pool replaces. +func mldsa44HashesReplaced(stored, rebuilt *keys.MLDSA44KeyPool) (replaced int) { + count := func(stored, rebuilt [][]byte) { + for i, hash := range stored { + if !bytes.Equal(hash, rebuilt[i]) { + replaced++ + } + } + } + count(stored.ExternalPublicKeyHashes, rebuilt.ExternalPublicKeyHashes) + count(stored.InternalPublicKeyHashes, rebuilt.InternalPublicKeyHashes) + return replaced +} + func mldsa44PoolGrowth(pool *keys.MLDSA44KeyPool, count uint32) (existing, missing uint64) { var receive, change uint64 if pool != nil { @@ -172,14 +203,12 @@ func exportMLDSA44Keys(conf *exportMLDSA44KeysConfig) error { // importMLDSA44Keys adds another cosigner's exported ML-DSA-44 keys to the multisig wallet. func importMLDSA44Keys(conf *importMLDSA44KeysConfig) error { - keysFile, err := keys.ReadKeysFile(conf.NetParams(), conf.KeysFile) - if err != nil { - return err - } - err = keysFile.TryLock() + // Lock before reading, so a concurrent generation's save is not overwritten with an older snapshot. + keysFile, unlock, err := keys.ReadLockedKeysFile(conf.NetParams(), conf.KeysFile) if err != nil { return errors.Wrap(err, "stop the wallet daemon before importing ML-DSA-44 keys") } + defer unlock() count, err := keysFile.ImportMLDSA44Cosigners(conf.NetParams(), conf.InputFile) if err != nil { return err diff --git a/cmd/htnwallet/generate_mldsa44_keys_test.go b/cmd/htnwallet/generate_mldsa44_keys_test.go index 63ab36f3b0..723587a9d6 100644 --- a/cmd/htnwallet/generate_mldsa44_keys_test.go +++ b/cmd/htnwallet/generate_mldsa44_keys_test.go @@ -2,8 +2,10 @@ package main import ( "bytes" + "io" "os" "path/filepath" + "runtime" "strings" "testing" @@ -263,6 +265,69 @@ func TestGenerateMLDSA44ImplicitFileGrowthNeedsExplicitCount(t *testing.T) { } } +func TestGenerateMLDSA44SingleSigGrowthRepairsStoredHashes(t *testing.T) { + file, mnemonic := generationTestWallet(t) + want, err := libhtnwallet.MLDSA44PublicKeyHashes(mnemonic, libhtnwallet.ExternalKeychain, 4, 1, false) + if err != nil { + t.Fatal(err) + } + // A well-formed hash the mnemonic does not produce, as a hand edit or a storage error can leave. + file.MLDSA44.ExternalPublicKeyHashes[4] = bytes.Repeat([]byte{0x42}, 32) + if err := file.SetLastUsedExternalIndex(1); err != nil { // saves; the default count is now 502 + t.Fatal(err) + } + + reader, writer, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + defer reader.Close() + original := os.Stdout + os.Stdout = writer + err = runGenerateMLDSA44CLI(t, file.Path()) + os.Stdout = original + writer.Close() + if err != nil { + t.Fatal(err) + } + output, err := io.ReadAll(reader) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(output), "Replaced 1 stored ML-DSA-44 key hashes") { + t.Errorf("default growth did not report the repair:\n%s", output) + } + read, err := keys.ReadKeysFile(&dagconfig.MainnetParams, file.Path()) + if err != nil { + t.Fatal(err) + } + if got, _ := read.MLDSA44.PublicKeyHash(libhtnwallet.ExternalKeychain, 4); !bytes.Equal(got, want[0]) { + t.Fatal("default growth kept a stored receive hash that differs from the mnemonic") + } +} + +// Default growth derives the stored hashes again, but only new hashes count against the work limit: +// the storage limit already bounds the stored ones. +func TestGenerateMLDSA44ImplicitWorkCountsOnlyNewHashes(t *testing.T) { + file, _ := generationTestWallet(t) + hashes := func() [][]byte { + hashes := make([][]byte, 10_000) + for i := range hashes { + hashes[i] = make([]byte, 32) + } + return hashes + } + file.MLDSA44.ExternalPublicKeyHashes, file.MLDSA44.InternalPublicKeyHashes = hashes(), hashes() + if err := file.SetLastUsedExternalIndex(9_600); err != nil { // default count 10,101: 202 new hashes + t.Fatal(err) + } + // The limits are checked before the password. Passing them leads to the wrong-password error. + err := runGenerateMLDSA44CLI(t, file.Path(), "--password", "wrong") + if err == nil || strings.Contains(err.Error(), "default generation would derive") { + t.Fatalf("a 202-hash default extension of a 10,000-index pool must pass the limits, got %v", err) + } +} + func TestGenerateMLDSA44RejectsExplicitCountPastAddressRange(t *testing.T) { file, _ := generationTestWallet(t) err := runGenerateMLDSA44CLI(t, file.Path(), "--count", "2147483649", "--password", "wrong") @@ -304,6 +369,49 @@ func TestGenerateMLDSA44ReadsUnderLock(t *testing.T) { } } +// An earlier run can rename the new keys file and then fail to sync its directory. A run that then finds +// no work must still sync the directory before it reports success. +func TestGenerateMLDSA44WithoutWorkSyncsDirectory(t *testing.T) { + if runtime.GOOS == "windows" || os.Geteuid() == 0 { + t.Skip("needs a directory that can be entered but not opened") + } + file, _ := generationTestWallet(t) + dir := filepath.Dir(file.Path()) + // Opening the directory for its sync fails; reading and locking the keys file still work. + if err := os.Chmod(dir, 0o300); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.Chmod(dir, 0o700) }) + err := runGenerateMLDSA44CLI(t, file.Path(), "--count", "500") + if err == nil || !strings.Contains(err.Error(), "permission denied") { + t.Fatalf("a run without work must sync the directory, got %v", err) + } +} + +func TestImportMLDSA44KeysReadsUnderLock(t *testing.T) { + file, _ := generationTestWallet(t) + lock := flock.New(file.Path() + ".lock") + if ok, err := lock.TryLock(); err != nil || !ok { + t.Fatalf("acquiring a lock for another writer: %t, %v", ok, err) + } + defer lock.Close() + if err := os.WriteFile(file.Path(), []byte("unreadable"), 0o600); err != nil { + t.Fatal(err) + } + oldArgs := os.Args + os.Args = []string{oldArgs[0], importMLDSA44KeysSubCmd, "--keys-file", file.Path(), "--input", filepath.Join(t.TempDir(), "peer.json")} + defer func() { os.Args = oldArgs }() + command, conf := parseCommandLine() + if command != importMLDSA44KeysSubCmd { + t.Fatalf("parsed command %q", command) + } + // An unlocked read would decode the other writer's snapshot and fail before reporting contention. + err := importMLDSA44Keys(conf.(*importMLDSA44KeysConfig)) + if err == nil || !strings.Contains(err.Error(), "locked") || !strings.Contains(err.Error(), "stop the wallet daemon") { + t.Fatalf("want lock contention before reading, got %v", err) + } +} + func TestGenerateMLDSA44MultisigKeepsPeerRangeUntilExchange(t *testing.T) { params := &dagconfig.MainnetParams localMnemonics, localKeys, localPools, err := keys.CreateMnemonics(params, 1, "password", true) @@ -394,7 +502,13 @@ func TestGenerateMLDSA44MultisigKeepsPeerRangeUntilExchange(t *testing.T) { if err := legacy.Save(); err != nil { t.Fatal(err) } - before, err := os.Stat(file.Path()) + // Stat an open handle: on Windows os.Stat reads the file ID lazily, by path, in os.SameFile. + original, err := os.Open(file.Path()) + if err != nil { + t.Fatal(err) + } + before, err := original.Stat() + original.Close() if err != nil { t.Fatal(err) } diff --git a/cmd/htnwallet/keys/keys.go b/cmd/htnwallet/keys/keys.go index f51d7d0ceb..595886a373 100644 --- a/cmd/htnwallet/keys/keys.go +++ b/cmd/htnwallet/keys/keys.go @@ -157,12 +157,13 @@ func (p *MLDSA44KeyPool) Extend(mnemonic string, size uint32, multisig bool) (*M return &MLDSA44KeyPool{ExternalPublicKeyHashes: external, InternalPublicKeyHashes: internal}, nil } -// RebuildCosigner derives both chains of a local cosigner pool from the mnemonic, covering +// Rebuild derives both chains of a local pool from the mnemonic, covering // size indexes or the stored range of a chain if that is longer. // matches reports whether the stored hashes equal the derived ones. -func (p *MLDSA44KeyPool) RebuildCosigner(mnemonic string, size uint32) (rebuilt *MLDSA44KeyPool, matches bool, err error) { +// multisig selects the mnemonic's multisig cosigner keys. +func (p *MLDSA44KeyPool) Rebuild(mnemonic string, size uint32, multisig bool) (rebuilt *MLDSA44KeyPool, matches bool, err error) { if p == nil { - rebuilt, err = NewMLDSA44KeyPool(mnemonic, size, true) + rebuilt, err = NewMLDSA44KeyPool(mnemonic, size, multisig) return rebuilt, err == nil, err } derive := func(chain uint8, existing [][]byte) ([][]byte, error) { @@ -170,7 +171,7 @@ func (p *MLDSA44KeyPool) RebuildCosigner(mnemonic string, size uint32) (rebuilt if count > MLDSA44AddressIndexLimit || count > uint64(math.MaxInt) { return nil, errors.Errorf("ML-DSA-44 key count %d exceeds the supported address range", count) } - return libhtnwallet.MLDSA44PublicKeyHashes(mnemonic, chain, 0, uint32(count), true) + return libhtnwallet.MLDSA44PublicKeyHashes(mnemonic, chain, 0, uint32(count), multisig) } receive, err := derive(libhtnwallet.ExternalKeychain, p.ExternalPublicKeyHashes) if err != nil { @@ -466,6 +467,16 @@ func (d *File) LastUsedExternalIndex() uint32 { return d.lastUsedExternalIndex } +// ReserveExternalIndex is ReserveInternalIndex for the external key chain. +func (d *File) ReserveExternalIndex(index uint32) error { + previous := d.lastUsedExternalIndex + if err := d.SetLastUsedExternalIndex(index); err != nil { + d.lastUsedExternalIndex = previous + return err + } + return nil +} + // SetLastUsedInternalIndex sets the last used index in the internal key chain, and saves the file. func (d *File) SetLastUsedInternalIndex(index uint32) error { return d.setLastUsedIndex(&d.lastUsedInternalIndex, index) @@ -675,6 +686,18 @@ func (d *File) save() (bool, error) { return true, directory.Sync() } +// SyncDirectory syncs the keys file's directory, which makes an earlier rename of the file durable. +// A command that finds no work calls it, because an earlier run may have renamed the file and then +// failed to sync the directory. +func (d *File) SyncDirectory() error { + directory, err := openSyncDir(filepath.Dir(d.path)) + if err != nil { + return err + } + defer directory.Close() + return directory.Sync() +} + type syncDirectory interface { Sync() error Close() error diff --git a/cmd/htnwallet/keys/keys_save_test.go b/cmd/htnwallet/keys/keys_save_test.go index 2ad13fc5a1..1dbcea5ee2 100644 --- a/cmd/htnwallet/keys/keys_save_test.go +++ b/cmd/htnwallet/keys/keys_save_test.go @@ -287,6 +287,104 @@ type failingDirectorySync struct { func (d failingDirectorySync) Sync() error { return d.err } +func TestExternalReservationRetriesAfterDirectorySyncFailure(t *testing.T) { + path := filepath.Join(t.TempDir(), "keys.json") + seedKeysFile(t, path) + params := &dagconfig.MainnetParams + file, err := ReadKeysFile(params, path) + if err != nil { + t.Fatal(err) + } + injected := errors.New("injected directory sync failure") + openSyncDir = func(dir string) (syncDirectory, error) { + directory, err := openDirectoryForSync(dir) + if err != nil { + return nil, err + } + return failingDirectorySync{directory, injected}, nil + } + t.Cleanup(func() { openSyncDir = openDirectoryForSync }) + + // Each failed reservation must leave the index unrecorded, so the next one saves again. + for range 2 { + if err := file.ReserveExternalIndex(1); !errors.Is(err, injected) { + t.Fatalf("reservation returned %v, want the directory sync error", err) + } + if got := file.LastUsedExternalIndex(); got != 0 { + t.Fatalf("a failed reservation kept index %d in memory, so a retry would not save it", got) + } + } + syncs := 0 + openSyncDir = func(dir string) (syncDirectory, error) { + directory, err := openDirectoryForSync(dir) + if err != nil { + return nil, err + } + return countingDirectorySync{directory, &syncs}, nil + } + if err := file.ReserveExternalIndex(1); err != nil { + t.Fatal(err) + } + if syncs != 1 { + t.Fatalf("the successful retry synced the directory %d times, want 1", syncs) + } + reloaded, err := ReadKeysFile(params, path) + if err != nil { + t.Fatal(err) + } + if memory, disk := file.LastUsedExternalIndex(), reloaded.LastUsedExternalIndex(); memory != 1 || disk != 1 { + t.Errorf("retry reserved index %d in memory and %d on disk, want index 1", memory, disk) + } +} + +type countingDirectorySync struct { + syncDirectory + syncs *int +} + +func (d countingDirectorySync) Sync() error { + err := d.syncDirectory.Sync() + if err == nil { + *d.syncs++ + } + return err +} + +func TestSyncDirectoryReportsAndCompletesTheSync(t *testing.T) { + path := filepath.Join(t.TempDir(), "keys.json") + seedKeysFile(t, path) + file, err := ReadKeysFile(&dagconfig.MainnetParams, path) + if err != nil { + t.Fatal(err) + } + injected := errors.New("injected directory sync failure") + openSyncDir = func(dir string) (syncDirectory, error) { + directory, err := openDirectoryForSync(dir) + if err != nil { + return nil, err + } + return failingDirectorySync{directory, injected}, nil + } + t.Cleanup(func() { openSyncDir = openDirectoryForSync }) + if err := file.SyncDirectory(); !errors.Is(err, injected) { + t.Fatalf("SyncDirectory returned %v, want the directory sync error", err) + } + syncs := 0 + openSyncDir = func(dir string) (syncDirectory, error) { + if dir != filepath.Dir(path) { + t.Errorf("synced %s, want the keys file's directory", dir) + } + directory, err := openDirectoryForSync(dir) + if err != nil { + return nil, err + } + return countingDirectorySync{directory, &syncs}, nil + } + if err := file.SyncDirectory(); err != nil || syncs != 1 { + t.Fatalf("SyncDirectory: %v after %d syncs, want one sync", err, syncs) + } +} + func TestInternalReservationRetriesAfterDirectorySyncFailure(t *testing.T) { path := filepath.Join(t.TempDir(), "keys.json") seedKeysFile(t, path)