summaryrefslogtreecommitdiff
path: root/src/http/pow.go
blob: 1bd5cb587148ca1553734b753d12e6ed120dae2e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package http

import (
	"encoding/hex"
	"errors"
	"fmt"
	"net/http"

	"github.com/mediocregopher/blog.mediocregopher.com/srv/http/apiutil"
)

func (a *api) newPowChallengeHandler() http.Handler {
	return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {

		challenge := a.params.PowManager.NewChallenge()

		apiutil.JSONResult(rw, r, struct {
			Seed   string `json:"seed"`
			Target uint32 `json:"target"`
		}{
			Seed:   hex.EncodeToString(challenge.Seed),
			Target: challenge.Target,
		})
	})
}

func (a *api) requirePowMiddleware(h http.Handler) http.Handler {
	return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {

		seedHex := r.FormValue("powSeed")
		seed, err := hex.DecodeString(seedHex)
		if err != nil || len(seed) == 0 {
			apiutil.BadRequest(rw, r, errors.New("invalid powSeed"))
			return
		}

		solutionHex := r.FormValue("powSolution")
		solution, err := hex.DecodeString(solutionHex)
		if err != nil || len(seed) == 0 {
			apiutil.BadRequest(rw, r, errors.New("invalid powSolution"))
			return
		}

		err = a.params.PowManager.CheckSolution(seed, solution)

		if err != nil {
			apiutil.BadRequest(rw, r, fmt.Errorf("checking proof-of-work solution: %w", err))
			return
		}

		h.ServeHTTP(rw, r)
	})
}