Skip to content

Update KeyUtil.swift #299

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

Merged
merged 3 commits into from
Jan 2, 2023
Merged
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
14 changes: 7 additions & 7 deletions web3swift/src/Utils/KeyUtil.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import Logging
import secp256k1
import Foundation

enum KeyUtilError: Error {
public enum KeyUtilError: Error {
case invalidContext
case privateKeyInvalid
case unknownError
Expand All @@ -16,16 +16,16 @@ enum KeyUtilError: Error {
case badArguments
}

class KeyUtil {
public class KeyUtil {
private static var logger: Logger {
Logger(label: "web3.swift.key-util")
}

static func generatePrivateKeyData() -> Data? {
public static func generatePrivateKeyData() -> Data? {
Data.randomOfLength(32)
}

static func generatePublicKey(from privateKey: Data) throws -> Data {
public static func generatePublicKey(from privateKey: Data) throws -> Data {
guard let ctx = secp256k1_context_create(UInt32(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY)) else {
logger.warning("Failed to generate a public key: invalid context.")
throw KeyUtilError.invalidContext
Expand Down Expand Up @@ -62,13 +62,13 @@ class KeyUtil {
return publicKey
}

static func generateAddress(from publicKey: Data) -> EthereumAddress {
public static func generateAddress(from publicKey: Data) -> EthereumAddress {
let hash = publicKey.web3.keccak256
let address = hash.subdata(in: 12 ..< hash.count)
return EthereumAddress(address.web3.hexString)
}

static func sign(message: Data, with privateKey: Data, hashing: Bool) throws -> Data {
public static func sign(message: Data, with privateKey: Data, hashing: Bool) throws -> Data {
guard let ctx = secp256k1_context_create(UInt32(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY)) else {
logger.warning("Failed to sign message: invalid context.")
throw KeyUtilError.invalidContext
Expand Down Expand Up @@ -109,7 +109,7 @@ class KeyUtil {
return signature
}

static func recoverPublicKey(message: Data, signature: Data) throws -> String {
public static func recoverPublicKey(message: Data, signature: Data) throws -> String {
if signature.count != 65 || message.count != 32 {
throw KeyUtilError.badArguments
}
Expand Down