From 3967d9e24e4b4e45e56312c1fd0841e5f026d08c Mon Sep 17 00:00:00 2001 From: jholdstock Date: Mon, 11 Sep 2023 15:22:40 +0100 Subject: [PATCH] webapi: Don't export funcs/vars unnecessarily. --- internal/webapi/addressgenerator.go | 4 +-- internal/webapi/admin.go | 40 +++++++++++++------------- internal/webapi/getfeeaddress.go | 8 +++--- internal/webapi/helpers.go | 2 +- internal/webapi/homepage.go | 2 +- internal/webapi/middleware.go | 14 ++++----- internal/webapi/payfee.go | 2 +- internal/webapi/recovery.go | 4 +-- internal/webapi/setaltsignaddr.go | 10 +++---- internal/webapi/setaltsignaddr_test.go | 6 ++-- internal/webapi/setvotechoices.go | 2 +- internal/webapi/ticketstatus.go | 2 +- internal/webapi/vspinfo.go | 2 +- internal/webapi/webapi.go | 14 ++++----- 14 files changed, 56 insertions(+), 56 deletions(-) diff --git a/internal/webapi/addressgenerator.go b/internal/webapi/addressgenerator.go index c0948d6..7d84cc9 100644 --- a/internal/webapi/addressgenerator.go +++ b/internal/webapi/addressgenerator.go @@ -44,10 +44,10 @@ func newAddressGenerator(xPub string, netParams *chaincfg.Params, lastUsedIdx ui }, nil } -// NextAddress increments the last used address counter and returns a new +// nextAddress increments the last used address counter and returns a new // address. It will skip any address index which causes an ErrInvalidChild. // Not safe for concurrent access. -func (m *addressGenerator) NextAddress() (string, uint32, error) { +func (m *addressGenerator) nextAddress() (string, uint32, error) { var key *hdkeychain.ExtendedKey var err error diff --git a/internal/webapi/admin.go b/internal/webapi/admin.go index a772f70..a166599 100644 --- a/internal/webapi/admin.go +++ b/internal/webapi/admin.go @@ -14,10 +14,10 @@ import ( "github.com/gorilla/sessions" ) -// WalletStatus describes the current status of a single voting wallet. This is +// walletStatus describes the current status of a single voting wallet. This is // used by the admin.html template, and also serialized to JSON for the // /admin/status endpoint. -type WalletStatus struct { +type walletStatus struct { Connected bool `json:"connected"` InfoError bool `json:"infoerror"` DaemonConnected bool `json:"daemonconnected"` @@ -28,10 +28,10 @@ type WalletStatus struct { BestBlockHeight int64 `json:"bestblockheight"` } -// DcrdStatus describes the current status of the local instance of dcrd used by +// dcrdStatus describes the current status of the local instance of dcrd used by // vspd. This is used by the admin.html template, and also serialized to JSON // for the /admin/status endpoint. -type DcrdStatus struct { +type dcrdStatus struct { Host string `json:"host"` Connected bool `json:"connected"` BestBlockError bool `json:"bestblockerror"` @@ -48,9 +48,9 @@ type searchResult struct { MaxVoteChanges int } -func (s *Server) dcrdStatus(c *gin.Context) DcrdStatus { +func (s *server) dcrdStatus(c *gin.Context) dcrdStatus { hostname := c.MustGet(dcrdHostKey).(string) - status := DcrdStatus{Host: hostname} + status := dcrdStatus{Host: hostname} dcrdClient := c.MustGet(dcrdKey).(*rpc.DcrdRPC) dcrdErr := c.MustGet(dcrdErrorKey) @@ -73,13 +73,13 @@ func (s *Server) dcrdStatus(c *gin.Context) DcrdStatus { return status } -func (s *Server) walletStatus(c *gin.Context) map[string]WalletStatus { +func (s *server) walletStatus(c *gin.Context) map[string]walletStatus { walletClients := c.MustGet(walletsKey).([]*rpc.WalletRPC) failedWalletClients := c.MustGet(failedWalletsKey).([]string) - walletStatus := make(map[string]WalletStatus) + status := make(map[string]walletStatus) for _, v := range walletClients { - ws := WalletStatus{Connected: true} + ws := walletStatus{Connected: true} walletInfo, err := v.WalletInfo() if err != nil { @@ -100,18 +100,18 @@ func (s *Server) walletStatus(c *gin.Context) map[string]WalletStatus { ws.BestBlockHeight = height } - walletStatus[v.String()] = ws + status[v.String()] = ws } for _, v := range failedWalletClients { - ws := WalletStatus{Connected: false} - walletStatus[v] = ws + ws := walletStatus{Connected: false} + status[v] = ws } - return walletStatus + return status } // statusJSON is the handler for "GET /admin/status". It returns a JSON object // describing the current status of voting wallets. -func (s *Server) statusJSON(c *gin.Context) { +func (s *server) statusJSON(c *gin.Context) { httpStatus := http.StatusOK wallets := s.walletStatus(c) @@ -143,7 +143,7 @@ func (s *Server) statusJSON(c *gin.Context) { } // adminPage is the handler for "GET /admin". -func (s *Server) adminPage(c *gin.Context) { +func (s *server) adminPage(c *gin.Context) { c.HTML(http.StatusOK, "admin.html", gin.H{ "WebApiCache": s.cache.getData(), "WebApiCfg": s.cfg, @@ -154,7 +154,7 @@ func (s *Server) adminPage(c *gin.Context) { // ticketSearch is the handler for "POST /admin/ticket". The hash param will be // used to retrieve a ticket from the database. -func (s *Server) ticketSearch(c *gin.Context) { +func (s *server) ticketSearch(c *gin.Context) { hash := c.PostForm("hash") ticket, found, err := s.db.GetTicketByHash(hash) @@ -227,7 +227,7 @@ func (s *Server) ticketSearch(c *gin.Context) { // adminLogin is the handler for "POST /admin". If a valid password is provided, // the current session will be authenticated as an admin. -func (s *Server) adminLogin(c *gin.Context) { +func (s *server) adminLogin(c *gin.Context) { password := c.PostForm("password") if password != s.cfg.AdminPass { @@ -245,13 +245,13 @@ func (s *Server) adminLogin(c *gin.Context) { // adminLogout is the handler for "POST /admin/logout". The current session will // have its admin authentication removed. -func (s *Server) adminLogout(c *gin.Context) { +func (s *server) adminLogout(c *gin.Context) { s.setAdminStatus(nil, c) } // downloadDatabaseBackup is the handler for "GET /backup". A binary // representation of the whole database is generated and returned to the client. -func (s *Server) downloadDatabaseBackup(c *gin.Context) { +func (s *server) downloadDatabaseBackup(c *gin.Context) { err := s.db.BackupDB(c.Writer) if err != nil { s.log.Errorf("Error backing up database: %v", err) @@ -263,7 +263,7 @@ func (s *Server) downloadDatabaseBackup(c *gin.Context) { // setAdminStatus stores the authentication status of the current session and // redirects the client to GET /admin. -func (s *Server) setAdminStatus(admin any, c *gin.Context) { +func (s *server) setAdminStatus(admin any, c *gin.Context) { session := c.MustGet(sessionKey).(*sessions.Session) session.Values["admin"] = admin err := session.Save(c.Request, c.Writer) diff --git a/internal/webapi/getfeeaddress.go b/internal/webapi/getfeeaddress.go index 425ab3a..ab5fe6a 100644 --- a/internal/webapi/getfeeaddress.go +++ b/internal/webapi/getfeeaddress.go @@ -24,11 +24,11 @@ var addrMtx sync.Mutex // the last used address index in the database. In order to maintain consistency // between the internal counter of address generator and the database, this func // uses a mutex to ensure it is not run concurrently. -func (s *Server) getNewFeeAddress() (string, uint32, error) { +func (s *server) getNewFeeAddress() (string, uint32, error) { addrMtx.Lock() defer addrMtx.Unlock() - addr, idx, err := s.addrGen.NextAddress() + addr, idx, err := s.addrGen.nextAddress() if err != nil { return "", 0, err } @@ -43,7 +43,7 @@ func (s *Server) getNewFeeAddress() (string, uint32, error) { // getCurrentFee returns the minimum fee amount a client should pay in order to // register a ticket with the VSP at the current block height. -func (s *Server) getCurrentFee(dcrdClient *rpc.DcrdRPC) (dcrutil.Amount, error) { +func (s *server) getCurrentFee(dcrdClient *rpc.DcrdRPC) (dcrutil.Amount, error) { bestBlock, err := dcrdClient.GetBestBlockHeader() if err != nil { return 0, err @@ -70,7 +70,7 @@ func (s *Server) getCurrentFee(dcrdClient *rpc.DcrdRPC) (dcrutil.Amount, error) } // feeAddress is the handler for "POST /api/v3/feeaddress". -func (s *Server) feeAddress(c *gin.Context) { +func (s *server) feeAddress(c *gin.Context) { const funcName = "feeAddress" diff --git a/internal/webapi/helpers.go b/internal/webapi/helpers.go index f947dfb..84f89bb 100644 --- a/internal/webapi/helpers.go +++ b/internal/webapi/helpers.go @@ -172,7 +172,7 @@ func validateTicketHash(hash string) error { // canTicketVote checks determines whether a ticket is able to vote at some // point in the future by checking that it is currently either in the mempool, // immature or live. -func canTicketVote(rawTx *dcrdtypes.TxRawResult, dcrdClient Node, netParams *chaincfg.Params) (bool, error) { +func canTicketVote(rawTx *dcrdtypes.TxRawResult, dcrdClient node, netParams *chaincfg.Params) (bool, error) { // Tickets which have more than (TicketMaturity+TicketExpiry+1) // confirmations are too old to vote. diff --git a/internal/webapi/homepage.go b/internal/webapi/homepage.go index e2f71fd..5401e31 100644 --- a/internal/webapi/homepage.go +++ b/internal/webapi/homepage.go @@ -10,7 +10,7 @@ import ( "github.com/gin-gonic/gin" ) -func (s *Server) homepage(c *gin.Context) { +func (s *server) homepage(c *gin.Context) { c.HTML(http.StatusOK, "homepage.html", gin.H{ "WebApiCache": s.cache.getData(), "WebApiCfg": s.cfg, diff --git a/internal/webapi/middleware.go b/internal/webapi/middleware.go index 7e18df2..d1e9e59 100644 --- a/internal/webapi/middleware.go +++ b/internal/webapi/middleware.go @@ -63,7 +63,7 @@ func rateLimit(limit rate.Limit, limitExceeded gin.HandlerFunc) gin.HandlerFunc // withSession middleware adds a gorilla session to the request context for // downstream handlers to make use of. Sessions are used by admin pages to // maintain authentication status. -func (s *Server) withSession(store *sessions.CookieStore) gin.HandlerFunc { +func (s *server) withSession(store *sessions.CookieStore) gin.HandlerFunc { return func(c *gin.Context) { session, err := store.Get(c.Request, "vspd-session") if err != nil { @@ -95,7 +95,7 @@ func (s *Server) withSession(store *sessions.CookieStore) gin.HandlerFunc { // requireAdmin will only allow the request to proceed if the current session is // authenticated as an admin, otherwise it will render the login template. -func (s *Server) requireAdmin(c *gin.Context) { +func (s *server) requireAdmin(c *gin.Context) { session := c.MustGet(sessionKey).(*sessions.Session) admin := session.Values["admin"] @@ -111,7 +111,7 @@ func (s *Server) requireAdmin(c *gin.Context) { // withDcrdClient middleware adds a dcrd client to the request context for // downstream handlers to make use of. -func (s *Server) withDcrdClient(dcrd rpc.DcrdConnect) gin.HandlerFunc { +func (s *server) withDcrdClient(dcrd rpc.DcrdConnect) gin.HandlerFunc { return func(c *gin.Context) { client, hostname, err := dcrd.Client() // Don't handle the error here, add it to the context and let downstream @@ -125,7 +125,7 @@ func (s *Server) withDcrdClient(dcrd rpc.DcrdConnect) gin.HandlerFunc { // withWalletClients middleware attempts to add voting wallet clients to the // request context for downstream handlers to make use of. Downstream handlers // must handle the case where no wallet clients are connected. -func (s *Server) withWalletClients(wallets rpc.WalletConnect) gin.HandlerFunc { +func (s *server) withWalletClients(wallets rpc.WalletConnect) gin.HandlerFunc { return func(c *gin.Context) { clients, failedConnections := wallets.Clients() if len(clients) == 0 { @@ -151,7 +151,7 @@ func drainAndReplaceBody(req *http.Request) ([]byte, error) { return reqBytes, nil } -func (s *Server) vspMustBeOpen(c *gin.Context) { +func (s *server) vspMustBeOpen(c *gin.Context) { if s.cfg.VspClosed { s.sendError(types.ErrVspClosed, c) return @@ -163,7 +163,7 @@ func (s *Server) vspMustBeOpen(c *gin.Context) { // Ticket hash, ticket hex, and parent hex are parsed from the request body and // validated. They are broadcast to the network using SendRawTransaction if dcrd // is not aware of them. -func (s *Server) broadcastTicket(c *gin.Context) { +func (s *server) broadcastTicket(c *gin.Context) { const funcName = "broadcastTicket" // Read request bytes. @@ -304,7 +304,7 @@ func (s *Server) broadcastTicket(c *gin.Context) { // does not contain the request body signed with the commitment address. // Ticket information is added to the request context for downstream handlers to // use. -func (s *Server) vspAuth(c *gin.Context) { +func (s *server) vspAuth(c *gin.Context) { const funcName = "vspAuth" // Read request bytes. diff --git a/internal/webapi/payfee.go b/internal/webapi/payfee.go index 0c25a5b..979e5a9 100644 --- a/internal/webapi/payfee.go +++ b/internal/webapi/payfee.go @@ -21,7 +21,7 @@ import ( ) // payFee is the handler for "POST /api/v3/payfee". -func (s *Server) payFee(c *gin.Context) { +func (s *server) payFee(c *gin.Context) { const funcName = "payFee" // Get values which have been added to context by middleware. diff --git a/internal/webapi/recovery.go b/internal/webapi/recovery.go index d453d93..0be5743 100644 --- a/internal/webapi/recovery.go +++ b/internal/webapi/recovery.go @@ -26,11 +26,11 @@ var ( slash = []byte("/") ) -// Recovery returns a middleware that recovers from any panics which occur in +// recovery returns a middleware that recovers from any panics which occur in // request handlers. It logs the panic, a stack trace, and the full request // details. It also ensure the client receives a 500 response rather than no // response at all. -func Recovery(log slog.Logger) gin.HandlerFunc { +func recovery(log slog.Logger) gin.HandlerFunc { return func(c *gin.Context) { defer func() { if err := recover(); err != nil { diff --git a/internal/webapi/setaltsignaddr.go b/internal/webapi/setaltsignaddr.go index 7b7ea0d..93dcacf 100644 --- a/internal/webapi/setaltsignaddr.go +++ b/internal/webapi/setaltsignaddr.go @@ -17,21 +17,21 @@ import ( ) // Ensure that Node is satisfied by *rpc.DcrdRPC. -var _ Node = (*rpc.DcrdRPC)(nil) +var _ node = (*rpc.DcrdRPC)(nil) -// Node is satisfied by *rpc.DcrdRPC and retrieves data from the blockchain. -type Node interface { +// node is satisfied by *rpc.DcrdRPC and retrieves data from the blockchain. +type node interface { ExistsLiveTicket(ticketHash string) (bool, error) GetRawTransaction(txHash string) (*dcrdtypes.TxRawResult, error) } // setAltSignAddr is the handler for "POST /api/v3/setaltsignaddr". -func (s *Server) setAltSignAddr(c *gin.Context) { +func (s *server) setAltSignAddr(c *gin.Context) { const funcName = "setAltSignAddr" // Get values which have been added to context by middleware. - dcrdClient := c.MustGet(dcrdKey).(Node) + dcrdClient := c.MustGet(dcrdKey).(node) dcrdErr := c.MustGet(dcrdErrorKey) if dcrdErr != nil { s.log.Errorf("%s: Could not get dcrd client: %v", funcName, dcrdErr.(error)) diff --git a/internal/webapi/setaltsignaddr_test.go b/internal/webapi/setaltsignaddr_test.go index cdd10d9..3841fe5 100644 --- a/internal/webapi/setaltsignaddr_test.go +++ b/internal/webapi/setaltsignaddr_test.go @@ -39,7 +39,7 @@ var ( seededRand = rand.New(rand.NewSource(time.Now().UnixNano())) feeXPub = "feexpub" maxVoteChangeRecords = 3 - api *Server + api *server ) // randBytes returns a byte slice of size n filled with random bytes. @@ -84,7 +84,7 @@ func TestMain(m *testing.M) { panic(fmt.Errorf("error opening test database: %w", err)) } - api = &Server{ + api = &server{ cfg: cfg, signPrivKey: signPrivKey, db: db, @@ -112,7 +112,7 @@ func randString(length int, charset string) string { } // Ensure that testNode satisfies Node. -var _ Node = (*testNode)(nil) +var _ node = (*testNode)(nil) type testNode struct { getRawTransaction *dcrdtypes.TxRawResult diff --git a/internal/webapi/setvotechoices.go b/internal/webapi/setvotechoices.go index 014ba99..489a5d6 100644 --- a/internal/webapi/setvotechoices.go +++ b/internal/webapi/setvotechoices.go @@ -17,7 +17,7 @@ import ( ) // setVoteChoices is the handler for "POST /api/v3/setvotechoices". -func (s *Server) setVoteChoices(c *gin.Context) { +func (s *server) setVoteChoices(c *gin.Context) { const funcName = "setVoteChoices" // Get values which have been added to context by middleware. diff --git a/internal/webapi/ticketstatus.go b/internal/webapi/ticketstatus.go index ed35da2..7258321 100644 --- a/internal/webapi/ticketstatus.go +++ b/internal/webapi/ticketstatus.go @@ -14,7 +14,7 @@ import ( ) // ticketStatus is the handler for "POST /api/v3/ticketstatus". -func (s *Server) ticketStatus(c *gin.Context) { +func (s *server) ticketStatus(c *gin.Context) { const funcName = "ticketStatus" // Get values which have been added to context by middleware. diff --git a/internal/webapi/vspinfo.go b/internal/webapi/vspinfo.go index 4e60df3..908810e 100644 --- a/internal/webapi/vspinfo.go +++ b/internal/webapi/vspinfo.go @@ -13,7 +13,7 @@ import ( ) // vspInfo is the handler for "GET /api/v3/vspinfo". -func (s *Server) vspInfo(c *gin.Context) { +func (s *server) vspInfo(c *gin.Context) { cachedStats := s.cache.getData() s.sendJSONResponse(types.VspInfoResponse{ APIVersions: []int64{3}, diff --git a/internal/webapi/webapi.go b/internal/webapi/webapi.go index 3741e16..b057132 100644 --- a/internal/webapi/webapi.go +++ b/internal/webapi/webapi.go @@ -65,7 +65,7 @@ const ( commitmentAddressKey = "CommitmentAddress" ) -type Server struct { +type server struct { cfg Config db *database.VspDatabase log slog.Logger @@ -79,7 +79,7 @@ func Start(ctx context.Context, requestShutdown func(), shutdownWg *sync.WaitGro listen string, vdb *database.VspDatabase, log slog.Logger, dcrd rpc.DcrdConnect, wallets rpc.WalletConnect, config Config) error { - s := &Server{ + s := &server{ cfg: config, db: vdb, log: log, @@ -191,7 +191,7 @@ func Start(ctx context.Context, requestShutdown func(), shutdownWg *sync.WaitGro return nil } -func (s *Server) router(cookieSecret []byte, dcrd rpc.DcrdConnect, wallets rpc.WalletConnect) *gin.Engine { +func (s *server) router(cookieSecret []byte, dcrd rpc.DcrdConnect, wallets rpc.WalletConnect) *gin.Engine { // With release mode enabled, gin will only read template files once and cache them. // With release mode disabled, templates will be reloaded on the fly. if !s.cfg.Debug { @@ -218,7 +218,7 @@ func (s *Server) router(cookieSecret []byte, dcrd rpc.DcrdConnect, wallets rpc.W // Recovery middleware handles any go panics generated while processing web // requests. Ensures a 500 response is sent to the client rather than // sending no response at all. - router.Use(Recovery(s.log)) + router.Use(recovery(s.log)) if s.cfg.Debug { // Logger middleware outputs very detailed logging of webserver requests @@ -283,7 +283,7 @@ func (s *Server) router(cookieSecret []byte, dcrd rpc.DcrdConnect, wallets rpc.W // sendJSONResponse serializes the provided response, signs it, and sends the // response to the client with a 200 OK status. Returns the seralized response // and the signature. -func (s *Server) sendJSONResponse(resp any, c *gin.Context) (string, string) { +func (s *server) sendJSONResponse(resp any, c *gin.Context) (string, string) { dec, err := json.Marshal(resp) if err != nil { s.log.Errorf("JSON marshal error: %v", err) @@ -302,14 +302,14 @@ func (s *Server) sendJSONResponse(resp any, c *gin.Context) (string, string) { // sendError sends an error response with the provided error code and the // default message for that code. -func (s *Server) sendError(e types.ErrorCode, c *gin.Context) { +func (s *server) sendError(e types.ErrorCode, c *gin.Context) { msg := e.DefaultMessage() s.sendErrorWithMsg(msg, e, c) } // sendErrorWithMsg sends an error response with the provided error code and // message. -func (s *Server) sendErrorWithMsg(msg string, e types.ErrorCode, c *gin.Context) { +func (s *server) sendErrorWithMsg(msg string, e types.ErrorCode, c *gin.Context) { status := e.HTTPStatus() resp := types.ErrorResponse{