From: Ramakrishnan Muthukrishnan Date: Thu, 17 Sep 2015 22:10:10 +0000 (+0530) Subject: refactoring: move verifyHash to Utils module X-Git-Url: https://git.rkrishnan.org/simplejson/index.php?a=commitdiff_plain;h=225d009c7375cf080ff1f6b49faccb71f6863e07;p=functorrent.git refactoring: move verifyHash to Utils module --- diff --git a/src/FuncTorrent/Peer.hs b/src/FuncTorrent/Peer.hs index 157dab0..e4d7a72 100644 --- a/src/FuncTorrent/Peer.hs +++ b/src/FuncTorrent/Peer.hs @@ -18,11 +18,10 @@ import Control.Monad.State import Data.Bits import Data.Word (Word8) import Data.Map (Map, fromList, toList, (!), mapWithKey, traverseWithKey, adjust, filter) -import qualified Crypto.Hash.SHA1 as SHA1 (hash) import Safe (headMay) import FuncTorrent.Metainfo (Info(..), Metainfo(..)) -import FuncTorrent.Utils (splitN, splitNum, writeFileAtOffset, readFileAtOffset) +import FuncTorrent.Utils (splitN, splitNum, writeFileAtOffset, readFileAtOffset, verifyHash) import FuncTorrent.PeerMsgs (Peer(..), PeerMsg(..), sendMsg, getMsg, genHandshakeMsg) data PState = PState { handle :: Handle @@ -161,7 +160,7 @@ msgLoop pieceStatus file = do pBS <- liftIO $ downloadPiece h workPiece pLen if not $ verifyHash pBS (hash (pieceStatus ! workPiece)) then - liftIO $ putStrLn $ "Hash mismatch: " ++ show (hash (pieceStatus ! workPiece)) ++ " vs " ++ show (take 20 (SHA1.hash pBS)) + liftIO $ putStrLn $ "Hash mismatch" else do let fileOffset = if workPiece == 0 then 0 else workPiece * len (pieceStatus ! (workPiece - 1)) liftIO $ putStrLn $ "Write into file at offset: " ++ show fileOffset @@ -209,6 +208,3 @@ downloadPiece h index pieceLength = do putStrLn "ignoring irrelevant msg" return empty) -verifyHash :: ByteString -> ByteString -> Bool -verifyHash bs pieceHash = - take 20 (SHA1.hash bs) == pieceHash diff --git a/src/FuncTorrent/Utils.hs b/src/FuncTorrent/Utils.hs index ac08927..48ebe67 100644 --- a/src/FuncTorrent/Utils.hs +++ b/src/FuncTorrent/Utils.hs @@ -3,16 +3,18 @@ module FuncTorrent.Utils writeFileAtOffset, readFileAtOffset, splitNum, - splitN + splitN, + verifyHash ) where -import Prelude hiding (writeFile) +import Prelude hiding (writeFile, take) +import qualified Crypto.Hash.SHA1 as SHA1 (hash) +import Data.ByteString (ByteString, writeFile, hPut, hGet, take) +import qualified Data.ByteString.Char8 as BC import System.IO (withFile, hSeek, IOMode(..), SeekMode(..)) import System.Directory (doesFileExist) -import Data.ByteString (ByteString, writeFile, hPut, hGet) -import qualified Data.ByteString.Char8 as BC splitN :: Int -> BC.ByteString -> [BC.ByteString] splitN n bs | BC.null bs = [] @@ -42,3 +44,7 @@ readFileAtOffset path offset len = withFile path ReadWriteMode (\h -> do hSeek h AbsoluteSeek offset hGet h (fromInteger len)) + +verifyHash :: ByteString -> ByteString -> Bool +verifyHash bs pieceHash = + take 20 (SHA1.hash bs) == pieceHash