Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add-on library for recoverable signatures #45

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions scripts/format
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,5 @@ REPO_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )/.." &> /dev/null && pwd )

find $REPO_DIR/secp256k1-haskell/src -type f -name "*.hs" | xargs ormolu -i
find $REPO_DIR/secp256k1-haskell/test -type f -name "*.hs" | xargs ormolu -i
find $REPO_DIR/secp256k1-haskell-recovery/src -type f -name "*.hs" | xargs ormolu -i
find $REPO_DIR/secp256k1-haskell-recovery/test -type f -name "*.hs" | xargs ormolu -i
8 changes: 8 additions & 0 deletions secp256k1-haskell-recovery/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# Changelog
All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).

## 0.1.0
Initial version
19 changes: 19 additions & 0 deletions secp256k1-haskell-recovery/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
Copyright 2020 Haskoin Developers

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

2 changes: 2 additions & 0 deletions secp256k1-haskell-recovery/Setup.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
import Distribution.Simple
main = defaultMain
44 changes: 44 additions & 0 deletions secp256k1-haskell-recovery/package.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
name: secp256k1-haskell-recovery
version: 0.1.0
synopsis: Bindings for recoverable signatures feature of secp256k1
description: Sign and verify recoverable signatures using the secp256k1 library.
category: Crypto
author: Evgeny Osipenko
maintainer: [email protected]
copyright: (c) 2023 Evgeny Osipenko
license: MIT
license-file: LICENSE
github: haskoin/secp256k1-haskell
homepage: http://github.com/haskoin/secp256k1-haskell#readme
extra-source-files:
- CHANGELOG.md
dependencies:
- base >=4.9 && <5
- base16 >=1.0
- bytestring >=0.10.8 && <0.12
- entropy >=0.3.8 && <0.5
- deepseq >=1.4.2 && <1.5
- hashable >=1.2.6 && <1.5
- QuickCheck >=2.9.2 && <2.15
- secp256k1-haskell
- string-conversions >=0.4 && <0.5
- unliftio-core >=0.1.0 && <0.3
library:
source-dirs: src
tests:
spec:
main: Spec.hs
source-dirs: test
ghc-options:
- -threaded
- -rtsopts
- -with-rtsopts=-N
verbatim:
build-tool-depends:
hspec-discover:hspec-discover
dependencies:
- hspec
- secp256k1-haskell-recovery
- monad-par
- mtl
- HUnit
75 changes: 75 additions & 0 deletions secp256k1-haskell-recovery/secp256k1-haskell-recovery.cabal
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
cabal-version: 1.12

-- This file has been generated from package.yaml by hpack version 0.36.0.
--
-- see: https://github.com/sol/hpack

name: secp256k1-haskell-recovery
version: 0.1.0
synopsis: Bindings for recoverable signatures feature of secp256k1
description: Sign and verify recoverable signatures using the secp256k1 library.
category: Crypto
homepage: http://github.com/haskoin/secp256k1-haskell#readme
bug-reports: https://github.com/haskoin/secp256k1-haskell/issues
author: Evgeny Osipenko
maintainer: [email protected]
copyright: (c) 2023 Evgeny Osipenko
license: MIT
license-file: LICENSE
build-type: Simple
extra-source-files:
CHANGELOG.md

source-repository head
type: git
location: https://github.com/haskoin/secp256k1-haskell

library
exposed-modules:
Crypto.Secp256k1.Internal.Recovery
Crypto.Secp256k1.Internal.RecoveryOps
Crypto.Secp256k1.Recovery
other-modules:
Paths_secp256k1_haskell_recovery
hs-source-dirs:
src
build-depends:
QuickCheck >=2.9.2 && <2.15
, base >=4.9 && <5
, base16 >=1.0
, bytestring >=0.10.8 && <0.12
, deepseq >=1.4.2 && <1.5
, entropy >=0.3.8 && <0.5
, hashable >=1.2.6 && <1.5
, secp256k1-haskell
, string-conversions ==0.4.*
, unliftio-core >=0.1.0 && <0.3
default-language: Haskell2010

