SPB Git

Repository Public

Address.swift 4.1 KB 105 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraEthereum/Address.swift8// Module           : Qyvora Ethereum9// Repository       : https://git.spboucher.ai/qyvora10// Project Website  : Not specified11// Created          : 2026-12-0412// Last Modified    : 2026-12-0413//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import QyvoraMath42import QyvoraKeccak43import QyvoraSecp256k14445/// 20-byte Ethereum account address with EIP-55 mixed-case checksum.46public struct EthereumAddress: Equatable, Hashable, Sendable, CustomStringConvertible, Codable {47    public let bytes: Bytes4849    public static let zero = EthereumAddress(unchecked: Bytes(repeating: 0, count: 20))5051    init(unchecked: Bytes) { bytes = unchecked }5253    public init?(bytes: Bytes) {54        guard bytes.count == 20 else { return nil }55        self.bytes = bytes56    }5758    /// Parses "0x" + 40 hexadecimal digits. Mixed case must carry a valid EIP-55 checksum;59    /// all-lower-case and all-upper-case input is accepted (no checksum information).60    public init?(_ text: String) {61        guard text.hasPrefix("0x") || text.hasPrefix("0X") else { return nil }62        let h = String(text.dropFirst(2))63        guard h.utf8.count == 40, let b = Hex.decode(h) else { return nil }64        let candidate = EthereumAddress(unchecked: b)65        let hasLower = h.utf8.contains { $0 >= 0x61 && $0 <= 0x66 }66        let hasUpper = h.utf8.contains { $0 >= 0x41 && $0 <= 0x46 }67        if hasLower && hasUpper && candidate.checksummed.dropFirst(2) != h { return nil }68        self = candidate69    }7071    /// Address of an uncompressed or compressed secp256k1 public key: last 20 bytes of Keccak-256(X ‖ Y).72    public init(publicKey: Bytes) throws {73        let u = try Secp256k1.convert(publicKey: publicKey, compressed: false)74        bytes = Bytes(SHA3.keccak256(Bytes(u[1...])).suffix(20))75    }7677    /// EIP-55 form.78    public var checksummed: String {79        let lower = Array(Hex.encode(bytes).utf8)80        let hash = SHA3.keccak256(lower)81        var out = Bytes("0x".utf8)82        for (i, c) in lower.enumerated() {83            let nibble = (hash[i / 2] >> (i % 2 == 0 ? 4 : 0)) & 0x0f84            out.append(c >= 0x61 && nibble >= 8 ? c - 32 : c)85        }86        return String(decoding: out, as: UTF8.self)87    }8889    public var description: String { checksummed }90    public var isZero: Bool { bytes.allSatisfy { $0 == 0 } }9192    public init(from decoder: Decoder) throws {93        let s = try decoder.singleValueContainer().decode(String.self)94        guard let a = EthereumAddress(s) else {95            throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "invalid address"))96        }97        self = a98    }99100    public func encode(to encoder: Encoder) throws {101        var c = encoder.singleValueContainer()102        try c.encode(checksummed)103    }104}105
Files main
Menu

Theme