-
Notifications
You must be signed in to change notification settings - Fork 156
/
Copy pathAddress.hs
322 lines (267 loc) · 10.4 KB
/
Address.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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE UndecidableInstances #-}
-- | Functionality related to 'Address' data type and related types.
module Cardano.Chain.Common.Address
( Address(..)
, Address'(..)
-- * Formatting
, addressF
, addressDetailedF
, fromCBORTextAddress
-- * Spending data checks
, checkAddrSpendingData
, checkVerKeyAddress
, checkRedeemAddress
-- * Encoding/Decoding
, addrToBase58
, toCBORAddr
, toCBORAddrCRC32
, decodeAddressBase58
, encodeAddressBase58
-- * Utilities
, addrAttributesUnwrapped
, addrNetworkMagic
-- * Pattern-matching helpers
, isRedeemAddress
-- * Construction
, makeAddress
, makeVerKeyAddress
, makeVerKeyHdwAddress
, makeRedeemAddress
)
where
import Cardano.Prelude
import qualified Data.Aeson as Aeson
import Data.ByteString.Base58
(Alphabet(..), bitcoinAlphabet, decodeBase58, encodeBase58)
import Data.Text.Internal.Builder (Builder)
import Formatting
(Format, bprint, build, builder, formatToString, later)
import qualified Formatting.Buildable as B
import NoThunks.Class (NoThunks (..))
import Text.JSON.Canonical
( FromJSON(..)
, FromObjectKey(..)
, JSValue(..)
, ToJSON(..)
, ToObjectKey(..)
, toJSString
)
import Cardano.Binary
( DecoderError(..)
, Encoding
, FromCBOR(..)
, ToCBOR(..)
, decodeFull'
, decodeListLenCanonical
, matchSize
, serialize'
)
import Cardano.Chain.Common.CBOR
(encodeCrcProtected, encodedCrcProtectedSizeExpr, decodeCrcProtected)
import Cardano.Chain.Common.AddrAttributes
(AddrAttributes(..), HDAddressPayload)
import Cardano.Chain.Common.AddressHash (AddressHash, addressHash)
import Cardano.Chain.Common.AddrSpendingData
(AddrSpendingData(..), AddrType(..), addrSpendingDataToType)
import Cardano.Chain.Common.Attributes (Attributes(..), mkAttributes)
import Cardano.Chain.Common.NetworkMagic (NetworkMagic(..))
import Cardano.Crypto.Hashing (hashHexF)
import Cardano.Crypto.Signing
( VerificationKey
, RedeemVerificationKey
)
-- | Hash of this data is stored in 'Address'. This type exists mostly
-- for internal usage.
newtype Address' = Address'
{ unAddress' :: (AddrType, AddrSpendingData, Attributes AddrAttributes)
} deriving (Eq, Show, Generic)
deriving newtype ToCBOR
-- We need to use canonical encodings for @Address'@ so that all implementations
-- agree on the `AddressHash`. The components of the @Address'@ also have
-- canonical encodings enforced.
instance FromCBOR Address' where
fromCBOR = do
len <- decodeListLenCanonical
matchSize "Address'" 3 len
fmap Address' $ (,,) <$> fromCBOR <*> fromCBOR <*> fromCBOR
-- | 'Address' is where you can send Lovelace
data Address = Address
{ addrRoot :: !(AddressHash Address')
-- ^ Root of imaginary pseudo Merkle tree stored in this address.
, addrAttributes :: !(Attributes AddrAttributes)
-- ^ Attributes associated with this address.
, addrType :: !AddrType
-- ^ The type of this address. Should correspond to
-- 'AddrSpendingData', but it can't be checked statically, because
-- spending data is hashed.
} deriving (Eq, Ord, Generic, Show)
deriving anyclass (NFData, NoThunks)
-- Used for debugging purposes only
instance Aeson.ToJSON Address where
instance ToCBOR Address where
toCBOR addr =
encodeCrcProtected (addrRoot addr, addrAttributes addr, addrType addr)
encodedSizeExpr size pxy =
encodedCrcProtectedSizeExpr size
$ (,,)
<$> (addrRoot <$> pxy)
<*> (addrAttributes <$> pxy)
<*> (addrType <$> pxy)
instance FromCBOR Address where
fromCBOR = do
(root, attributes, addrType') <- decodeCrcProtected
pure $ Address
{ addrRoot = root
, addrAttributes = attributes
, addrType = addrType'
}
instance B.Buildable [Address] where
build = bprint listJson
instance Monad m => ToObjectKey m Address where
toObjectKey = pure . toJSString . formatToString addressF
instance MonadError SchemaError m => FromObjectKey m Address where
fromObjectKey = fmap Just . parseJSString fromCBORTextAddress . JSString
instance Monad m => ToJSON m Address where
toJSON = fmap JSString . toObjectKey
instance MonadError SchemaError m => FromJSON m Address where
fromJSON = parseJSString fromCBORTextAddress
instance HeapWords Address where
heapWords (Address root attrs typ) = heapWords3 root attrs typ
--------------------------------------------------------------------------------
-- Formatting, pretty-printing
--------------------------------------------------------------------------------
-- | A formatter showing guts of an 'Address'
addressDetailedF :: Format r (Address -> r)
addressDetailedF = later $ \addr -> bprint
(builder . " address with root " . hashHexF . ", attributes: " . build)
(formattedType $ addrType addr)
(addrRoot addr)
(addrAttributes addr)
where
formattedType :: AddrType -> Builder
formattedType = \case
ATVerKey -> "VerKey"
ATRedeem -> "Redeem"
-- | Currently we use Bitcoin alphabet for representing addresses in base58
addrAlphabet :: Alphabet
addrAlphabet = bitcoinAlphabet
addrToBase58 :: Address -> ByteString
addrToBase58 = encodeBase58 addrAlphabet . serialize'
instance B.Buildable Address where
build = B.build . decodeUtf8 . addrToBase58
-- | Specialized formatter for 'Address'
addressF :: Format r (Address -> r)
addressF = build
-- | A function which decodes base58-encoded 'Address'
{-# DEPRECATED fromCBORTextAddress "Use decodeAddressBase58 instead" #-}
fromCBORTextAddress :: Text -> Either DecoderError Address
fromCBORTextAddress = fromCBORAddress . encodeUtf8
where
fromCBORAddress :: ByteString -> Either DecoderError Address
fromCBORAddress bs = do
let
base58Err = DecoderErrorCustom
"Address"
"Invalid base58 representation of address"
dbs <- maybeToRight base58Err $ decodeBase58 addrAlphabet bs
decodeFull' dbs
-- | Decode an address from Base58 encoded Text.
decodeAddressBase58 :: Text -> Either DecoderError Address
decodeAddressBase58 = fromCBORTextAddress
-- | Encode an address to Text.
-- `decodeAddressBase58 (encodeAddressBase58 x) === Right x`
encodeAddressBase58 :: Address -> Text
encodeAddressBase58 = decodeUtf8 . addrToBase58
--------------------------------------------------------------------------------
-- Constructors
--------------------------------------------------------------------------------
-- | Make an 'Address' from spending data and attributes.
makeAddress :: AddrSpendingData -> AddrAttributes -> Address
makeAddress spendingData attributesUnwrapped = Address
{ addrRoot = addressHash address'
, addrAttributes = attributes
, addrType = addrType'
}
where
addrType' = addrSpendingDataToType spendingData
attributes = mkAttributes attributesUnwrapped
address' = Address' (addrType', spendingData, attributes)
-- | A function for making an address from 'VerificationKey'
makeVerKeyAddress :: NetworkMagic -> VerificationKey -> Address
makeVerKeyAddress nm = makeVerKeyAddressImpl nm Nothing
-- | A function for making an HDW address
makeVerKeyHdwAddress
:: NetworkMagic
-> HDAddressPayload
-- ^ Derivation path
-> VerificationKey
-> Address
makeVerKeyHdwAddress nm path = makeVerKeyAddressImpl nm (Just path)
makeVerKeyAddressImpl :: NetworkMagic -> Maybe HDAddressPayload -> VerificationKey -> Address
makeVerKeyAddressImpl nm path key = makeAddress spendingData attrs
where
spendingData = VerKeyASD key
attrs = AddrAttributes { aaVKDerivationPath = path
, aaNetworkMagic = nm }
-- | A function for making an address from 'RedeemVerificationKey'
makeRedeemAddress :: NetworkMagic -> RedeemVerificationKey -> Address
makeRedeemAddress nm key = makeAddress spendingData attrs
where
spendingData = RedeemASD key
attrs = AddrAttributes { aaVKDerivationPath = Nothing
, aaNetworkMagic = nm }
--------------------------------------------------------------------------------
-- Checks
--------------------------------------------------------------------------------
-- | Check whether given 'AddrSpendingData' corresponds to given 'Address'
checkAddrSpendingData :: AddrSpendingData -> Address -> Bool
checkAddrSpendingData asd addr =
addrRoot addr
== addressHash address'
&& addrType addr
== addrSpendingDataToType asd
where address' = Address' (addrType addr, asd, addrAttributes addr)
-- | Check if given 'Address' is created from given 'VerificationKey'
checkVerKeyAddress :: VerificationKey -> Address -> Bool
checkVerKeyAddress vk = checkAddrSpendingData (VerKeyASD vk)
-- | Check if given 'Address' is created from given 'RedeemVerificationKey'
checkRedeemAddress :: RedeemVerificationKey -> Address -> Bool
checkRedeemAddress rvk = checkAddrSpendingData (RedeemASD rvk)
--------------------------------------------------------------------------------
-- Utils
--------------------------------------------------------------------------------
-- | Get 'AddrAttributes' from 'Address'
addrAttributesUnwrapped :: Address -> AddrAttributes
addrAttributesUnwrapped = attrData . addrAttributes
-- | Get 'NetworkMagic' from 'Address'
addrNetworkMagic :: Address -> NetworkMagic
addrNetworkMagic = aaNetworkMagic . addrAttributesUnwrapped
--------------------------------------------------------------------------------
-- Pattern-matching helpers
--------------------------------------------------------------------------------
-- | Check whether an 'Address' is redeem address
isRedeemAddress :: Address -> Bool
isRedeemAddress addr = case addrType addr of
ATRedeem -> True
_ -> False
-- Encodes the `Address` __without__ the CRC32.
-- It's important to keep this function separated from the `toCBOR`
-- definition to avoid that `toCBOR` would call `crc32` and
-- the latter invoke `crc32Update`, which would then try to call `toCBOR`
-- indirectly once again, in an infinite loop.
toCBORAddr :: Address -> Encoding
toCBORAddr addr =
toCBOR (addrRoot addr) <> toCBOR (addrAttributes addr) <> toCBOR
(addrType addr)
toCBORAddrCRC32 :: Address -> Encoding
toCBORAddrCRC32 addr =
encodeCrcProtected (addrRoot addr, addrAttributes addr, addrType addr)