Skip to content

A peer-to-peer stack for code collaboration

Primops for generating and verifying signatures (#117)

James Haydon80e96e3b5050
diff --git a/package.yaml b/package.yaml
index 6edf212..fbd2196 100644
--- a/package.yaml
+++ b/package.yaml
@@ -25,6 +25,7 @@ dependencies:
- serialise
- text
- unordered-containers
+- cryptonite
- generics-eot
when:
- condition: impl(ghcjs)
diff --git a/src/Radicle/Internal/Core.hs b/src/Radicle/Internal/Core.hs
index ac35083..4dbd98b 100644
--- a/src/Radicle/Internal/Core.hs
+++ b/src/Radicle/Internal/Core.hs
@@ -15,7 +15,7 @@ import qualified Data.IntMap as IntMap
import Data.List.NonEmpty (NonEmpty)
import qualified Data.List.NonEmpty as NonEmpty
import qualified Data.Map as Map
-import Data.Scientific (Scientific)
+import Data.Scientific (Scientific, floatingOrInteger)
import Data.Semigroup ((<>))
import Generics.Eot
import qualified GHC.Exts as GhcExts
@@ -115,13 +115,16 @@ data Value =
| Lambda [Ident] (NonEmpty Value) (Env Value)
deriving (Eq, Show, Ord, Read, Generic)
-instance Serialise Value
-
-- Should just be a prism
isAtom :: Value -> Maybe Ident
isAtom (Atom i) = pure i
isAtom _ = Nothing
+-- should be a prism
+isInt :: Value -> Maybe Integer
+isInt (Number s) = either (const Nothing :: Double -> Maybe Integer) pure (floatingOrInteger s)
+isInt _ = Nothing
+
instance A.FromJSON Value where
parseJSON = \case
A.Number n -> pure $ Number n
@@ -289,7 +292,6 @@ eval val = do
_ -> throwError $ OtherError "eval: should return list with value and new env"
-
-- | The built-in, original, eval.
baseEval :: Monad m => Value -> Lang m Value
baseEval val = case val of
@@ -315,6 +317,12 @@ instance FromRad Scientific where
fromRad x = case x of
Number n -> pure n
_ -> Left "Expecting number"
+instance FromRad Integer where
+ fromRad = \case
+ Number s -> case floatingOrInteger s of
+ Left (_ :: Double) -> Left "Expecting whole number"
+ Right i -> pure i
+ _ -> Left "Expecting number"
instance FromRad Text where
fromRad x = case x of
String n -> pure n
@@ -352,6 +360,8 @@ class ToRad a where
instance ToRad Int where
toRad = Number . fromIntegral
+instance ToRad Integer where
+ toRad = Number . fromIntegral
instance ToRad Scientific where
toRad = Number
instance ToRad Text where
@@ -403,7 +413,6 @@ mfn $$ vs = do
callFn f vs'
_ -> throwError $ TypeError "Trying to apply a non-function"
-
nil :: Value
nil = List []
@@ -419,6 +428,10 @@ kwLookup key = Map.lookup (Keyword $ Ident key)
(??) :: MonadError e m => Maybe a -> e -> m a
a ?? n = n `note` a
+hoistEither :: MonadError e m => Either e a -> m a
+hoistEither (Left e) = throwError e
+hoistEither (Right x) = pure x
+
-- * Generic encoding/decoding of Radicle values.
toRadG :: forall a. (HasEot a, ToRadG (Eot a)) => a -> Value
diff --git a/src/Radicle/Internal/Crypto.hs b/src/Radicle/Internal/Crypto.hs
new file mode 100644
index 0000000..fbc7e37
--- /dev/null
+++ b/src/Radicle/Internal/Crypto.hs
@@ -0,0 +1,78 @@
+{-# OPTIONS_GHC -fno-warn-orphans #-}
+
+module Radicle.Internal.Crypto
+ ( PublicKey
+ , PrivateKey
+ , Signature
+ , hasher
+ , defaultCurve
+ , verifySignature
+ , signText
+ , generateKeyPair
+ , MonadRandom(..)
+ ) where
+
+import Protolude
+
+import Crypto.Hash.Algorithms
+import Crypto.PubKey.ECC.ECDSA
+import Crypto.PubKey.ECC.Generate (generate)
+import Crypto.PubKey.ECC.Types
+import Crypto.Random
+import Crypto.Random.Types (MonadRandom)
+
+import Radicle.Internal.Core
+
+deriving instance Generic PublicKey
+instance FromRad PublicKey
+instance ToRad PublicKey
+
+deriving instance Generic PrivateKey
+instance FromRad PrivateKey
+instance ToRad PrivateKey
+
+deriving instance Generic Curve
+instance FromRad Curve
+instance ToRad Curve
+
+deriving instance Generic Point
+instance FromRad Point
+instance ToRad Point
+
+deriving instance Generic CurveBinary
+instance FromRad CurveBinary
+instance ToRad CurveBinary
+
+deriving instance Generic CurvePrime
+instance FromRad CurvePrime
+instance ToRad CurvePrime
+
+deriving instance Generic CurveCommon
+instance FromRad CurveCommon
+instance ToRad CurveCommon
+
+deriving instance Generic Signature
+instance FromRad Signature
+instance ToRad Signature
+
+hasher :: Blake2b_256
+hasher = Blake2b_256
+
+generateKeyPair :: MonadRandom m => Curve -> m (PublicKey, PrivateKey)
+generateKeyPair = generate
+
+defaultCurve :: Curve
+defaultCurve = getCurveByName SEC_p256k1
+
+signText :: forall m. MonadRandom m => PrivateKey -> Text -> m Signature
+signText key = signBytes . toS
+ where
+ signBytes :: ByteString -> m Signature
+ signBytes = sign key hasher
+
+-- | Verify a signed message with the public key.
+verifySignature :: PublicKey -> Signature -> Text -> Bool
+verifySignature key sig = verifyBytes . toS
+ where
+ verifyBytes :: ByteString -> Bool
+ verifyBytes = verify hasher key sig
diff --git a/src/Radicle/Internal/Effects.hs b/src/Radicle/Internal/Effects.hs
index c6c35b6..16d7942 100644
--- a/src/Radicle/Internal/Effects.hs
+++ b/src/Radicle/Internal/Effects.hs
@@ -1,3 +1,4 @@
+{-# OPTIONS_GHC -fno-warn-orphans #-}
module Radicle.Internal.Effects where
import Protolude hiding (TypeError)
@@ -18,19 +19,25 @@ import System.Console.Haskeline
)
import Radicle.Internal.Core
+import Radicle.Internal.Crypto
import Radicle.Internal.Effects.Capabilities
import Radicle.Internal.Interpret
import Radicle.Internal.Pretty
import Radicle.Internal.Primops
-
type ReplM m =
( Monad m, Stdout (Lang m), Stdin (Lang m)
+ , MonadRandom m
, ReadFile (Lang m)
, GetEnv (Lang m) Value
, SetEnv (Lang m) Value )
+instance MonadRandom (InputT IO) where
+ getRandomBytes = liftIO . getRandomBytes
+instance MonadRandom m => MonadRandom (LangT (Bindings (Primops m)) m) where
+ getRandomBytes = lift . getRandomBytes
+
repl :: Maybe FilePath -> Text -> Bindings (Primops (InputT IO)) -> IO ()
repl histFile preCode bindings = do
let settings = setComplete completion
@@ -121,8 +128,28 @@ replPrimops = Primops . Map.fromList $ first toIdent <$>
_ -> throwError $ TypeError "read-file: expects a string"
)
, ( "load!"
- , evalOneArg "load" $ \case
+ , evalOneArg "load!" $ \case
String filename -> readFileS filename >>= interpretMany "[load!]"
_ -> throwError $ TypeError "load: expects a string"
)
+ , ( "gen-key-pair!"
+ , evalArgs $ \case
+ [curvev] -> do
+ curve <- hoistEither . first OtherError $ fromRad curvev
+ (pk, sk) <- generateKeyPair curve
+ let pkv = toRad pk
+ let skv = toRad sk
+ pure . Dict . Map.fromList $
+ [ (Keyword (Ident "private-key"), skv)
+ , (Keyword (Ident "public-key"), pkv)
+ ]
+ xs -> throwError $ WrongNumberOfArgs "gen-key-pair!" 0 (length xs)
+ )
+ , ( "gen-signature!"
+ , evalArgs $ \case
+ [skv, String msg] -> do
+ sk <- hoistEither . first OtherError $ fromRad skv
+ toRad <$> signText sk msg
+ _ -> throwError $ TypeError "gen-signature!: expects a string."
+ )
]
diff --git a/src/Radicle/Internal/Primops.hs b/src/Radicle/Internal/Primops.hs
index a5dd86b..c23aeec 100644
--- a/src/Radicle/Internal/Primops.hs
+++ b/src/Radicle/Internal/Primops.hs
@@ -15,6 +15,7 @@ import Data.Scientific (Scientific, floatingOrInteger)
import GHC.Exts (IsList(..))
import Radicle.Internal.Core
+import Radicle.Internal.Crypto
import Radicle.Internal.Parse
import Radicle.Internal.Pretty
@@ -260,6 +261,20 @@ purePrimops = Primops $ fromList $ first Ident <$>
, evalOneArg "to-json" $ \v -> String . toS . Aeson.encode <$>
maybeJson v ?? OtherError "Could not serialise value to JSON"
)
+ , ( "default-ecc-curve",
+ evalArgs $ \case
+ [] -> pure $ toRad defaultCurve
+ xs -> throwError $ WrongNumberOfArgs "default-ecc-curve" 0 (length xs)
+ )
+ , ( "verify-signature"
+ , evalArgs $ \case
+ [keyv, sigv, String msg] -> do
+ key <- hoistEither . first OtherError $ fromRad keyv
+ sig <- hoistEither . first OtherError $ fromRad sigv
+ pure . Boolean $ verifySignature key sig msg
+ [_, _, _] -> throwError $ OtherError "verify-signature: message must be a string"
+ xs -> throwError $ WrongNumberOfArgs "verify-signature" 3 (length xs)
+ )
]
where
diff --git a/test/spec/Radicle/Internal/TestCapabilities.hs b/test/spec/Radicle/Internal/TestCapabilities.hs
index d5fd047..7954653 100644
--- a/test/spec/Radicle/Internal/TestCapabilities.hs
+++ b/test/spec/Radicle/Internal/TestCapabilities.hs
@@ -4,10 +4,12 @@ module Radicle.Internal.TestCapabilities where
import Protolude
+import qualified Crypto.Random as CryptoRand
import qualified Data.Map.Strict as Map
import qualified System.FilePath.Find as FP
import Radicle
+import Radicle.Internal.Crypto
import Radicle.Internal.Effects.Capabilities
import Paths_radicle
@@ -17,6 +19,7 @@ data WorldState = WorldState
, worldStateStdout :: [Text]
, worldStateEnv :: Env Value
, worldStateFiles :: Map Text Text
+ , worldDRG :: CryptoRand.ChaChaDRG
}
@@ -35,6 +38,7 @@ runTestWithFiles bindings inputs files action =
, worldStateStdout = []
, worldStateEnv = bindingsEnv bindings
, worldStateFiles = files
+ , worldDRG = CryptoRand.drgNewSeed (CryptoRand.seedFromInteger 4) -- chosen by fair dice roll
}
in case runState (fmap fst $ runLang bindings $ interpretMany "[test]" action) ws of
(val, st) -> (val, reverse $ worldStateStdout st)
@@ -90,3 +94,10 @@ instance {-# OVERLAPPING #-} ReadFile TestLang where
case Map.lookup fn fs of
Just f -> pure f
Nothing -> throwError . OtherError $ "File not found: " <> fn
+
+instance MonadRandom (State WorldState) where
+ getRandomBytes i = do
+ drg <- gets worldDRG
+ let (a, drg') = CryptoRand.randomBytesGenerate i drg
+ modify $ \ws -> ws { worldDRG = drg' }
+ pure a
diff --git a/test/spec/Radicle/Tests.hs b/test/spec/Radicle/Tests.hs
index 0d841e0..e0ec8d8 100644
--- a/test/spec/Radicle/Tests.hs
+++ b/test/spec/Radicle/Tests.hs
@@ -546,6 +546,16 @@ test_repl_primops =
|]
files = Map.singleton "foo.rad" "(define foo 42) (define bar 8)"
runFiles files prog @?= Right (Number 50)
+ , testCase "generating and verifying cryptographic signatures works" $
+ let prog = [s|
+ (define my-keys (gen-key-pair! (default-ecc-curve)))
+ (define not-my-keys (gen-key-pair! (default-ecc-curve)))
+ (define sig (gen-signature! (lookup :private-key my-keys) "hello"))
+ (define tt (verify-signature (lookup :public-key my-keys) sig "hello"))
+ (define ff (verify-signature (lookup :public-key not-my-keys) sig "hello"))
+ (list tt ff)
+ |]
+ in run [] prog @?= Right (List [Boolean True, Boolean False])
]
where
run stdin' prog = fst $ runTestWith replBindings stdin' prog