forked from stellar/go
/
challenge.go
76 lines (64 loc) · 1.68 KB
/
challenge.go
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package serve
import (
"net/http"
"time"
"github.com/stellar/go/keypair"
"github.com/stellar/go/strkey"
supportlog "github.com/stellar/go/support/log"
"github.com/stellar/go/support/render/httpjson"
"github.com/stellar/go/txnbuild"
)
// ChallengeHandler implements the SEP-10 challenge endpoint and handles
// requests for a new challenge transaction.
type challengeHandler struct {
Logger *supportlog.Entry
ServerName string
NetworkPassphrase string
SigningKey *keypair.Full
ChallengeExpiresIn time.Duration
}
type challengeResponse struct {
Transaction string `json:"transaction"`
NetworkPassphrase string `json:"network_passphrase"`
}
func (h challengeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
account := r.URL.Query().Get("account")
if !strkey.IsValidEd25519PublicKey(account) {
badRequest.Render(w)
return
}
tx, err := txnbuild.BuildChallengeTx(
h.SigningKey.Seed(),
account,
h.ServerName,
h.NetworkPassphrase,
h.ChallengeExpiresIn,
)
if err != nil {
h.Logger.Ctx(ctx).WithStack(err).Error(err)
serverError.Render(w)
return
}
hash, err := tx.HashHex(h.NetworkPassphrase)
if err != nil {
h.Logger.Ctx(ctx).WithStack(err).Error(err)
serverError.Render(w)
return
}
l := h.Logger.Ctx(ctx).
WithField("tx", hash).
WithField("account", account)
l.Info("Generated challenge transaction for account.")
txeBase64, err := tx.Base64()
if err != nil {
h.Logger.Ctx(ctx).WithStack(err).Error(err)
serverError.Render(w)
return
}
res := challengeResponse{
Transaction: txeBase64,
NetworkPassphrase: h.NetworkPassphrase,
}
httpjson.Render(w, res, httpjson.JSON)
}