test-suite spec
type: exitcode-stdio-1.0
main-is: Spec.hs
other-modules:
Crypto.Secp256k1.RecoverySpec
Paths_secp256k1_haskell_recovery
hs-source-dirs:
test
ghc-options: -threaded -rtsopts -with-rtsopts=-N
build-depends:
HUnit
, QuickCheck >=2.9.2 && <2.15
, base >=4.9 && <5
, base16 >=1.0
, bytestring >=0.10.8 && <0.12
, deepseq >=1.4.2 && <1.5
, entropy >=0.3.8 && <0.5
, hashable >=1.2.6 && <1.5
, hspec
, monad-par
, mtl
, secp256k1-haskell
, secp256k1-haskell-recovery
, string-conversions ==0.4.*
, unliftio-core >=0.1.0 && <0.3
default-language: Haskell2010
build-tool-depends: hspec-discover:hspec-discover
179 changes: 179 additions & 0 deletions secp256k1-haskell-recovery/src/Crypto/Secp256k1/Internal/Recovery.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE ImportQualifiedPost #-}
{-# LANGUAGE OverloadedRecordDot #-}
{-# LANGUAGE NoFieldSelectors #-}

-- |
-- Module : Crypto.Secp256k1.Internal.Recovery
-- License : UNLICENSE
-- Maintainer : Jean-Pierre Rupp <[email protected]>
-- Stability : experimental
-- Portability : POSIX
--
-- Crytpographic functions related to recoverable signatures from Bitcoin’s secp256k1 library.
--
-- The API for this module may change at any time. This is an internal module only
-- exposed for hacking and experimentation.
module Crypto.Secp256k1.Internal.Recovery where

import Control.DeepSeq (NFData)
import Control.Monad (unless, (<=<))
import Crypto.Secp256k1.Internal.Base (Msg (..), PubKey (..), SecKey (..), Sig (..))
import Crypto.Secp256k1.Internal.Context (Ctx (..))
import Crypto.Secp256k1.Internal.ForeignTypes
( isSuccess,
)
import Crypto.Secp256k1.Internal.RecoveryOps
( ecdsaRecover,
ecdsaRecoverableSignatureConvert,
ecdsaRecoverableSignatureParseCompact,
ecdsaRecoverableSignatureSerializeCompact,
ecdsaSignRecoverable,
)
import Crypto.Secp256k1.Internal.Util
( decodeHex,
showsHex,
unsafePackByteString,
unsafeUseByteString,
)
import Data.ByteString (ByteString)
import Data.ByteString qualified as BS
import Data.Maybe (fromMaybe)
import Data.String (IsString (..))
import Data.Word (Word8)
import Foreign
( alloca,
free,
mallocBytes,
nullFunPtr,
nullPtr,
peek,
)
import GHC.Generics (Generic)
import System.IO.Unsafe (unsafePerformIO)
import Text.Read
( Lexeme (String),
lexP,
parens,
pfail,
readPrec,
)

newtype RecSig = RecSig {get :: ByteString}
deriving (Eq, Generic, NFData)

data CompactRecSig = CompactRecSig
{ rs :: !ByteString,
v :: {-# UNPACK #-} !Word8
}
deriving (Eq, Generic)

instance NFData CompactRecSig

compactRecSig :: ByteString -> Maybe CompactRecSig
compactRecSig bs
| BS.length bs == 65,
BS.last bs <= 3 =
Just (CompactRecSig (BS.take 64 bs) (BS.last bs))
| otherwise = Nothing

serializeCompactRecSig :: CompactRecSig -> ByteString
serializeCompactRecSig (CompactRecSig bs v) =
BS.snoc bs v

compactRecSigFromString :: String -> Maybe CompactRecSig
compactRecSigFromString = compactRecSig <=< decodeHex

instance Read CompactRecSig where
readPrec = parens $ do
String str <- lexP
maybe pfail return $ compactRecSigFromString str

instance IsString CompactRecSig where
fromString = fromMaybe e . compactRecSigFromString
where
e = error "Could not decode signature from hex string"

instance Show CompactRecSig where
showsPrec _ = showsHex . serializeCompactRecSig

-- | Parse a compact ECDSA signature (64 bytes + recovery id).
importCompactRecSig :: Ctx -> CompactRecSig -> Maybe RecSig
importCompactRecSig (Ctx ctx) (CompactRecSig sig_rs sig_v)
| BS.length sig_rs == 64,
sig_v <= 3 = unsafePerformIO $
unsafeUseByteString sig_rs $ \(sig_rs_ptr, _) -> do
out_rec_sig_ptr <- mallocBytes 65
ret <-
ecdsaRecoverableSignatureParseCompact
ctx
out_rec_sig_ptr
sig_rs_ptr
(fromIntegral sig_v)
if isSuccess ret
then do
out_bs <- unsafePackByteString (out_rec_sig_ptr, 65)
return (Just (RecSig out_bs))
else do
free out_rec_sig_ptr
return Nothing
| otherwise = Nothing

-- | Serialize an ECDSA signature in compact format (64 bytes + recovery id).
exportCompactRecSig :: Ctx -> RecSig -> CompactRecSig
exportCompactRecSig (Ctx ctx) (RecSig rec_sig_bs) = unsafePerformIO $
unsafeUseByteString rec_sig_bs $ \(rec_sig_ptr, _) ->
alloca $ \out_v_ptr -> do
out_sig_ptr <- mallocBytes 64
ret <-
ecdsaRecoverableSignatureSerializeCompact
ctx
out_sig_ptr
out_v_ptr
rec_sig_ptr
unless (isSuccess ret) $ do
free out_sig_ptr
error "Could not obtain compact signature"
out_bs <- unsafePackByteString (out_sig_ptr, 64)
out_v <- peek out_v_ptr
return $ CompactRecSig out_bs (fromIntegral out_v)

-- | Convert a recoverable signature into a normal signature.
convertRecSig :: Ctx -> RecSig -> Sig
convertRecSig (Ctx ctx) (RecSig rec_sig_bs) = unsafePerformIO $
unsafeUseByteString rec_sig_bs $ \(rec_sig_ptr, _) -> do
out_ptr <- mallocBytes 64
ret <- ecdsaRecoverableSignatureConvert ctx out_ptr rec_sig_ptr
unless (isSuccess ret) $
error "Could not convert a recoverable signature"
out_bs <- unsafePackByteString (out_ptr, 64)
return $ Sig out_bs

-- | Create a recoverable ECDSA signature.
signRecMsg :: Ctx -> SecKey -> Msg -> RecSig
signRecMsg (Ctx ctx) (SecKey sec_key) (Msg m) = unsafePerformIO $
unsafeUseByteString sec_key $ \(sec_key_ptr, _) ->
unsafeUseByteString m $ \(msg_ptr, _) -> do
rec_sig_ptr <- mallocBytes 65
ret <- ecdsaSignRecoverable ctx rec_sig_ptr msg_ptr sec_key_ptr nullFunPtr nullPtr
unless (isSuccess ret) $ do
free rec_sig_ptr
error "could not sign message"
RecSig <$> unsafePackByteString (rec_sig_ptr, 65)

-- | Recover an ECDSA public key from a signature.
recover :: Ctx -> RecSig -> Msg -> Maybe PubKey
recover (Ctx ctx) (RecSig rec_sig) (Msg m) = unsafePerformIO $
unsafeUseByteString rec_sig $ \(rec_sig_ptr, _) ->
unsafeUseByteString m $ \(msg_ptr, _) -> do
pub_key_ptr <- mallocBytes 64
ret <- ecdsaRecover ctx pub_key_ptr rec_sig_ptr msg_ptr
if isSuccess ret
then do
pub_key_bs <- unsafePackByteString (pub_key_ptr, 64)
return (Just (PubKey pub_key_bs))
else do
free pub_key_ptr
return Nothing
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
-- |
-- Module : Crypto.Secp256k1.Internal.RecoveryOps
-- License : UNLICENSE
-- Maintainer : Jean-Pierre Rupp <[email protected]>
-- Stability : experimental
-- Portability : POSIX
--
-- The API for this module may change at any time. This is an internal module only
-- exposed for hacking and experimentation.
module Crypto.Secp256k1.Internal.RecoveryOps where

import Crypto.Secp256k1.Internal.ForeignTypes (Compact64, LCtx, Msg32, NonceFun, PubKey64, Ret, SecKey32, Sig64)
import Foreign (FunPtr, Ptr)
import Foreign.C (CInt (..))

data RecSig65

foreign import ccall safe "secp256k1_recovery.h secp256k1_ecdsa_recoverable_signature_parse_compact"
ecdsaRecoverableSignatureParseCompact ::
Ptr LCtx ->
Ptr RecSig65 ->
Ptr Compact64 ->
CInt ->
IO Ret

foreign import ccall safe "secp256k1_recovery.h secp256k1_ecdsa_recoverable_signature_convert"
ecdsaRecoverableSignatureConvert ::
Ptr LCtx ->
Ptr Sig64 ->
Ptr RecSig65 ->
IO Ret

foreign import ccall safe "secp256k1_recovery.h secp256k1_ecdsa_recoverable_signature_serialize_compact"
ecdsaRecoverableSignatureSerializeCompact ::
Ptr LCtx ->
Ptr Compact64 ->
Ptr CInt ->
Ptr RecSig65 ->
IO Ret

foreign import ccall safe "secp256k1_recovery.h secp256k1_ecdsa_sign_recoverable"
ecdsaSignRecoverable ::
Ptr LCtx ->
Ptr RecSig65 ->
Ptr Msg32 ->
Ptr SecKey32 ->
FunPtr (NonceFun a) ->
-- | nonce data
Ptr a ->
IO Ret

foreign import ccall safe "secp256k1_recovery.h secp256k1_ecdsa_recover"
ecdsaRecover ::
Ptr LCtx ->
Ptr PubKey64 ->
Ptr RecSig65 ->
Ptr Msg32 ->
IO Ret
Loading