package server import ( "fmt" "net" "os" "sync" "sync/atomic" "time" "github.com/HoosatNetwork/HTND/v2/app/appmessage" "github.com/HoosatNetwork/HTND/v2/domain/consensus/model/externalapi" "github.com/HoosatNetwork/HTND/v2/version" "github.com/HoosatNetwork/HTND/v2/util/txmass" "github.com/HoosatNetwork/HTND/v2/util/profiling" "github.com/HoosatNetwork/HTND/v2/cmd/htnwallet/daemon/pb" "github.com/HoosatNetwork/HTND/v2/cmd/htnwallet/keys" "github.com/HoosatNetwork/HTND/v2/cmd/htnwallet/libhtnwallet" "github.com/HoosatNetwork/HTND/v2/domain/dagconfig" "github.com/HoosatNetwork/HTND/v2/infrastructure/os/signal" "github.com/HoosatNetwork/HTND/v2/util/panics" "github.com/pkg/errors" "google.golang.org/grpc" ) type walletRPCClient interface { Reconnect() error GetBlockDAGInfo() (*appmessage.GetBlockDAGInfoResponseMessage, error) GetUTXOsByAddresses(addresses []string, limit uint32) (*appmessage.GetUTXOsByAddressesResponseMessage, error) transactionSubmitter } type walletBackgroundNode interface { transactionSubmitter GetBalancesByAddresses(addresses []string) (*appmessage.GetBalancesByAddressesResponseMessage, error) GetMempoolEntriesByAddresses(addresses []string, includeOrphanPool, filterTransactionPool bool) (*appmessage.GetMempoolEntriesByAddressesResponseMessage, error) GetMempoolEntry(txID string, includeOrphanPool, filterTransactionPool bool) (*appmessage.GetMempoolEntryResponseMessage, error) GetTransactionStatus(transactionID string) (*appmessage.GetTransactionStatusResponseMessage, error) GetUsableAddresses(addresses []string) (*appmessage.GetUsableAddressesResponseMessage, error) GetUTXOsByAddresses(addresses []string, limit uint32) (*appmessage.GetUTXOsByAddressesResponseMessage, error) } type server struct { pb.UnimplementedHtnwalletdServer rpcClient walletRPCClient // RPC client for ongoing user requests backgroundRPCClient walletBackgroundNode // RPC client dedicated for address and UTXO background fetching dagInfoRequests dagInfoRequests addressListingTimeout time.Duration params *dagconfig.Params coinbaseMaturity uint64 // Is different from default if we use testnet-11 lock sync.RWMutex utxosSortedByAmount []*walletUTXO nextSyncStartIndex uint32 nextRescanIndex uint32 // The batch collectOldAddresses scans next rescanRoundEnd uint32 // Where the round of collectOldAddresses under way ends oldBatchRechecks []oldBatchRecheck // Old batches to scan once more; see collectOldAddresses now func() time.Time // The clock; nil means time.Now (tests set it) keysFile *keys.File shutdown chan struct{} forceSyncChan chan struct{} startTimeOfLastCompletedRefresh time.Time limitOfLastCompletedRefresh uint32 // The per-address UTXO limit utxosSortedByAmount was fetched with utxoSetIsStale bool // A broadcast found utxosSortedByAmount holding coins already spent transactionStatusUnavailable bool // The node's GetTransactionStatus timed out; see acceptanceVerdict addressSet walletAddressSet importedAddresses walletAddressSet // Every address of an imported key; see trackImportedKeys compoundP2SHAddresses map[[32]byte]walletAddress // Built from the public key pools before serving. recentAddressBatches map[uint32]walletAddressSet // Derived address batches by start index; see addressesToQueryCached recentBatchPolls map[uint32]recentBatchPoll // Poll deadlines for batches in the recent window txMassCalculator *txmass.Calculator usedOutpoints map[externalapi.DomainOutpoint]time.Time pendingBroadcasts map[externalapi.DomainTransactionID]*pendingBroadcast firstSyncDone atomic.Bool warnedOfMLDSA44ScanGap bool // See warnOfMLDSA44ScanGap mldsa44ActiveAtStartup bool observedReceiveZero, observedChangeZero bool isLogFinalProgressLineShown bool maxUsedAddressesForLog uint32 maxProcessedAddressesForLog uint32 } // MaxDaemonSendMsgSize is the max send message size used for the daemon server. // Currently, set to 100MB const MaxDaemonMsgSize = 1_000_000_000 // Start starts the htnwalletd server func Start(params *dagconfig.Params, listen, rpcServer string, keysFilePath string, profile string, timeout uint32) error { initLog(defaultLogFile, defaultErrLogFile) defer panics.HandlePanic(log, "MAIN", nil) interrupt := signal.InterruptListener() if profile != "" { profiling.Start(profile, log) } log.Infof("Version %s", version.Version()) listener, err := net.Listen("tcp", listen) if err != nil { return (errors.Wrapf(err, "Error listening to TCP on %s", listen)) } log.Infof("Listening to TCP on %s", listen) log.Infof("Connecting to a node at %s...", rpcServer) rpcClient, err := connectToRPC(params, rpcServer, timeout) if err != nil { return (errors.Wrapf(err, "Error connecting to RPC server %s", rpcServer)) } // Ask the node first, so that a failure has only the listener and this client to release. dagInfo, err := rpcClient.GetBlockDAGInfo() if err != nil { _ = rpcClient.Close() _ = listener.Close() return errors.Wrapf(err, "Error getting the DAG info from RPC server %s", rpcServer) } backgroundRPCClient, err := connectToRPC(params, rpcServer, timeout) if err != nil { return (errors.Wrapf(err, "Error making a second connection to RPC server %s", rpcServer)) } log.Infof("Connected, reading keys file %s...", keysFilePath) keysFile, unlockKeysFile, err := keys.ReadLockedKeysFile(params, keysFilePath) if err != nil { return (errors.Wrapf(err, "Error reading keys file %s", keysFilePath)) } coinbaseMaturity := params.BlockCoinbaseMaturity if dagInfo.NetworkName == "hoosat-testnet" { coinbaseMaturity = 1000 } addressListingTimeout := maxAddressListingRPCTimeout if timeout != 0 { addressListingTimeout = min(time.Duration(timeout)*time.Second, addressListingTimeout) } serverInstance := &server{ addressListingTimeout: addressListingTimeout, rpcClient: rpcClient, backgroundRPCClient: backgroundRPCClient, params: params, coinbaseMaturity: coinbaseMaturity, utxosSortedByAmount: []*walletUTXO{}, nextSyncStartIndex: 0, keysFile: keysFile, shutdown: make(chan struct{}), forceSyncChan: newForceSyncChan(), addressSet: make(walletAddressSet), txMassCalculator: txmass.NewCalculator(params.MassPerTxByte, params.MassPerScriptPubKeyByte, params.MassPerSigOp), usedOutpoints: map[externalapi.DomainOutpoint]time.Time{}, mldsa44ActiveAtStartup: libhtnwallet.MLDSA44Active(params, dagInfo.VirtualDAAScore), isLogFinalProgressLineShown: false, maxUsedAddressesForLog: 0, maxProcessedAddressesForLog: 0, } err = serverInstance.trackImportedKeys() if err != nil { _ = unlockKeysFile() return errors.Wrap(err, "Error reading the imported keys") } serverInstance.indexCompoundP2SHAddresses() log.Infof("Read, syncing the wallet...") spawn("serverInstance.syncLoop", func() { err := serverInstance.syncLoop() if err != nil { printErrorAndExit(errors.Wrap(err, "error syncing the wallet")) } }) grpcServer := grpc.NewServer( grpc.MaxSendMsgSize(MaxDaemonMsgSize), grpc.MaxRecvMsgSize(MaxDaemonMsgSize), ) pb.RegisterHtnwalletdServer(grpcServer, serverInstance) spawn("grpcServer.Serve", func() { err := grpcServer.Serve(listener) if err != nil { printErrorAndExit(errors.Wrap(err, "Error serving gRPC")) } }) select { case <-serverInstance.shutdown: case <-interrupt: const stopTimeout = 2 * time.Second stopChan := make(chan any) spawn("gRPCServer.Stop", func() { grpcServer.GracefulStop() close(stopChan) }) select { case <-stopChan: case <-time.After(stopTimeout): log.Warnf("Could not gracefully stop: timed out after %s", stopTimeout) grpcServer.Stop() } } return nil } func printErrorAndExit(err error) { fmt.Fprintf(os.Stderr, "%+v\n", err) os.Exit(1) }