packages feed

haskoin-core 1.6.2 → 1.6.3

raw patch · 9 files changed

+187/−59 lines, 9 filesPVP ok

version bump matches the API change (PVP)

API changes (from Hackage documentation)

Files

CHANGELOG.md view
@@ -5,7 +5,20 @@ 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). -## [Unreleased]+## [1.6.3] - 2026-11-14++### Changed++- **Writing and reading addresses is faster**, for servers that show an+  address for every input and output. Measured on 20,000 addresses:+  - `scriptToAddressBS` tells the four standard kinds of output by their+    bytes, without parsing the script: 3 ms where it took 33, and the+    same answers as the parser for any script, which the tests check.+  - `encodeBase58` divides by 58^5 in machine words instead of building an+    `Integer`, and `checkSum32` reads its four bytes directly: Base58Check+    addresses take 60 ms where they took 81.+  - `toBase32` reads five bits at a time from the bytes, and the Bech32+    checksum has no lists: SegWit addresses take 50 ms where they took 81.  ## [1.6.2] - 2026-11-12 
README.md view
@@ -115,7 +115,7 @@ ```yaml resolver: nightly-2026-10-28 extra-deps:-  - haskoin-core-1.6.2+  - haskoin-core-1.6.3   - base16-2.0   - secp256k1-haskell-2.0.1 ```
haskoin-core.cabal view
@@ -5,7 +5,7 @@ -- see: https://github.com/sol/hpack  name:           haskoin-core-version:        1.6.2+version:        1.6.3 synopsis:       Bitcoin & Bitcoin Cash library for Haskell description:    Please see the README on GitHub at <https://github.com/jprupp/haskoin-core#readme> category:       Bitcoin, Finance, Network
src/Haskoin/Address.hs view
@@ -90,6 +90,7 @@ import Data.Binary (Binary (..)) import Data.ByteString (ByteString) import Data.ByteString qualified as B+import Data.ByteString.Unsafe qualified as BU import Data.Bytes.Get (MonadGet (getByteString, getWord64be, getWord8), isEmpty, runGetS) import Data.Bytes.Put (MonadPut (putByteString, putWord64be, putWord8), runPutS) import Data.Bytes.Serial (Serial (..))@@ -724,11 +725,39 @@  -- | Decode a serialized script into the 'Address' it has on a network, if it -- has one there. See 'outputAddress'.+--+-- The four kinds of output that nearly every transaction pays to are told+-- by their bytes, without parsing the script: a key hash, a script hash,+-- and on a network with SegWit a witness key hash and a witness script+-- hash. A server reads the address of every input and output that it shows,+-- and parsing took most of that time. Any other script is parsed, and gives+-- what it gave before; the tests hold both ways to the same answers. scriptToAddressBS :: Network -> Ctx -> ByteString -> Either String Address-scriptToAddressBS net ctx =-  maybeToEither e . outputAddress net ctx <=< unmarshal ctx+scriptToAddressBS net ctx bytes+  | Just a <- standard = Right a+  | otherwise = maybeToEither e . outputAddress net ctx =<< unmarshal ctx bytes   where     e = "Could not decode address"+    n = B.length bytes+    at = BU.unsafeIndex bytes+    segwit = isJust net.bech32Prefix+    hash :: (Serial h) => Int -> Int -> Maybe h+    hash from size = eitherToMaybe (runGetS deserialize (B.take size (B.drop from bytes)))+    standard+      -- OP_DUP OP_HASH160, a push of 20 bytes, OP_EQUALVERIFY OP_CHECKSIG+      | n == 25,+        at 0 == 0x76,+        at 1 == 0xa9,+        at 2 == 0x14,+        at 23 == 0x88,+        at 24 == 0xac =+          PubKeyAddress <$> hash 3 20+      -- OP_HASH160, a push of 20 bytes, OP_EQUAL+      | n == 23, at 0 == 0xa9, at 1 == 0x14, at 22 == 0x87 = ScriptAddress <$> hash 2 20+      -- OP_0 and a push of 20 bytes, or of 32+      | segwit, n == 22, at 0 == 0x00, at 1 == 0x14 = WitnessPubKeyAddress <$> hash 2 20+      | segwit, n == 34, at 0 == 0x00, at 1 == 0x20 = WitnessScriptAddress <$> hash 2 32+      | otherwise = Nothing  -- | Get the 'Address' that a 'ScriptOutput' has on a network. --
src/Haskoin/Address/Base58.hs view
@@ -1,3 +1,4 @@+{-# LANGUAGE BangPatterns #-} {-# LANGUAGE ImportQualifiedPost #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE NoFieldSelectors #-}@@ -24,20 +25,17 @@  import Control.Monad (guard) import Data.Array (Array, assocs, listArray, (!), (//))+import Data.Bits (shiftL, (.|.)) import Data.ByteString (ByteString) import Data.ByteString qualified as B+import Data.ByteString.Unsafe qualified as BU import Data.Bytes.Put (runPutS) import Data.Bytes.Serial (Serial (serialize))-import Data.Char (chr)-import Data.String.Conversions (cs) import Data.Text (Text)-import Data.Text qualified as T import Data.Text.Encoding qualified as E-import Data.Bits (shiftL, (.|.)) import Data.Word (Word64, Word8) import Haskoin.Crypto.Hash (checkSum32) import Haskoin.Util.Helpers (integerToBS)-import Numeric (showIntAtBase)  -- | 'Base58' classic Bitcoin address format. type Base58 = Text@@ -63,39 +61,12 @@  -- | Convert a number less than 58 into a 'Base58' character. b58 :: Int -> Word8-b58 = (b58Array !)+b58 = BU.unsafeIndex b58Data  -- | Convert a 'Base58' character into the number it represents. b58' :: Word8 -> Maybe Int b58' = (b58InvArray !) --- | Encode an arbitrary-length 'Integer' into a 'Base58' string. Leading zeroes--- will not be part of the resulting string.-encodeBase58I :: Integer -> Base58-encodeBase58I i-  | i < 0 = cs $ showIntAtBase 58 (chr . fromIntegral . b58) i ""-  | otherwise = E.decodeLatin1 . B.pack . map b58 $ chunks i []-  where-    -- Divide by 58^10 rather than by 58, so that a number of n digits takes-    -- n/10 divisions of a big number and the rest is machine arithmetic.-    chunk = 58 ^ (10 :: Int) :: Integer-    chunks n acc-      | n < chunk = top (fromInteger n) acc-      | otherwise =-          let (q, r) = n `quotRem` chunk-           in chunks q (digits (10 :: Int) (fromInteger r) acc)-    -- the digits of a chunk, ten of them with leading zeros-    digits 0 _ acc = acc-    digits k w acc =-      let (q, r) = w `quotRem` (58 :: Word64)-       in digits (k - 1) q (fromIntegral r : acc)-    -- the digits of the leading chunk, without leading zeros-    top w acc-      | w < 58 = fromIntegral w : acc-      | otherwise =-          let (q, r) = w `quotRem` (58 :: Word64)-           in top q (fromIntegral r : acc)- -- | Decode the UTF-8 bytes of a 'Base58' string into an 'Integer'. Fails on -- the first byte that is not a 'Base58' digit. decodeBase58I :: ByteString -> Maybe Integer@@ -106,17 +77,42 @@       d <- b58' w       return (n * 58 + toInteger d) --- | Encode an arbitrary 'ByteString' into a its 'Base58' representation,+-- | Encode an arbitrary 'ByteString' into its 'Base58' representation, -- preserving leading zeroes.+--+-- The bytes are read as one number in limbs of 32 bits, and divided by 58^5+-- (656,356,768) in machine words: each pass over the limbs gives five digits. An address+-- of 25 bytes takes seven passes over seven limbs. Building an 'Integer'+-- and dividing that, as this did until 1.6.2, took about five times as long,+-- and a server writes an address for every input and output it shows. encodeBase58 :: ByteString -> Base58 encodeBase58 bs =-  l <> r+  E.decodeLatin1 (B.replicate (B.length z) (b58 0) <> B.pack (map b58 (dropWhile (== 0) (groups (limbs b) []))))   where     (z, b) = B.span (== 0) bs-    l = T.replicate (B.length z) "1" -- preserve leading 0's-    r-      | B.null b = T.empty-      | otherwise = encodeBase58I $ B.foldl' (\n w -> n `shiftL` 8 .|. toInteger w) 0 b+    -- the number, most significant limb first, each limb under 2^32+    limbs bytes =+      let padded = B.replicate ((4 - B.length bytes `mod` 4) `mod` 4) 0 <> bytes+       in [ B.foldl' (\acc w -> acc `shiftL` 8 .|. fromIntegral w) 0 (BU.unsafeTake 4 (BU.unsafeDrop k padded))+          | k <- [0, 4 .. B.length padded - 4]+          ]+    -- the digits, most significant first, five for each division+    groups ls !acc = case dropWhile (== 0) ls of+      [] -> acc+      live -> let (q, r) = divide live in groups q (five (5 :: Int) r acc)+    -- the number divided by 58^5, with the remainder; a remainder is under+    -- 2^30, so with a limb after it it fits in 64 bits+    divide = go 0 []+      where+        go !r qs [] = (reverse qs, r)+        go !r qs (x : xs) =+          let !cur = r `shiftL` 32 .|. x+              !q = cur `quot` chunk+           in go (cur `rem` chunk) (q : qs) xs+    chunk = 656356768 :: Word64+    five :: Int -> Word64 -> [Int] -> [Int]+    five 0 _ acc = acc+    five k !w acc = let !d = fromIntegral (w `rem` 58) in five (k - 1) (w `quot` 58) (d : acc)  -- | Decode a 'Base58'-encoded 'Text' to a 'ByteString'. Returns 'Nothing' if -- the input contains any character outside the 'Base58' alphabet.@@ -140,8 +136,7 @@ -- | Computes a checksum for the input 'ByteString' and encodes the input and -- the checksum as 'Base58'. encodeBase58Check :: ByteString -> Base58-encodeBase58Check bs =-  (encodeBase58 . B.append bs . runPutS . serialize . checkSum32) bs+encodeBase58Check bs = encodeBase58 (bs <> runPutS (serialize (checkSum32 bs)))  -- | Decode a 'Base58'-encoded string that contains a checksum. This function -- returns 'Nothing' if the input string contains invalid 'Base58' characters,
src/Haskoin/Address/Bech32.hs view
@@ -1,3 +1,4 @@+{-# LANGUAGE BangPatterns #-} {-# LANGUAGE ImportQualifiedPost #-} {-# LANGUAGE MultiWayIf #-} {-# LANGUAGE OverloadedStrings #-}@@ -43,6 +44,8 @@   ) import Data.Bits   ( Bits,+    shiftL,+    shiftR,     testBit,     unsafeShiftL,     unsafeShiftR,@@ -51,6 +54,7 @@     (.|.),   ) import Data.ByteString qualified as B+import Data.ByteString.Unsafe qualified as BU import Data.Foldable (foldl') import Data.Functor.Identity (Identity, runIdentity) import Data.Ix (Ix (..))@@ -102,6 +106,10 @@ charset =   listArray (UnsafeWord5 0, UnsafeWord5 31) "qpzry9x8gf2tvdw0s3jn54khce6mua7l" +-- | 'charset' as bytes, for writing: looked up without bounds or boxes.+charsetBytes :: B.ByteString+charsetBytes = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"+ -- | Inverse of 'charset'. Only the lowercase characters are present. The -- decoder checks that the string is ASCII and not mixed case, then lowercases -- it, before looking characters up here. No character from another alphabet@@ -122,13 +130,19 @@ bech32Polymod :: [Word5] -> Word bech32Polymod values = foldl' go 1 values .&. 0x3fffffff   where-    go chk value =-      foldl' xor chk' [g | (g, i) <- zip generator [25 ..], testBit chk i]+    -- the five generators, each where its bit of the top of the accumulator+    -- is set, written out: a list of them for each character made the+    -- checksum the most of the cost of an address+    go !chk value =+      g 29 0x2a1462b3 . g 28 0x3d4233dd . g 27 0x1ea119fa . g 26 0x26508e6d $ g 25 0x3b6a57b2 chk'       where-        generator = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3]         -- Keep only the low 25 bits before shifting, as the reference         -- implementation does, so the accumulator never grows past 30 bits.         chk' = ((chk .&. 0x1ffffff) .<<. 5) `xor` fromWord5 value+        g :: Int -> Word -> Word -> Word+        g i gen c+          | testBit chk i = c `xor` gen+          | otherwise = c  -- | Convert human-readable part of 'Bech32' string into a list of five-bit -- words.@@ -179,8 +193,8 @@   -- character.   guard $ all (\(UnsafeWord5 w) -> w <= 31) dat   let dat' = dat ++ bech32CreateChecksum enc (T.toLower hrp) dat-      rest = map (charset !) dat'-      result = T.concat [T.toLower hrp, T.pack "1", T.pack rest]+      rest = map (\(UnsafeWord5 w) -> BU.unsafeIndex charsetBytes (fromIntegral w)) dat'+      result = T.concat [T.toLower hrp, T.pack "1", E.decodeLatin1 (B.pack rest)]   guard $ T.length result <= maxBech32Length   return result @@ -251,9 +265,26 @@ {-# INLINE convertBits #-}  -- | Convert from eight-bit to five-bit word string, adding padding as required.+--+-- Each five bits are read from the two bytes that hold them, as+-- "Haskoin.Address.CashAddr" does, rather than through 'convertBits', whose+-- lists made this most of the cost of writing a SegWit address. The tests+-- hold it to 'convertBits'. toBase32 :: [Word8] -> [Word5]-toBase32 dat =-  map word5 $ runIdentity $ convertBits (map fromIntegral dat) 8 5 yesPadding+toBase32 dat = map UnsafeWord5 (B.unpack (fst (B.unfoldrN groups group 0)))+  where+    bs = B.pack dat+    groups = (B.length bs * 8 + 4) `div` 5+    byte :: Int -> Word+    byte i+      | i < B.length bs = fromIntegral (BU.unsafeIndex bs i)+      | otherwise = 0+    -- the five bits that start this many bits into the input, padded with+    -- zeros after its end+    group bit =+      let i = bit `shiftR` 3+          two = byte i `shiftL` 8 .|. byte (i + 1)+       in Just (fromIntegral ((two `shiftR` (11 - (bit .&. 7))) .&. 0x1f), bit + 5)  -- | Convert from five-bit word string to eight-bit word string. Fails if the -- padding bits are not zero, or if there are enough of them to hold a whole
src/Haskoin/Crypto/Hash.hs view
@@ -44,6 +44,7 @@ import Crypto.Hash import Crypto.MAC.HMAC (HMAC, hmac) import Data.Binary (Binary (..))+import Data.Bits (shiftL, (.|.)) import Data.ByteArray (ByteArrayAccess, convert) import Data.ByteString (ByteString) import Data.ByteString qualified as B@@ -51,7 +52,6 @@ import Data.Bytes.Get import Data.Bytes.Put import Data.Bytes.Serial (Serial (..))-import Data.Either (fromRight) import Data.Function (on) import Data.Hashable (Hashable) import Data.Serialize (Serialize (..))@@ -210,11 +210,13 @@  {- CheckSum -} --- | Computes a 32 bit checksum.+-- | Computes a 32 bit checksum: the first four bytes of two rounds of+-- SHA-256, read big-endian. It is read from the bytes directly rather than+-- parsed, as it is part of every 'Haskoin.Address.Base58.encodeBase58Check'. checkSum32 :: (ByteArrayAccess b) => b -> CheckSum32 checkSum32 =-  fromRight (error "Could not decode bytes as CheckSum32")-    . runGetS deserialize+  CheckSum32+    . B.foldl' (\acc w -> acc `shiftL` 8 .|. fromIntegral w) 0     . B.take 4     . convert     . hashWith SHA256
test/Haskoin/Address/Bech32Spec.hs view
@@ -4,7 +4,7 @@ module Haskoin.Address.Bech32Spec (spec) where  import Control.Monad-import Data.Bits (xor)+import Data.Bits (testBit, xor) import Data.ByteString (ByteString) import Data.ByteString qualified as ByteString import Data.Char (chr, ord, toLower)@@ -18,6 +18,7 @@ import Haskoin.Util import Test.HUnit import Test.Hspec+import Test.Hspec.QuickCheck (prop)  spec :: Spec spec = do@@ -108,6 +109,12 @@       map fromWord5 (toBase32 [0xff]) `shouldBe` [31, 28 :: Int]     it "toBase32 needs no padding for five bytes" $       map fromWord5 (toBase32 [1, 2, 3, 4, 5]) `shouldBe` [0, 4, 1, 0, 6, 1, 0, 5 :: Int]+    prop "toBase32 reads the bits five at a time, most significant first, padded with zeros" $ \bytes ->+      let bits = concatMap (\b -> [testBit (b :: Word8) i | i <- [7, 6 .. 0]]) bytes+          groups [] = []+          groups bs = take 5 (bs <> replicate 4 False) : groups (drop 5 bs)+          value = foldl (\acc b -> acc * 2 + if b then 1 else 0) 0+       in map fromWord5 (toBase32 bytes) `shouldBe` (map value (groups bits) :: [Int])     it "toBase256 reverses toBase32" $       toBase256 (map word5 [31, 28 :: Int]) `shouldBe` Just [0xff]     it "toBase256 rejects padding bits that are not zero" $
test/Haskoin/AddressSpec.hs view
@@ -26,11 +26,11 @@ import Haskoin.Util import Haskoin.Util.Arbitrary import System.Timeout (timeout)-import Text.Read (readMaybe) import Test.HUnit import Test.Hspec import Test.Hspec.QuickCheck import Test.QuickCheck+import Text.Read (readMaybe)  identityTests :: Network -> IdentityTests identityTests net =@@ -88,6 +88,15 @@       decodeBase58 "2\x0131" `shouldBe` Nothing     it "rejects a checked string shorter than a checksum" $       decodeBase58Check "1" `shouldBe` Nothing+    prop "writes what the plain conversion through one big number writes" $+      -- leading zero bytes, which are written as 1, and lengths of every+      -- remainder by four, for the limbs of 32 bits+      forAll ((<>) <$> (B.pack <$> listOf (pure 0)) <*> arbitraryBS) $ \bs ->+        encodeBase58 bs `shouldBe` slowBase58 bs+    it "writes the numbers around the edges of a limb and of 58^5" $+      forM_ [0, 1, 57, 58, 656356767, 656356768, 4294967295, 4294967296, 2 ^ (200 :: Int) - 1] $ \n -> do+        let bs = integerToBS n+        assertEqual (show n) (slowBase58 bs) (encodeBase58 bs)   describe "Smart constructors" $ do     it "witnessAddress builds a P2WPKH address from version 0 and 20 bytes" $       witnessAddress 0 hash20Bytes `shouldBe` Just (WitnessPubKeyAddress hash20)@@ -391,6 +400,22 @@       ((.ops) <$> addressToScript ctx p2sh)         `shouldBe` Just [OP_HASH160, OP_PUSHDATA hash20Bytes OPCODE, OP_EQUAL]   describe "outputAddress, scriptToAddress and scriptToAddressBS" $ do+    prop "reads the standard kinds by their bytes as the parser reads them" $+      -- outputs of every kind, of any network, read on any network+      forAll ((,) <$> arbitraryNetwork <*> (arbitraryNetwork >>= \other -> arbitraryScriptOutput other ctx)) $ \(net, out) ->+        let bytes = marshal ctx out+         in scriptToAddressBS net ctx bytes `shouldBe` parsed ctx net bytes+    prop "reads bytes that are nearly of a standard kind as the parser reads them" $+      -- a standard script with one byte changed, or one too many or too few+      forAll ((,,) <$> arbitraryNetwork <*> elements standardShapes <*> arbitrary) $ \(net, hex, (i, w, cut)) -> do+        let good = fromJust (decodeHex hex)+            k = i `mod` B.length good+            changed = B.take k good <> B.singleton w <> B.drop (k + 1) good+            bytes = case cut `mod` (3 :: Int) of+              0 -> changed+              1 -> changed <> "\x00"+              _ -> B.take (B.length changed - 1) changed+        scriptToAddressBS net ctx bytes `shouldBe` parsed ctx net bytes     it "recovers the address of every standard locking script on a network that has its kind" $       forM_ scriptTable $ \(net, a, hex) ->         assertEqual (T.unpack hex) (Right a) (scriptToAddressBS net ctx (fromJust (decodeHex hex)))@@ -837,4 +862,30 @@       "cNUnpYpMsJXYCERYBciJnsWBpcYEFjdcbq6dxj4SskGhs7uHuJ7Q",       "2N6PDTueBHvXzW61B4oe5SW1D3v2Z3Vpbvw"     )+  ]++-- | Base58 as it was written until haskoin-core 1.6.2: the bytes as one+-- 'Integer', divided by 58 until nothing is left, and a 1 for each leading+-- zero byte.+slowBase58 :: ByteString -> Text+slowBase58 bs = T.replicate (B.length zeros) "1" <> T.pack (map (T.index alphabet) (digits number []))+  where+    (zeros, rest) = B.span (== 0) bs+    number = B.foldl' (\n w -> n * 256 + toInteger w) 0 rest :: Integer+    digits 0 acc = acc+    digits n acc = digits (n `div` 58) (fromInteger (n `mod` 58) : acc)+    alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"++-- | The address of a script as the parser reads it, which is what+-- 'scriptToAddressBS' did for every script until haskoin-core 1.6.2.+parsed :: Ctx -> Network -> ByteString -> Either String Address+parsed ctx net bytes = maybeToEither "Could not decode address" . outputAddress net ctx =<< unmarshal ctx bytes++-- | The four kinds of script that 'scriptToAddressBS' reads by their bytes.+standardShapes :: [Text]+standardShapes =+  [ "76a91476a04053bda0a88bda5177b86a15c3b29f55987388ac",+    "a91476a04053bda0a88bda5177b86a15c3b29f55987387",+    "001476a04053bda0a88bda5177b86a15c3b29f559873",+    "00201863143c14c5166804bd19203356da136c985678cd4d27a1b8c6329604903262"   ]