|
| 1 | +package payment |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/base64" |
| 6 | + "encoding/json" |
| 7 | + "fmt" |
| 8 | + "log/slog" |
| 9 | + "net/http" |
| 10 | + "strconv" |
| 11 | + |
| 12 | + "github.com/bsv-blockchain/go-bsv-middleware/pkg/internal/authctx" |
| 13 | + "github.com/bsv-blockchain/go-bsv-middleware/pkg/internal/payctx" |
| 14 | + sdkUtils "github.com/bsv-blockchain/go-sdk/auth/utils" |
| 15 | + ec "github.com/bsv-blockchain/go-sdk/primitives/ec" |
| 16 | + "github.com/bsv-blockchain/go-sdk/wallet" |
| 17 | + "github.com/go-softwarelab/common/pkg/slogx" |
| 18 | + "github.com/go-softwarelab/common/pkg/to" |
| 19 | +) |
| 20 | + |
| 21 | +type Config struct { |
| 22 | + Logger *slog.Logger |
| 23 | + |
| 24 | + // CalculateRequestPrice determines the cost in satoshis for a request |
| 25 | + CalculateRequestPrice func(r *http.Request) (int, error) |
| 26 | +} |
| 27 | + |
| 28 | +// Middleware is the payment middleware handler that implements Direct Payment Protocol (DPP) for HTTP-based micropayments |
| 29 | +type Middleware struct { |
| 30 | + log *slog.Logger |
| 31 | + wallet wallet.Interface |
| 32 | + calculateRequestPrice func(r *http.Request) (int, error) |
| 33 | + nextHandler http.Handler |
| 34 | +} |
| 35 | + |
| 36 | +func NewMiddleware(next http.Handler, wallet wallet.Interface, opts ...func(*Config)) *Middleware { |
| 37 | + cfg := to.OptionsWithDefault(Config{ |
| 38 | + CalculateRequestPrice: DefaultPriceFunc, |
| 39 | + Logger: slog.Default(), |
| 40 | + }, opts...) |
| 41 | + |
| 42 | + logger := slogx.Child(cfg.Logger, "PaymentMiddleware") |
| 43 | + |
| 44 | + return &Middleware{ |
| 45 | + wallet: wallet, |
| 46 | + nextHandler: next, |
| 47 | + log: logger, |
| 48 | + calculateRequestPrice: cfg.CalculateRequestPrice, |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +// Handler returns a middleware handler function that processes payments |
| 53 | +func (m *Middleware) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| 54 | + ctx := r.Context() |
| 55 | + |
| 56 | + identityKey, err := authctx.ShouldGetIdentity(r.Context()) |
| 57 | + if err != nil { |
| 58 | + m.log.ErrorContext(ctx, "Failed to get identity from request context", slogx.Error(err)) |
| 59 | + m.respondWith(w, ErrServerMisconfigured) |
| 60 | + return |
| 61 | + } |
| 62 | + |
| 63 | + log := m.log.With(slog.String("identityKey", identityKey.ToDERHex())) |
| 64 | + |
| 65 | + price, err := m.calculateRequestPrice(r) |
| 66 | + if err != nil { |
| 67 | + log.ErrorContext(ctx, "Failed to calculate request price", slogx.Error(err)) |
| 68 | + m.respondWith(w, ErrPaymentInternal) |
| 69 | + return |
| 70 | + } |
| 71 | + |
| 72 | + if price == 0 { |
| 73 | + log.DebugContext(ctx, "Request without payment requested, proceeding to next handler", slog.Int("price", price)) |
| 74 | + m.proceedWithoutPayment(w, r) |
| 75 | + return |
| 76 | + } |
| 77 | + |
| 78 | + paymentData, err := m.extractPaymentData(r) |
| 79 | + if err != nil { |
| 80 | + log.ErrorContext(ctx, "Failed to extract payment data", slogx.Error(err)) |
| 81 | + m.respondWith(w, ErrMalformedPayment) |
| 82 | + return |
| 83 | + } |
| 84 | + |
| 85 | + if paymentData == nil { |
| 86 | + log.DebugContext(ctx, "Requesting payment", slog.Int("price", price)) |
| 87 | + err = m.requestPayment(w, r, price) |
| 88 | + if err != nil { |
| 89 | + log.ErrorContext(ctx, "Failed to prepare payment request", slogx.Error(err)) |
| 90 | + m.respondWith(w, ErrPaymentInternal) |
| 91 | + } |
| 92 | + return |
| 93 | + } |
| 94 | + |
| 95 | + log.DebugContext(ctx, "Processing payment", slog.Int("price", price)) |
| 96 | + paymentInfo, processErr := m.processPayment(ctx, paymentData, identityKey, price) |
| 97 | + if processErr != nil { |
| 98 | + log.ErrorContext(ctx, "Failed to process payment", slogx.Error(processErr.Cause)) |
| 99 | + m.respondWith(w, processErr) |
| 100 | + return |
| 101 | + } |
| 102 | + |
| 103 | + log.DebugContext(ctx, "Request successfully paid, proceeding to next handler", slog.Int("price", price)) |
| 104 | + m.proceedWithSuccessfulPayment(w, r, paymentInfo) |
| 105 | +} |
| 106 | + |
| 107 | +func (m *Middleware) respondWith(w http.ResponseWriter, resp Response) { |
| 108 | + w.Header().Set("Content-Type", "application/json") |
| 109 | + w.WriteHeader(resp.GetStatusCode()) |
| 110 | + err := json.NewEncoder(w).Encode(resp) |
| 111 | + if err != nil { |
| 112 | + m.log.Error("Error writing response body", slog.Any("response", resp), slogx.Error(err)) |
| 113 | + return |
| 114 | + } |
| 115 | +} |
| 116 | + |
| 117 | +func (m *Middleware) proceedWithoutPayment(w http.ResponseWriter, r *http.Request) { |
| 118 | + ctx := payctx.WithoutPayment(r.Context()) |
| 119 | + m.nextHandler.ServeHTTP(w, r.WithContext(ctx)) |
| 120 | +} |
| 121 | + |
| 122 | +func (m *Middleware) extractPaymentData(r *http.Request) (*Payment, error) { |
| 123 | + paymentHeader := r.Header.Get(HeaderPayment) |
| 124 | + if paymentHeader == "" { |
| 125 | + return nil, nil |
| 126 | + } |
| 127 | + |
| 128 | + var payment Payment |
| 129 | + if err := json.Unmarshal([]byte(paymentHeader), &payment); err != nil { |
| 130 | + return nil, fmt.Errorf("invalid payment data format: %w", err) |
| 131 | + } |
| 132 | + |
| 133 | + return &payment, nil |
| 134 | +} |
| 135 | + |
| 136 | +func (m *Middleware) requestPayment(w http.ResponseWriter, r *http.Request, price int) error { |
| 137 | + derivationPrefix, err := sdkUtils.CreateNonce(r.Context(), m.wallet, wallet.Counterparty{Type: wallet.CounterpartyTypeSelf}) |
| 138 | + if err != nil { |
| 139 | + return fmt.Errorf("failed to prepare derivation prefix as nonce: %w", err) |
| 140 | + } |
| 141 | + |
| 142 | + w.Header().Set(HeaderVersion, PaymentVersion) |
| 143 | + w.Header().Set(HeaderSatoshisRequired, strconv.Itoa(price)) |
| 144 | + w.Header().Set(HeaderDerivationPrefix, derivationPrefix) |
| 145 | + |
| 146 | + m.respondWith(w, ErrPaymentRequired.WithSatoshisRequired(price)) |
| 147 | + |
| 148 | + return nil |
| 149 | +} |
| 150 | + |
| 151 | +func (m *Middleware) proceedWithSuccessfulPayment(w http.ResponseWriter, r *http.Request, paymentInfo *payctx.Payment) { |
| 152 | + ctx := payctx.WithPayment(r.Context(), paymentInfo) |
| 153 | + w.Header().Set(HeaderSatoshisPaid, strconv.Itoa(paymentInfo.SatoshisPaid)) |
| 154 | + m.nextHandler.ServeHTTP(w, r.WithContext(ctx)) |
| 155 | +} |
| 156 | + |
| 157 | +func (m *Middleware) processPayment( |
| 158 | + ctx context.Context, |
| 159 | + paymentData *Payment, |
| 160 | + identityKey *ec.PublicKey, |
| 161 | + price int, |
| 162 | +) (*payctx.Payment, *ProcessingError) { |
| 163 | + derivationPrefix, err := base64.StdEncoding.DecodeString(paymentData.DerivationPrefix) |
| 164 | + if err != nil { |
| 165 | + return nil, NewProcessingError(ErrInvalidDerivationPrefix, fmt.Errorf("invalid derivation prefix: must be base64: %w", err)) |
| 166 | + } |
| 167 | + |
| 168 | + valid, err := sdkUtils.VerifyNonce(ctx, paymentData.DerivationPrefix, m.wallet, wallet.Counterparty{Type: wallet.CounterpartyTypeSelf}) |
| 169 | + if err != nil { |
| 170 | + return nil, NewProcessingError(ErrInvalidDerivationPrefix, fmt.Errorf("error verifying derivation prefix as nonce: %w", err)) |
| 171 | + } |
| 172 | + if !valid { |
| 173 | + return nil, NewProcessingError(ErrInvalidDerivationPrefix, fmt.Errorf("derivation prefix is invalid nonce")) |
| 174 | + } |
| 175 | + |
| 176 | + derivationSuffix, err := base64.StdEncoding.DecodeString(paymentData.DerivationSuffix) |
| 177 | + if err != nil { |
| 178 | + return nil, NewProcessingError(ErrInvalidDerivationSuffix, fmt.Errorf("invalid derivation suffix: must be base64: %w", err)) |
| 179 | + } |
| 180 | + |
| 181 | + result, err := m.wallet.InternalizeAction(ctx, wallet.InternalizeActionArgs{ |
| 182 | + Tx: paymentData.Transaction, |
| 183 | + Outputs: []wallet.InternalizeOutput{ |
| 184 | + { |
| 185 | + OutputIndex: 0, |
| 186 | + Protocol: wallet.InternalizeProtocolWalletPayment, |
| 187 | + PaymentRemittance: &wallet.Payment{ |
| 188 | + DerivationPrefix: derivationPrefix, |
| 189 | + DerivationSuffix: derivationSuffix, |
| 190 | + SenderIdentityKey: identityKey, |
| 191 | + }, |
| 192 | + }, |
| 193 | + }, |
| 194 | + Description: "Payment for request", |
| 195 | + }, |
| 196 | + PaymentOriginator, |
| 197 | + ) |
| 198 | + if err != nil { |
| 199 | + return nil, NewProcessingError(ErrPaymentFailed, fmt.Errorf("payment processing failed: %w", err)) |
| 200 | + } |
| 201 | + |
| 202 | + return &payctx.Payment{ |
| 203 | + SatoshisPaid: price, |
| 204 | + Accepted: result.Accepted, |
| 205 | + Tx: paymentData.Transaction, |
| 206 | + }, nil |
| 207 | +} |
0 commit comments