zenith/src/Zenith/RPC.hs

84 lines
2.4 KiB
Haskell
Raw Normal View History

2024-07-23 18:46:37 +00:00
{-# LANGUAGE TypeOperators #-}
2024-07-24 21:03:49 +00:00
{-# LANGUAGE DeriveGeneric #-}
2024-07-23 18:46:37 +00:00
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE OverloadedStrings #-}
2024-07-24 21:03:49 +00:00
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
2024-07-23 18:46:37 +00:00
module Zenith.RPC where
import Data.Aeson
import qualified Data.Text as T
2024-07-24 21:03:49 +00:00
import Data.Typeable
import GHC.Generics (Generic)
2024-07-23 18:46:37 +00:00
import Servant
import ZcashHaskell.Types (RpcError(..), RpcResponse(..))
2024-07-24 21:03:49 +00:00
import Zenith.Types
( Config(..)
, RpcCall(..)
, ZenithMethod(..)
, ZenithParams(..)
)
2024-07-23 18:46:37 +00:00
type ZenithRPC
2024-07-24 21:13:13 +00:00
= "status" :> Get '[ JSON] Value :<|> BasicAuth "zenith-realm" Bool :> ReqBody
2024-07-23 18:46:37 +00:00
'[ JSON]
2024-07-24 21:13:13 +00:00
RpcCall :> Post '[ JSON] (RpcResponse Value)
2024-07-23 18:46:37 +00:00
2024-07-24 21:03:49 +00:00
zenithServer :: Config -> Server ZenithRPC
zenithServer config = getinfo :<|> handleRPC
2024-07-23 18:46:37 +00:00
where
getinfo :: Handler Value
getinfo =
return $
object
[ "version" .= ("0.7.0.0-beta" :: String)
, "network" .= ("testnet" :: String)
]
2024-07-24 21:13:13 +00:00
handleRPC :: Bool -> RpcCall -> Handler (RpcResponse Value)
handleRPC isAuth req =
2024-07-23 18:46:37 +00:00
case method req of
2024-07-24 21:03:49 +00:00
UnknownMethod ->
return $
MakeRpcResponse
(Just $ RpcError (-32601) "Method not found")
(callId req)
Nothing
2024-07-23 18:46:37 +00:00
GetInfo ->
case parameters req of
2024-07-24 21:03:49 +00:00
BlankParams ->
2024-07-23 18:46:37 +00:00
return $
MakeRpcResponse
Nothing
(callId req)
(Just $ object ["data" .= ("Here's your info" :: String)])
_anyOtherParams ->
return $
MakeRpcResponse
(Just $ RpcError (-32602) "Invalid params")
(callId req)
Nothing
Test ->
case parameters req of
TestParams x ->
return $
MakeRpcResponse Nothing (callId req) (Just $ object ["data" .= x])
_anyOtherParams ->
return $
MakeRpcResponse
(Just $ RpcError (-32602) "Invalid params")
(callId req)
Nothing
2024-07-24 21:03:49 +00:00
authenticate :: Config -> BasicAuthCheck Bool
authenticate config = BasicAuthCheck check
where
check (BasicAuthData username password) =
if username == c_zenithUser config && password == c_zenithPwd config
then return $ Authorized True
else return Unauthorized