A peer-to-peer stack for code collaboration
Primops for generating and verifying signatures (#117)
James Haydon80e96e3b5050
diff --git a/package.yaml b/package.yamlindex 6edf212..fbd2196 100644--- a/package.yaml+++ b/package.yaml@@ -25,6 +25,7 @@ dependencies:- serialise- text- unordered-containers+- cryptonite- generics-eotwhen:- condition: impl(ghcjs)diff --git a/src/Radicle/Internal/Core.hs b/src/Radicle/Internal/Core.hsindex ac35083..4dbd98b 100644--- a/src/Radicle/Internal/Core.hs+++ b/src/Radicle/Internal/Core.hs@@ -15,7 +15,7 @@ import qualified Data.IntMap as IntMapimport Data.List.NonEmpty (NonEmpty)import qualified Data.List.NonEmpty as NonEmptyimport qualified Data.Map as Map-import Data.Scientific (Scientific)+import Data.Scientific (Scientific, floatingOrInteger)import Data.Semigroup ((<>))import Generics.Eotimport 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 prismisAtom :: Value -> Maybe IdentisAtom (Atom i) = pure iisAtom _ = 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 whereparseJSON = \caseA.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 ValuebaseEval val = case val of@@ -315,6 +317,12 @@ instance FromRad Scientific wherefromRad x = case x ofNumber 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 wherefromRad x = case x ofString n -> pure n@@ -352,6 +360,8 @@ class ToRad a whereinstance ToRad Int wheretoRad = Number . fromIntegral+instance ToRad Integer where+ toRad = Number . fromIntegralinstance ToRad Scientific wheretoRad = Numberinstance ToRad Text where@@ -403,7 +413,6 @@ mfn $$ vs = docallFn f vs'_ -> throwError $ TypeError "Trying to apply a non-function"-nil :: Valuenil = List []@@ -419,6 +428,10 @@ kwLookup key = Map.lookup (Keyword $ Ident key)(??) :: MonadError e m => Maybe a -> e -> m aa ?? 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 -> Valuediff --git a/src/Radicle/Internal/Crypto.hs b/src/Radicle/Internal/Crypto.hsnew file mode 100644index 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 sigdiff --git a/src/Radicle/Internal/Effects.hs b/src/Radicle/Internal/Effects.hsindex 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 whereimport Protolude hiding (TypeError)@@ -18,19 +19,25 @@ import System.Console.Haskeline)import Radicle.Internal.Core+import Radicle.Internal.Cryptoimport Radicle.Internal.Effects.Capabilitiesimport Radicle.Internal.Interpretimport Radicle.Internal.Prettyimport 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 = dolet 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!" $ \caseString 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.hsindex 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.Cryptoimport Radicle.Internal.Parseimport 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)+ )]wherediff --git a/test/spec/Radicle/Internal/TestCapabilities.hs b/test/spec/Radicle/Internal/TestCapabilities.hsindex 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 whereimport Protolude+import qualified Crypto.Random as CryptoRandimport qualified Data.Map.Strict as Mapimport qualified System.FilePath.Find as FPimport Radicle+import Radicle.Internal.Cryptoimport Radicle.Internal.Effects.Capabilitiesimport 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 wherecase Map.lookup fn fs ofJust f -> pure fNothing -> 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 adiff --git a/test/spec/Radicle/Tests.hs b/test/spec/Radicle/Tests.hsindex 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])]whererun stdin' prog = fst $ runTestWith replBindings stdin' prog