-
-
Notifications
You must be signed in to change notification settings - Fork 41
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
44 additions
and
0 deletions.
There are no files selected for viewing
44 changes: 44 additions & 0 deletions
44
...kchain_integration/pi_network/pi-network-layer2-scaling/contracts/libraries/CryptoLib.sol
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
// SPDX-License-Identifier: MIT | ||
pragma solidity ^0.8.0; | ||
|
||
library CryptoLib { | ||
// Hash a message using keccak256 | ||
function hashMessage(bytes memory message) internal pure returns (bytes32) { | ||
return keccak256(message); | ||
} | ||
|
||
// Verify a signature | ||
function verifySignature( | ||
bytes32 messageHash, | ||
bytes memory signature, | ||
address signer | ||
) internal pure returns (bool) { | ||
bytes32 ethSignedMessageHash = getEthSignedMessageHash(messageHash); | ||
return recoverSigner(ethSignedMessageHash, signature) == signer; | ||
} | ||
|
||
// Get the Ethereum signed message hash | ||
function getEthSignedMessageHash(bytes32 messageHash) internal pure returns (bytes32) { | ||
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", messageHash)); | ||
} | ||
|
||
// Recover the signer from a signature | ||
function recoverSigner(bytes32 ethSignedMessageHash, bytes memory signature) internal pure returns (address) { | ||
(bytes32 r, bytes32 s, uint8 v) = splitSignature(signature); | ||
return ecrecover(ethSignedMessageHash, v, r, s); | ||
} | ||
|
||
// Split the signature into r, s, and v | ||
function splitSignature(bytes memory signature) internal pure returns (bytes32 r, bytes32 s, uint8 v) { | ||
require(signature.length == 65, "CryptoLib: invalid signature length"); | ||
assembly { | ||
r := mload(add(signature, 0x20)) | ||
s := mload(add(signature, 0x40)) | ||
v := byte(0, mload(add(signature, 0x60))) | ||
} | ||
// Adjust v value | ||
if (v < 27) { | ||
v += 27; | ||
} | ||
} | ||
} |