-
Notifications
You must be signed in to change notification settings - Fork 211
/
Metadata.hs
239 lines (215 loc) · 7.88 KB
/
Metadata.hs
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NumericUnderscores #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE TypeApplications #-}
-- |
-- Copyright: © 2018-2020 IOHK
-- License: Apache-2.0
--
-- HTTP-client(s) for fetching stake pool metadata from remote servers (directly
-- from pool operators, or from smash).
module Cardano.Pool.Metadata
(
-- * Fetch
fetchFromRemote
, StakePoolMetadataFetchLog (..)
-- * Construct URLs
, identityUrlBuilder
, registryUrlBuilder
-- * re-exports
, newManager
, defaultManagerSettings
) where
import Prelude
import Cardano.BM.Data.Severity
( Severity (..) )
import Cardano.BM.Data.Tracer
( HasPrivacyAnnotation (..), HasSeverityAnnotation (..) )
import Cardano.Wallet.Primitive.AddressDerivation
( hex )
import Cardano.Wallet.Primitive.Types
( StakePoolMetadata (..)
, StakePoolMetadataHash (..)
, StakePoolMetadataUrl (..)
)
import Control.Exception
( IOException, handle )
import Control.Monad
( when )
import Control.Monad.IO.Class
( MonadIO (..) )
import Control.Monad.Trans.Except
( ExceptT (..), except, runExceptT, throwE, withExceptT )
import Control.Tracer
( Tracer, traceWith )
import Crypto.Hash.Utils
( blake2b256 )
import Data.Aeson
( eitherDecodeStrict )
import Data.ByteArray.Encoding
( Base (..), convertToBase )
import Data.ByteString
( ByteString )
import Data.Coerce
( coerce )
import Data.List
( intercalate )
import Data.Text.Class
( ToText (..) )
import Fmt
( pretty )
import Network.HTTP.Client
( HttpException (..)
, Manager
, ManagerSettings
, brReadSome
, managerResponseTimeout
, requestFromURI
, responseBody
, responseStatus
, responseTimeoutMicro
, withResponse
)
import Network.HTTP.Types.Status
( status200, status404 )
import Network.URI
( URI (..), parseURI, pathSegments )
import qualified Data.ByteString.Char8 as B8
import qualified Data.ByteString.Lazy as BL
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Network.HTTP.Client.TLS as HTTPS
-- | Some default settings, overriding some of the library's default with
-- stricter values.
defaultManagerSettings :: ManagerSettings
defaultManagerSettings =
HTTPS.tlsManagerSettings
{ managerResponseTimeout = responseTimeoutMicro tenSeconds }
where
tenSeconds = 10_000_000 -- in μs
-- | Create a connection manager that supports TLS connections.
newManager :: MonadIO m => ManagerSettings -> m Manager
newManager = HTTPS.newTlsManagerWith
-- | Simply return a pool metadata url, unchanged
identityUrlBuilder
:: StakePoolMetadataUrl
-> StakePoolMetadataHash
-> Either HttpException URI
identityUrlBuilder (StakePoolMetadataUrl url) _ =
maybe (Left e) Right $ parseURI (T.unpack url)
where
e = InvalidUrlException (T.unpack url) "Invalid URL"
-- | Build a URL from a metadata hash compatible with an aggregation registry
registryUrlBuilder
:: URI
-> StakePoolMetadataUrl
-> StakePoolMetadataHash
-> Either HttpException URI
registryUrlBuilder baseUrl _ (StakePoolMetadataHash bytes) =
Right $ baseUrl
{ uriPath = "/" <> intercalate "/" (pathSegments baseUrl ++ [hash])
}
where
hash = T.unpack $ T.decodeUtf8 $ convertToBase Base16 bytes
fetchFromRemote
:: Tracer IO StakePoolMetadataFetchLog
-> [StakePoolMetadataUrl -> StakePoolMetadataHash -> Either HttpException URI]
-> Manager
-> StakePoolMetadataUrl
-> StakePoolMetadataHash
-> IO (Maybe StakePoolMetadata)
fetchFromRemote tr builders manager url hash = runExceptTLog $ do
chunk <- getChunk `fromFirst` builders
when (blake2b256 chunk /= coerce hash) $ throwE $ mconcat
[ "Metadata hash mismatch. Saw: "
, B8.unpack $ hex $ blake2b256 chunk
, ", but expected: "
, B8.unpack $ hex $ coerce @_ @ByteString hash
]
except $ eitherDecodeStrict chunk
where
runExceptTLog
:: ExceptT String IO StakePoolMetadata
-> IO (Maybe StakePoolMetadata)
runExceptTLog action = runExceptT action >>= \case
Left msg ->
Nothing <$ traceWith tr (MsgFetchPoolMetadataFailure hash msg)
Right meta ->
Just meta <$ traceWith tr (MsgFetchPoolMetadataSuccess hash meta)
-- Try each builder in order, but only if the previous builder led to an
-- IO exception. Other exceptions like HTTP exceptions are treated as
-- 'normal' responses from the an aggregation server and do not cause a
-- retry.
fromFirst _ [] =
throwE "Metadata server(s) didn't reply in a timely manner."
fromFirst action (builder:rest) = do
uri <- withExceptT show $ except $ builder url hash
action uri >>= \case
Nothing -> do
liftIO $ traceWith tr $ MsgFetchPoolMetadataFallback uri (null rest)
fromFirst action rest
Just chunk ->
pure chunk
getChunk :: URI -> ExceptT String IO (Maybe ByteString)
getChunk uri = do
req <- withExceptT show $ except $ requestFromURI uri
liftIO $ traceWith tr $ MsgFetchPoolMetadata hash uri
ExceptT
$ handle fromIOException
$ handle fromHttpException
$ withResponse req manager $ \res -> do
-- NOTE
-- Metadata are _supposed to_ be made of:
--
-- - A name (at most 50 UTF-8 bytes)
-- - An optional description (at most 250 UTF-8 bytes)
-- - A ticker (at most 5 UTF-8 bytes)
-- - A homepage (at most 100 UTF-8 bytes)
--
-- So, the total, including a pretty JSON encoding with newlines ought
-- to be less than 512 bytes. For security reasons, we only download the
-- first 512 bytes.
case responseStatus res of
s | s == status200 -> do
let body = responseBody res
Right . Just . BL.toStrict <$> brReadSome body 512
s | s == status404 -> do
pure $ Left "There's no known metadata for this pool."
s -> do
pure $ Left $ "The server replied something unexpected: " <> show s
fromIOException :: Monad m => IOException -> m (Either String a)
fromIOException = return . Left . ("IO exception: " <>) . show
fromHttpException :: Monad m => HttpException -> m (Either String (Maybe a))
fromHttpException = const (return $ Right Nothing)
data StakePoolMetadataFetchLog
= MsgFetchPoolMetadata StakePoolMetadataHash URI
| MsgFetchPoolMetadataSuccess StakePoolMetadataHash StakePoolMetadata
| MsgFetchPoolMetadataFailure StakePoolMetadataHash String
| MsgFetchPoolMetadataFallback URI Bool
deriving (Show, Eq)
instance HasPrivacyAnnotation StakePoolMetadataFetchLog
instance HasSeverityAnnotation StakePoolMetadataFetchLog where
getSeverityAnnotation = \case
MsgFetchPoolMetadata{} -> Info
MsgFetchPoolMetadataSuccess{} -> Info
MsgFetchPoolMetadataFailure{} -> Warning
MsgFetchPoolMetadataFallback{} -> Warning
instance ToText StakePoolMetadataFetchLog where
toText = \case
MsgFetchPoolMetadata hash uri -> mconcat
[ "Fetching metadata with hash ", pretty hash
, " from ", T.pack (show uri)
]
MsgFetchPoolMetadataSuccess hash meta -> mconcat
[ "Successfully fetched metadata with hash ", pretty hash
, ": ", T.pack (show meta)
]
MsgFetchPoolMetadataFailure hash msg -> mconcat
[ "Failed to fetch metadata with hash ", pretty hash, ": ", T.pack msg
]
MsgFetchPoolMetadataFallback uri noMoreUrls -> mconcat
[ "Couldn't reach server at ", T.pack (show uri), "."
, if noMoreUrls
then ""
else " Falling back using a different strategy."
]