This repository has been archived by the owner on Nov 19, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
anchor-api.go
196 lines (178 loc) · 5.68 KB
/
anchor-api.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
//go:generate go run github.com/deepmap/oapi-codegen/cmd/oapi-codegen -package anchor -generate "types,chi-server,spec" -include-tags "Anchor" -o anchor/api.gen.go openapi.yml
package api
import (
"context"
"encoding/hex"
"errors"
"fmt"
"log"
"net/http"
"time"
"github.com/ebiiim/btcgw/api/anchor"
"github.com/ebiiim/btcgw/auth"
"github.com/ebiiim/btcgw/gw"
"github.com/ebiiim/btcgw/model"
oapimiddleware "github.com/deepmap/oapi-codegen/pkg/chi-middleware"
"github.com/getkin/kin-openapi/openapi3filter"
)
// export
var AnchorHandlerFromMux = anchor.HandlerFromMux
// TODO: cache
type GatewayService struct {
gw.Gateway
auth.Authenticator
}
var _ anchor.ServerInterface = (*GatewayService)(nil)
func NewGatewayService(gw gw.Gateway, authenticator auth.Authenticator) *GatewayService {
g := &GatewayService{
Gateway: gw,
Authenticator: authenticator,
}
return g
}
func sendGatewayServiceError(w http.ResponseWriter, code int, err error, desc string) {
var pDesc *string = nil
if desc != "" {
pDesc = &desc
}
gsErr := anchor.Error{
Error: err.Error(),
ErrorDescription: pDesc,
}
WriteJSON(w, code, gsErr)
}
func (g *GatewayService) GetAnchorsDomainsDomainDigestsDigest(w http.ResponseWriter, r *http.Request, dom string, dig string) {
bdom, err1 := hex.DecodeString(dom)
bdig, err2 := hex.DecodeString(dig)
if err1 != nil || err2 != nil {
sendGatewayServiceError(w, http.StatusBadRequest, ErrInvalidParam, ErrInvalidParamDesc)
return
}
ctx := r.Context()
ar, err := g.GetRecord(ctx, bdom, bdig)
if err != nil {
log.Println(err)
}
if errors.Is(err, gw.ErrCouldNotGetRecord) {
sendGatewayServiceError(w, http.StatusNotFound, ErrDigestNotFound, ErrDigestNotFoundDesc)
return
}
WriteJSON(w, http.StatusOK, convertAnchorRecord(ar))
}
func (g *GatewayService) PatchAnchorsDomainsDomainDigestsDigest(w http.ResponseWriter, r *http.Request, dom string, dig string) {
bdom, err1 := hex.DecodeString(dom)
bdig, err2 := hex.DecodeString(dig)
if err1 != nil || err2 != nil {
sendGatewayServiceError(w, http.StatusBadRequest, ErrInvalidParam, ErrInvalidParamDesc)
return
}
ctx := r.Context()
note := fmt.Sprintf("Updated at %s", time.Now().Format(time.RFC3339))
err := g.RefreshRecord(ctx, bdom, bdig, nil, ¬e)
if err != nil {
log.Println(err)
}
if errors.Is(err, gw.ErrCouldNotRefreshRecord) {
sendGatewayServiceError(w, http.StatusNotFound, ErrDigestNotFound, ErrDigestNotFoundDesc)
return
}
w.WriteHeader(http.StatusNoContent)
}
func (g *GatewayService) PostAnchorsDomainsDomainDigestsDigest(w http.ResponseWriter, r *http.Request, dom string, dig string) {
bdom, err1 := hex.DecodeString(dom)
bdig, err2 := hex.DecodeString(dig)
if err1 != nil || err2 != nil {
sendGatewayServiceError(w, http.StatusBadRequest, ErrInvalidParam, ErrInvalidParamDesc)
return
}
ctx := r.Context()
_, err := g.GetRecord(ctx, bdom, bdig)
if err == nil {
sendGatewayServiceError(w, http.StatusInternalServerError, ErrDigestAlreadyExists, ErrDigestAlreadyExistsDesc)
return
}
btctx, err := g.RegisterTransaction(ctx, bdom, bdig)
if err != nil {
log.Println(err)
}
if errors.Is(err, gw.ErrCouldNotPutAnchor) {
sendGatewayServiceError(w, http.StatusInternalServerError, ErrRegisterFailed, ErrRegisterFailedDesc)
return
}
err = g.StoreRecord(ctx, btctx)
if err != nil {
log.Println(err)
}
if errors.Is(err, gw.ErrCouldNotStoreRecord) {
sendGatewayServiceError(w, http.StatusInternalServerError, ErrRegisterFailed, ErrRegisterFailedDesc)
return
}
ar, err := g.GetRecord(ctx, bdom, bdig)
if err != nil {
log.Println(err)
}
if errors.Is(err, gw.ErrCouldNotGetRecord) {
sendGatewayServiceError(w, http.StatusInternalServerError, ErrRegisterFailed, ErrRegisterFailedDesc)
return
}
WriteJSON(w, http.StatusOK, convertAnchorRecord(ar))
}
// OAPIValidator sets up OpenAPI validator and must be set as a middleware.
func (g *GatewayService) OAPIValidator() func(next http.Handler) http.Handler {
swagger, err := anchor.GetSwagger()
if err != nil {
panic(fmt.Sprintf("could not load swagger spec: %s", err))
}
// Skips validating server names.
swagger.Servers = nil
validatorOpts := &oapimiddleware.Options{}
if g.Authenticator == nil {
return oapimiddleware.OapiRequestValidatorWithOptions(swagger, validatorOpts)
}
validatorOpts.Options.AuthenticationFunc = func(ctx context.Context, input *openapi3filter.AuthenticationInput) error {
h := input.RequestValidationInput.Request.Header["X-Api-Key"]
if h == nil {
return errors.New("X-API-KEY not found")
}
if !g.AuthFunc(ctx, h[0], input.RequestValidationInput.PathParams) {
return errors.New("auth failed")
}
return nil
}
return oapimiddleware.OapiRequestValidatorWithOptions(swagger, validatorOpts)
}
func (g *GatewayService) Close() error {
err1 := g.Gateway.Close()
err2 := g.Authenticator.Close()
if err1 != nil || err2 != nil {
return fmt.Errorf("%w (Gateway: %v, Authenticator: %v)", ErrCouldNotClose, err1, err2)
}
return nil
}
func convertAnchor(a *model.Anchor) anchor.Anchor {
return anchor.Anchor{
Domain: hex.EncodeToString(a.BBc1DomainID[:]),
Digest: hex.EncodeToString(a.BBc1TransactionID[:]),
Chain: a.BTCNet.String(),
Time: int(a.Timestamp.Unix()),
Version: int(a.Version),
}
}
func convertAnchorRecord(ar *model.AnchorRecord) anchor.AnchorRecord {
var name *string = nil
if ar.BBc1DomainName != "" {
name = &(ar.BBc1DomainName)
}
var note *string = nil
if ar.Note != "" {
note = &(ar.Note)
}
return anchor.AnchorRecord{
Anchor: convertAnchor(ar.Anchor),
Bbc1name: name,
Btctx: hex.EncodeToString(ar.BTCTransactionID),
Confirmations: int(ar.Confirmations),
Note: note,
Time: int(ar.TransactionTime.Unix()),
}
}