{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE UnboxedTuples #-}

{- |
Module: Crypto.Curve.Secp256k1.MuSig2.Internal.OneShot
Copyright: (c) 2025 Jose Storopoli
License: MIT
Maintainer: Jose Storopoli <jose@storopoli.com>

A secret that can be read at most once: a pinned mutable byte array holding
the secret bytes plus a state word. 'claimOneShot' flips the state from fresh
to claimed with an atomic compare-and-swap, copies the secret out and
zero-fills it in the buffer. Every later claim, through any copy of the
handle and from any thread, gets 'Nothing'.

The buffer is pinned, so the garbage collector never moves (and so never
copies) it. Zero-filling it is best-effort hygiene, not a guarantee: the
bytes the secret was built from, the copy 'claimOneShot' returns and
anything computed from it are ordinary heap values that are not wiped. A
buffer that is never claimed is not wiped either before its memory is
reused.

Not part of the public API.
-}
module Crypto.Curve.Secp256k1.MuSig2.Internal.OneShot (
  OneShot,
  newOneShot,
  claimOneShot,
  isClaimed,
  peekOneShot,
) where

import Control.Exception (mask_, onException)
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Internal as BI
import qualified Data.ByteString.Unsafe as BU
import GHC.Exts (
  Int (..),
  MutableByteArray#,
  Ptr (..),
  RealWorld,
  casIntArray#,
  copyAddrToByteArray#,
  copyMutableByteArrayToAddr#,
  isTrue#,
  newAlignedPinnedByteArray#,
  readIntArray#,
  setByteArray#,
  touch#,
  writeIntArray#,
  (+#),
  (==#),
 )
import GHC.IO (IO (..))

{- | A handle to a pinned buffer. Copies of the handle share the buffer and
its state.

Layout: one machine word of state (@0@ fresh, @1@ claimed) at byte offset
@0@, then the secret bytes from byte offset 'secretOffset'.
-}
data OneShot = OneShot !Int (MutableByteArray# RealWorld)

-- | Byte offset of the secret in the buffer (after the state word).
secretOffset :: Int
secretOffset :: Int
secretOffset = Int
8

-- | Copies the bytes into a new pinned buffer, in the fresh state.
newOneShot :: ByteString -> IO OneShot
newOneShot :: ByteString -> IO OneShot
newOneShot ByteString
bytes = do
  let !(I# Int#
n) = ByteString -> Int
BS.length ByteString
bytes
      !(I# Int#
off) = Int
secretOffset
  os <- (State# RealWorld -> (# State# RealWorld, OneShot #)) -> IO OneShot
forall a. (State# RealWorld -> (# State# RealWorld, a #)) -> IO a
IO ((State# RealWorld -> (# State# RealWorld, OneShot #))
 -> IO OneShot)
-> (State# RealWorld -> (# State# RealWorld, OneShot #))
-> IO OneShot
forall a b. (a -> b) -> a -> b
$ \State# RealWorld
s0 -> case Int#
-> Int#
-> State# RealWorld
-> (# State# RealWorld, MutableByteArray# RealWorld #)
forall d.
Int# -> Int# -> State# d -> (# State# d, MutableByteArray# d #)
newAlignedPinnedByteArray# (Int#
off Int# -> Int# -> Int#
+# Int#
n) Int#
off State# RealWorld
s0 of
    (# State# RealWorld
s1, MutableByteArray# RealWorld
mba #) -> case MutableByteArray# RealWorld
-> Int# -> Int# -> State# RealWorld -> State# RealWorld
forall d.
MutableByteArray# d -> Int# -> Int# -> State# d -> State# d
writeIntArray# MutableByteArray# RealWorld
mba Int#
0# Int#
0# State# RealWorld
s1 of
      State# RealWorld
s2 -> (# State# RealWorld
s2, Int -> MutableByteArray# RealWorld -> OneShot
OneShot (Int# -> Int
I# Int#
n) MutableByteArray# RealWorld
mba #)
  BU.unsafeUseAsCString bytes $ \(Ptr Addr#
addr) -> OneShot -> (MutableByteArray# RealWorld -> IO ()) -> IO ()
forall a. OneShot -> (MutableByteArray# RealWorld -> IO a) -> IO a
withBuffer OneShot
os ((MutableByteArray# RealWorld -> IO ()) -> IO ())
-> (MutableByteArray# RealWorld -> IO ()) -> IO ()
forall a b. (a -> b) -> a -> b
$ \MutableByteArray# RealWorld
mba ->
    (State# RealWorld -> (# State# RealWorld, () #)) -> IO ()
forall a. (State# RealWorld -> (# State# RealWorld, a #)) -> IO a
IO ((State# RealWorld -> (# State# RealWorld, () #)) -> IO ())
-> (State# RealWorld -> (# State# RealWorld, () #)) -> IO ()
forall a b. (a -> b) -> a -> b
$ \State# RealWorld
s -> (# Addr#
-> MutableByteArray# RealWorld
-> Int#
-> Int#
-> State# RealWorld
-> State# RealWorld
forall d.
Addr#
-> MutableByteArray# d -> Int# -> Int# -> State# d -> State# d
copyAddrToByteArray# Addr#
addr MutableByteArray# RealWorld
mba Int#
off Int#
n State# RealWorld
s, () #)
  pure os

{- | Claims the secret: atomically marks the buffer claimed, returns a copy of
the secret and zero-fills it in the buffer. 'Nothing' if it was claimed
before.

Asynchronous exceptions are masked, so a claim either does not happen or
both marks the buffer and wipes it.
-}
claimOneShot :: OneShot -> IO (Maybe ByteString)
claimOneShot :: OneShot -> IO (Maybe ByteString)
claimOneShot os :: OneShot
os@(OneShot Int
len MutableByteArray# RealWorld
mba) = IO (Maybe ByteString) -> IO (Maybe ByteString)
forall a. IO a -> IO a
mask_ (IO (Maybe ByteString) -> IO (Maybe ByteString))
-> IO (Maybe ByteString) -> IO (Maybe ByteString)
forall a b. (a -> b) -> a -> b
$ do
  won <- (State# RealWorld -> (# State# RealWorld, Bool #)) -> IO Bool
forall a. (State# RealWorld -> (# State# RealWorld, a #)) -> IO a
IO ((State# RealWorld -> (# State# RealWorld, Bool #)) -> IO Bool)
-> (State# RealWorld -> (# State# RealWorld, Bool #)) -> IO Bool
forall a b. (a -> b) -> a -> b
$ \State# RealWorld
s0 -> case MutableByteArray# RealWorld
-> Int#
-> Int#
-> Int#
-> State# RealWorld
-> (# State# RealWorld, Int# #)
forall d.
MutableByteArray# d
-> Int# -> Int# -> Int# -> State# d -> (# State# d, Int# #)
casIntArray# MutableByteArray# RealWorld
mba Int#
0# Int#
0# Int#
1# State# RealWorld
s0 of
    (# State# RealWorld
s1, Int#
old #) -> (# State# RealWorld
s1, Int# -> Bool
isTrue# (Int#
old Int# -> Int# -> Int#
==# Int#
0#) #)
  if not won
    then pure Nothing
    else do
      secret <- copyOut os `onException` wipe
      wipe
      pure (Just secret)
 where
  !(I# Int#
n) = Int
len
  !(I# Int#
off) = Int
secretOffset
  wipe :: IO ()
wipe = (State# RealWorld -> (# State# RealWorld, () #)) -> IO ()
forall a. (State# RealWorld -> (# State# RealWorld, a #)) -> IO a
IO ((State# RealWorld -> (# State# RealWorld, () #)) -> IO ())
-> (State# RealWorld -> (# State# RealWorld, () #)) -> IO ()
forall a b. (a -> b) -> a -> b
$ \State# RealWorld
s -> (# MutableByteArray# RealWorld
-> Int# -> Int# -> Int# -> State# RealWorld -> State# RealWorld
forall d.
MutableByteArray# d -> Int# -> Int# -> Int# -> State# d -> State# d
setByteArray# MutableByteArray# RealWorld
mba Int#
off Int#
n Int#
0# State# RealWorld
s, () #)

-- | Whether the buffer has been claimed.
isClaimed :: OneShot -> IO Bool
isClaimed :: OneShot -> IO Bool
isClaimed (OneShot Int
_ MutableByteArray# RealWorld
mba) = (State# RealWorld -> (# State# RealWorld, Bool #)) -> IO Bool
forall a. (State# RealWorld -> (# State# RealWorld, a #)) -> IO a
IO ((State# RealWorld -> (# State# RealWorld, Bool #)) -> IO Bool)
-> (State# RealWorld -> (# State# RealWorld, Bool #)) -> IO Bool
forall a b. (a -> b) -> a -> b
$ \State# RealWorld
s0 -> case MutableByteArray# RealWorld
-> Int# -> State# RealWorld -> (# State# RealWorld, Int# #)
forall d.
MutableByteArray# d -> Int# -> State# d -> (# State# d, Int# #)
readIntArray# MutableByteArray# RealWorld
mba Int#
0# State# RealWorld
s0 of
  (# State# RealWorld
s1, Int#
st #) -> (# State# RealWorld
s1, Int# -> Bool
isTrue# (Int#
st Int# -> Int# -> Int#
==# Int#
1#) #)

{- | The current contents of the secret area, without claiming it (all zero
after a claim). For tests only: it defeats the point of the buffer.
-}
peekOneShot :: OneShot -> IO ByteString
peekOneShot :: OneShot -> IO ByteString
peekOneShot = OneShot -> IO ByteString
copyOut

-- | A copy of the secret area.
copyOut :: OneShot -> IO ByteString
copyOut :: OneShot -> IO ByteString
copyOut os :: OneShot
os@(OneShot Int
len MutableByteArray# RealWorld
_) =
  Int -> (Ptr Word8 -> IO ()) -> IO ByteString
BI.create Int
len ((Ptr Word8 -> IO ()) -> IO ByteString)
-> (Ptr Word8 -> IO ()) -> IO ByteString
forall a b. (a -> b) -> a -> b
$ \(Ptr Addr#
addr) -> OneShot -> (MutableByteArray# RealWorld -> IO ()) -> IO ()
forall a. OneShot -> (MutableByteArray# RealWorld -> IO a) -> IO a
withBuffer OneShot
os ((MutableByteArray# RealWorld -> IO ()) -> IO ())
-> (MutableByteArray# RealWorld -> IO ()) -> IO ()
forall a b. (a -> b) -> a -> b
$ \MutableByteArray# RealWorld
mba ->
    (State# RealWorld -> (# State# RealWorld, () #)) -> IO ()
forall a. (State# RealWorld -> (# State# RealWorld, a #)) -> IO a
IO ((State# RealWorld -> (# State# RealWorld, () #)) -> IO ())
-> (State# RealWorld -> (# State# RealWorld, () #)) -> IO ()
forall a b. (a -> b) -> a -> b
$ \State# RealWorld
s -> (# MutableByteArray# RealWorld
-> Int# -> Addr# -> Int# -> State# RealWorld -> State# RealWorld
forall d.
MutableByteArray# d
-> Int# -> Addr# -> Int# -> State# d -> State# d
copyMutableByteArrayToAddr# MutableByteArray# RealWorld
mba Int#
off Addr#
addr Int#
n State# RealWorld
s, () #)
 where
  !(I# Int#
n) = Int
len
  !(I# Int#
off) = Int
secretOffset

-- | Runs an action on the buffer, keeping it alive until the action ends.
withBuffer :: OneShot -> (MutableByteArray# RealWorld -> IO a) -> IO a
withBuffer :: forall a. OneShot -> (MutableByteArray# RealWorld -> IO a) -> IO a
withBuffer (OneShot Int
_ MutableByteArray# RealWorld
mba) MutableByteArray# RealWorld -> IO a
k = do
  r <- MutableByteArray# RealWorld -> IO a
k MutableByteArray# RealWorld
mba
  IO $ \State# RealWorld
s -> (# MutableByteArray# RealWorld -> State# RealWorld -> State# RealWorld
forall a d. a -> State# d -> State# d
touch# MutableByteArray# RealWorld
mba State# RealWorld
s, () #)
  pure r