Skip to content
This repository has been archived by the owner on May 28, 2019. It is now read-only.

Validate lower and upper case eth address #51

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
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
33 changes: 32 additions & 1 deletion Sources/Ethereum/EthereumAddress.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,15 @@ public struct EthereumAddress: Address, Hashable {

/// Validates that the string is a valid address.
static public func isValid(string: String) -> Bool {

guard !isAdressWithoutChecksum(string: string) else {
return true
}

guard let data = Data(hexString: string) else {
return false
}

let eip55String = EthereumAddress.computeEIP55String(for: data)
return string == eip55String
}
Expand All @@ -44,7 +50,7 @@ public struct EthereumAddress: Address, Hashable {

/// Creates an address with an hexadecimal string representation.
public init?(string: String) {
guard let data = Data(hexString: string), data.count == EthereumAddress.size else {
guard let data = Data(hexString: string), EthereumAddress.isValid(data: data) else {
return nil
}
self.data = data
Expand Down Expand Up @@ -85,4 +91,29 @@ extension EthereumAddress {

return string
}

fileprivate static func isAdressWithoutChecksum(string: String) -> Bool {
guard string.hasPrefix("0x"), let data = Data(hexString: string), isValid(data: data) else {
return false
}

var hasUppers: Bool = false
var hasLowers: Bool = false

for character in string {
switch character {
case "A", "B", "C", "D", "E", "F": hasUppers = true
case "a", "b", "c", "d", "e", "f": hasLowers = true
default: break
}
}

// If all characters are uppercase or lowercase, return true
if (hasUppers && !hasLowers) || (!hasUppers && hasLowers) {
return true
}

return false
}

}
9 changes: 9 additions & 0 deletions Tests/Ethereum/EthereumAddressTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,15 @@ import TrustCore
import XCTest

class EthereumAddressTests: XCTestCase {

func testValidUpperCaseEthAddress() {
XCTAssertTrue(EthereumAddress.isValid(string: "0xFA52274DD61E1643D2205169732F29114BC240B3"))
}

func testValidLoverCaseEthAddress() {
XCTAssertTrue(EthereumAddress.isValid(string: "0xfa52274dd61e1643d2205169732f29114bc240b3"))
}

func testInvalid() {
XCTAssertNil(EthereumAddress(string: "abc"))
XCTAssertNil(EthereumAddress(string: "aaeb60f3e94c9b9a09f33669435e7ef1beaed"))
Expand Down