/
Byron.hs
406 lines (365 loc) · 14.8 KB
/
Byron.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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE InstanceSigs #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RoleAnnotations #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
-- |
-- Copyright: © 2018-2020 IOHK
-- License: Apache-2.0
--
-- Implementation of address derivation for the random scheme, as
-- implemented by the legacy Cardano wallets.
--
-- For full documentation of the key derivation schemes,
-- see the "Cardano.Crypto.Wallet" module, and the implementation in
-- <https://github.com/input-output-hk/cardano-crypto/blob/4590efa638397e952a51a8994b5543e4ea3c1ecd/cbits/encrypted_sign.c cardano-crypto>.
module Cardano.Wallet.Primitive.AddressDerivation.Byron
( -- * Types
ByronKey(..)
-- * Generation
, unsafeGenerateKeyFromSeed
, generateKeyFromSeed
, minSeedLengthBytes
, unsafeMkByronKeyFromMasterKey
, mkByronKeyFromMasterKey
-- * Derivation
, deriveAccountPrivateKey
, deriveAddressPrivateKey
-- * Encoding / Decoding
, decodeLegacyAddress
) where
import Prelude
import Cardano.Crypto.Wallet
( DerivationScheme (DerivationScheme1)
, XPrv
, XPub
, deriveXPrv
, generate
, toXPub
, unXPrv
, unXPub
, xPrvChangePass
, xprv
)
import Cardano.Mnemonic
( SomeMnemonic (..), entropyToBytes, mnemonicToEntropy )
import Cardano.Wallet.Primitive.AddressDerivation
( Depth (..)
, DerivationType (..)
, ErrMkKeyFingerprint (..)
, Index (..)
, KeyFingerprint (..)
, MkKeyFingerprint (..)
, NetworkDiscriminant (..)
, Passphrase (..)
, PaymentAddress (..)
, PersistPrivateKey (..)
, WalletKey (..)
, fromHex
, hex
)
import Cardano.Wallet.Primitive.Types
( Address (..), Hash (..), ProtocolMagic (..), invariant, testnetMagic )
import Control.DeepSeq
( NFData )
import Control.Monad
( guard )
import Crypto.Hash
( hash )
import Crypto.Hash.Algorithms
( SHA512 (..) )
import Crypto.Hash.Utils
( blake2b256 )
import Data.ByteArray
( ScrubbedBytes )
import Data.ByteString
( ByteString )
import Data.Proxy
( Proxy (..) )
import GHC.Generics
( Generic )
import GHC.TypeLits
( KnownNat )
import qualified Cardano.Byron.Codec.Cbor as CBOR
import qualified Cardano.Wallet.Primitive.AddressDerivation as W
import qualified Codec.CBOR.Encoding as CBOR
import qualified Codec.CBOR.Write as CBOR
import qualified Crypto.KDF.PBKDF2 as PBKDF2
import qualified Data.ByteArray as BA
import qualified Data.ByteString.Char8 as B8
{-------------------------------------------------------------------------------
Key Types
-------------------------------------------------------------------------------}
-- | Material for deriving HD random scheme keys, which can be used for making
-- addresses.
data ByronKey (depth :: Depth) key = ByronKey
{ getKey :: key
-- ^ The raw private or public key.
, derivationPath :: DerivationPath depth
-- ^ The address derivation indices for the level of this key.
, payloadPassphrase :: Passphrase "addr-derivation-payload"
-- ^ Used for encryption of payload containing address derivation path.
} deriving stock (Generic)
instance (NFData key, NFData (DerivationPath depth)) => NFData (ByronKey depth key)
deriving instance (Show key, Show (DerivationPath depth)) => Show (ByronKey depth key)
deriving instance (Eq key, Eq (DerivationPath depth)) => Eq (ByronKey depth key)
-- | The hierarchical derivation indices for a given level/depth.
type family DerivationPath (depth :: Depth) :: * where
-- The root key is generated from the seed.
DerivationPath 'RootK =
()
-- The account key is generated from the root key and account index.
DerivationPath 'AccountK =
Index 'WholeDomain 'AccountK
-- The address key is generated from the account key and address index.
DerivationPath 'AddressK =
(Index 'WholeDomain 'AccountK, Index 'WholeDomain 'AddressK)
instance WalletKey ByronKey where
changePassphrase = changePassphraseRnd
-- Extract the public key part of a private key.
publicKey = mapKey toXPub
-- Hash a public key to some other representation.
digest = hash . unXPub . getKey
getRawKey = getKey
keyTypeDescriptor _ = "rnd"
instance KnownNat pm => PaymentAddress ('Testnet pm) ByronKey where
paymentAddress k = Address
$ CBOR.toStrictByteString
$ CBOR.encodeAddress (getKey k)
[ CBOR.encodeDerivationPathAttr pwd acctIx addrIx
, CBOR.encodeProtocolMagicAttr (testnetMagic @pm)
]
where
(acctIx, addrIx) = derivationPath k
pwd = payloadPassphrase k
liftPaymentAddress (KeyFingerprint bytes) =
Address bytes
instance PaymentAddress 'Mainnet ByronKey where
paymentAddress k = Address
$ CBOR.toStrictByteString
$ CBOR.encodeAddress (getKey k)
[ CBOR.encodeDerivationPathAttr pwd acctIx addrIx ]
where
(acctIx, addrIx) = derivationPath k
pwd = payloadPassphrase k
liftPaymentAddress (KeyFingerprint bytes) =
Address bytes
instance MkKeyFingerprint ByronKey Address where
paymentKeyFingerprint addr@(Address bytes) =
case CBOR.deserialiseCbor CBOR.decodeAddressPayload bytes of
Just _ -> Right $ KeyFingerprint bytes
Nothing -> Left $ ErrInvalidAddress addr (Proxy @ByronKey)
{-------------------------------------------------------------------------------
Encoding / Decoding
-------------------------------------------------------------------------------}
-- | Attempt decoding a 'ByteString' into an 'Address'. This merely checks that
-- the underlying bytestring has a "valid" structure / format without doing much
-- more.
decodeLegacyAddress :: Maybe ProtocolMagic -> ByteString -> Maybe Address
decodeLegacyAddress expectedMagic bytes = do
payload <- CBOR.deserialiseCbor CBOR.decodeAddressPayload bytes
decodedMagic <- CBOR.deserialiseCbor CBOR.decodeProtocolMagicAttr payload
-- NOTE
-- Legacy / Byron addesses on Jörmungandr can have any network
-- discrimination. In practice, the genesis file only contains
-- Mainnet addresses whereas the network discrimination is set to testnet.
--
-- This create a very annoying discrepency where it becomes tricky to
-- enforce any sort of discrimination on legacy addresses. As a result, for
-- Jörmungandr (identified by as being 'Testnet 0'), we simply don't.
guard (expectedMagic == itnMagic || decodedMagic == expectedMagic)
pure (Address bytes)
where
itnMagic = Just (ProtocolMagic 0)
{-------------------------------------------------------------------------------
Key generation
-------------------------------------------------------------------------------}
-- | The amount of entropy carried by a BIP-39 12-word mnemonic is 16 bytes.
minSeedLengthBytes :: Int
minSeedLengthBytes = 16
-- | Generate a root key from a corresponding seed.
-- The seed should be at least 16 bytes.
generateKeyFromSeed
:: SomeMnemonic
-> Passphrase "encryption"
-> ByronKey 'RootK XPrv
generateKeyFromSeed = unsafeGenerateKeyFromSeed ()
-- | Generate a new key from seed. Note that the @depth@ is left open so that
-- the caller gets to decide what type of key this is. This is mostly for
-- testing, in practice, seeds are used to represent root keys, and one should
-- use 'generateKeyFromSeed'.
unsafeGenerateKeyFromSeed
:: DerivationPath depth
-> SomeMnemonic
-> Passphrase "encryption"
-> ByronKey depth XPrv
unsafeGenerateKeyFromSeed derivationPath (SomeMnemonic mw) (Passphrase pwd) = ByronKey
{ getKey = masterKey
, derivationPath
, payloadPassphrase = hdPassphrase (toXPub masterKey)
}
where
masterKey = generate (hashSeed seed') pwd
seed = entropyToBytes $ mnemonicToEntropy mw
seed' = invariant
("seed length : " <> show (BA.length seed)
<> " in (Passphrase \"seed\") is not valid")
seed
(\s -> BA.length s >= minSeedLengthBytes && BA.length s <= 255)
-- | Hash the seed entropy (generated from mnemonic) used to initiate a HD
-- wallet. This increases the key length to 34 bytes, selectKey is greater than the
-- minimum for 'generate' (32 bytes).
--
-- Note that our current implementation deviates from BIP-39 because we use a
-- hash function (Blake2b) rather than key stretching with PBKDF2.
--
-- There are two methods of hashing the seed entropy, for different use cases.
--
-- 1. Normal random derivation wallet seeds. The seed entropy is hashed using
-- Blake2b_256, inside a double CBOR serialization sandwich.
--
-- 2. Seeds for redeeming paper wallets. The seed entropy is hashed using
-- Blake2b_256, without any serialization.
hashSeed :: ScrubbedBytes -> ScrubbedBytes
hashSeed = BA.convert . cbor . blake2b256 . cbor . BA.convert
where
cbor = CBOR.toStrictByteString . CBOR.encodeBytes
-- | Derive a symmetric key for encrypting and authenticating the address
-- derivation path. PBKDF2 encryption using HMAC with the hash algorithm SHA512
-- is employed.
hdPassphrase :: XPub -> Passphrase "addr-derivation-payload"
hdPassphrase masterKey = Passphrase $
PBKDF2.generate
(PBKDF2.prfHMAC SHA512)
(PBKDF2.Parameters 500 32)
(unXPub masterKey)
("address-hashing" :: ByteString)
mkByronKeyFromMasterKey
:: XPrv
-> ByronKey 'RootK XPrv
mkByronKeyFromMasterKey = unsafeMkByronKeyFromMasterKey ()
unsafeMkByronKeyFromMasterKey
:: DerivationPath depth
-> XPrv
-> ByronKey depth XPrv
unsafeMkByronKeyFromMasterKey derivationPath masterKey = ByronKey
{ getKey = masterKey
, derivationPath
, payloadPassphrase = hdPassphrase (toXPub masterKey)
}
{-------------------------------------------------------------------------------
Passphrase
-------------------------------------------------------------------------------}
-- | Re-encrypt the private key using a different passphrase, and regenerate
-- the payload passphrase.
--
-- **Important**:
-- This function doesn't check that the old passphrase is correct! Caller is
-- expected to have already checked that. Using an incorrect passphrase here
-- will lead to very bad thing.
changePassphraseRnd
:: Passphrase "encryption"
-> Passphrase "encryption"
-> ByronKey depth XPrv
-> ByronKey depth XPrv
changePassphraseRnd (Passphrase oldPwd) (Passphrase newPwd) key = ByronKey
{ getKey = masterKey
, derivationPath = derivationPath key
, payloadPassphrase = hdPassphrase (toXPub masterKey)
}
where
masterKey = xPrvChangePass oldPwd newPwd (getKey key)
{-------------------------------------------------------------------------------
HD derivation
-------------------------------------------------------------------------------}
-- TODO
-- This instance is unsound. It only exists because we need to derive the
-- reward account in the wallet engine when making transaction (in case there
-- are any withdrawals).
--
-- With 'ByronKey', withdrawals will always be `0`, and the result of this
-- function shouldn't be evaluated (relying on lazyness here). If they do, then
-- we're doing something wrong.
instance W.HardDerivation ByronKey where
type AddressIndexDerivationType ByronKey = 'WholeDomain
deriveAccountPrivateKey _ _ _ = error
"unsound evaluation of 'deriveAccountPrivateKey' in the context of Byron key"
deriveAddressPrivateKey _ _ _ _ = error
"unsound evaluation of 'deriveAddressPrivateKey' in the context of Byron key"
-- | Derives account private key from the given root private key, using
-- derivation scheme 1.
--
-- NOTE: The caller is expected to provide the corresponding passphrase (and to
-- have checked that the passphrase is valid). Providing a wrong passphrase will
-- not make the function fail but will instead, yield an incorrect new key that
-- doesn't belong to the wallet.
deriveAccountPrivateKey
:: Passphrase "encryption"
-> ByronKey 'RootK XPrv
-> Index 'WholeDomain 'AccountK
-> ByronKey 'AccountK XPrv
deriveAccountPrivateKey (Passphrase pwd) masterKey idx@(Index accIx) = ByronKey
{ getKey = deriveXPrv DerivationScheme1 pwd (getKey masterKey) accIx
, derivationPath = idx
, payloadPassphrase = payloadPassphrase masterKey
}
-- | Derives address private key from the given account private key, using
-- derivation scheme 1.
--
-- NOTE: The caller is expected to provide the corresponding passphrase (and to
-- have checked that the passphrase is valid). Providing a wrong passphrase will
-- not make the function fail but will instead, yield an incorrect new key that
-- doesn't belong to the wallet.
deriveAddressPrivateKey
:: Passphrase "encryption"
-> ByronKey 'AccountK XPrv
-> Index 'WholeDomain 'AddressK
-> ByronKey 'AddressK XPrv
deriveAddressPrivateKey (Passphrase pwd) accountKey idx@(Index addrIx) = ByronKey
{ getKey = deriveXPrv DerivationScheme1 pwd (getKey accountKey) addrIx
, derivationPath = (derivationPath accountKey, idx)
, payloadPassphrase = payloadPassphrase accountKey
}
{-------------------------------------------------------------------------------
Storing and retrieving keys
-------------------------------------------------------------------------------}
instance PersistPrivateKey (ByronKey 'RootK) where
serializeXPrv ((ByronKey k _ (Passphrase p)), h) =
( hex (unXPrv k) <> ":" <> hex p
, hex . getHash $ h
)
unsafeDeserializeXPrv (k, h) = either err id $ (,)
<$> fmap mkKey (deserializeKey k)
<*> fmap Hash (fromHex h)
where
err _ = error "unsafeDeserializeXPrv: unable to deserialize ByronKey"
mkKey (key, pwd) = ByronKey key () pwd
deserializeKey
:: ByteString
-> Either String
( XPrv
, Passphrase "addr-derivation-payload"
)
deserializeKey b = case map (fromHex @ByteString) (B8.split ':' b) of
[Right rawK, Right p] ->
case xprv rawK of
Right k' -> Right (k', Passphrase (BA.convert p))
Left e -> Left e
_ ->
Left "Key input must be two hex strings separated by :"
{-------------------------------------------------------------------------------
Utils
-------------------------------------------------------------------------------}
-- | Transform the wrapped key.
mapKey :: (key -> key') -> ByronKey depth key -> ByronKey depth key'
mapKey f rnd = rnd { getKey = f (getKey rnd) }