2021-08-08 02:38:37 +00:00
|
|
|
package api
|
2021-08-01 23:54:53 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/hex"
|
2021-08-02 21:21:12 +00:00
|
|
|
"errors"
|
|
|
|
"fmt"
|
2021-08-01 23:54:53 +00:00
|
|
|
"net/http"
|
2021-08-31 02:08:51 +00:00
|
|
|
|
2022-05-14 22:14:11 +00:00
|
|
|
"github.com/mediocregopher/blog.mediocregopher.com/srv/api/apiutil"
|
2021-08-01 23:54:53 +00:00
|
|
|
)
|
|
|
|
|
2021-08-08 02:38:37 +00:00
|
|
|
func (a *api) newPowChallengeHandler() http.Handler {
|
2021-08-01 23:54:53 +00:00
|
|
|
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
|
2021-08-03 21:20:32 +00:00
|
|
|
|
2021-08-08 02:38:37 +00:00
|
|
|
challenge := a.params.PowManager.NewChallenge()
|
2021-08-01 23:54:53 +00:00
|
|
|
|
2022-05-14 22:14:11 +00:00
|
|
|
apiutil.JSONResult(rw, r, struct {
|
2021-08-01 23:54:53 +00:00
|
|
|
Seed string `json:"seed"`
|
|
|
|
Target uint32 `json:"target"`
|
|
|
|
}{
|
|
|
|
Seed: hex.EncodeToString(challenge.Seed),
|
|
|
|
Target: challenge.Target,
|
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
2021-08-02 21:21:12 +00:00
|
|
|
|
2021-08-08 02:38:37 +00:00
|
|
|
func (a *api) requirePowMiddleware(h http.Handler) http.Handler {
|
2021-08-02 21:21:12 +00:00
|
|
|
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
|
2021-08-03 21:20:32 +00:00
|
|
|
|
2021-09-02 23:02:20 +00:00
|
|
|
seedHex := r.FormValue("powSeed")
|
2021-08-02 21:21:12 +00:00
|
|
|
seed, err := hex.DecodeString(seedHex)
|
|
|
|
if err != nil || len(seed) == 0 {
|
2022-05-14 22:14:11 +00:00
|
|
|
apiutil.BadRequest(rw, r, errors.New("invalid powSeed"))
|
2021-08-02 21:21:12 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2021-09-02 23:02:20 +00:00
|
|
|
solutionHex := r.FormValue("powSolution")
|
2021-08-02 21:21:12 +00:00
|
|
|
solution, err := hex.DecodeString(solutionHex)
|
|
|
|
if err != nil || len(seed) == 0 {
|
2022-05-14 22:14:11 +00:00
|
|
|
apiutil.BadRequest(rw, r, errors.New("invalid powSolution"))
|
2021-08-02 21:21:12 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2021-08-08 02:38:37 +00:00
|
|
|
err = a.params.PowManager.CheckSolution(seed, solution)
|
|
|
|
|
|
|
|
if err != nil {
|
2022-05-14 22:14:11 +00:00
|
|
|
apiutil.BadRequest(rw, r, fmt.Errorf("checking proof-of-work solution: %w", err))
|
2021-08-02 21:21:12 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
h.ServeHTTP(rw, r)
|
|
|
|
})
|
|
|
|
}
|