Skip to content
Permalink
Browse files

AddressDerivation: more serialize/deserialize key funcs

  • Loading branch information...
rvl committed May 16, 2019
1 parent 4c1b866 commit b67758188b6f57b9e85da3a59a4d67344b19f57c
Showing with 28 additions and 10 deletions.
  1. +28 −10 lib/core/src/Cardano/Wallet/Primitive/AddressDerivation.hs
@@ -60,8 +60,10 @@ module Cardano.Wallet.Primitive.AddressDerivation
, deriveAddressPublicKey

-- * Storing and retrieving keys
, serializeKey
, deserializeKey
, serializeXPrv
, deserializeXPrv
, serializeXPub
, deserializeXPub
) where

import Prelude
@@ -77,6 +79,7 @@ import Cardano.Crypto.Wallet
, unXPrv
, unXPub
, xprv
, xpub
)
import Cardano.Wallet.Primitive.Mnemonic
( CheckSumBits
@@ -577,28 +580,43 @@ class KeyToAddress target where
Storing and retrieving keys
-------------------------------------------------------------------------------}

fromHexText :: ByteString -> Either String ByteString
fromHexText = convertFromBase Base16

toHexText :: ByteString -> ByteString
toHexText = convertToBase Base16

-- | Convert a private key and its password hash into hexadecimal strings
-- suitable for storing in a text file or database column.
serializeKey
serializeXPrv
:: (Key purpose XPrv, Hash "encryption")
-> (ByteString, ByteString)
serializeKey (k, h) = (hexText . unXPrv . getKey $ k, hexText . getHash $ h)
where hexText = convertToBase Base16
serializeXPrv (k, h) =
( toHexText . unXPrv . getKey $ k
, toHexText . getHash $ h )

-- | The reverse of 'serializeKey'. This may fail if the inputs are not valid
-- | The reverse of 'serializeXPrv'. This may fail if the inputs are not valid
-- hexadecimal strings, or if the key is of the wrong length.
deserializeKey
deserializeXPrv
:: (ByteString, ByteString)
-- ^ Hexadecimal encoded private key and password hash
-> Either String (Key purpose XPrv, Hash "encryption")
deserializeKey (k, h) = (,)
deserializeXPrv (k, h) = (,)
<$> fmap Key (xprvFromText k)
<*> fmap Hash (fromHexText h)
where
fromHexText :: ByteString -> Either String ByteString
fromHexText = convertFromBase Base16
xprvFromText = xprv <=< fromHexText

-- | Convert a public key into a hexadecimal string suitable for storing in a
-- text file or database column.
serializeXPub :: Key purpose XPub -> ByteString
serializeXPub = toHexText . unXPub . getKey

-- | The reverse of 'serializeXPub'. This will fail if the input is not a valid
-- hexadecimal string of the correct length.
deserializeXPub :: ByteString -> Either String (Key purpose XPub)
deserializeXPub = fmap Key . (xpub <=< fromHexText)

-- $use
-- 'Key' and 'Index' allow for representing public keys, private keys, hardened
-- indexes and soft (non-hardened) indexes for various level in a non-ambiguous

0 comments on commit b677581

Please sign in to comment.
You can’t perform that action at this time.