SPB Git

Repository Public

Transaction.swift 9.5 KB 205 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraEthereum/Transaction.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 QyvoraSecp256k144import QyvoraCore4546/// EIP-1559 (type 2) transaction.47public struct EIP1559Transaction: Equatable, Sendable {48    public var chainID: UInt6449    public var nonce: UInt6450    public var maxPriorityFeePerGas: UInt25651    public var maxFeePerGas: UInt25652    public var gasLimit: UInt6453    /// nil for contract creation (not produced by QYVORA 1.0, accepted when decoding).54    public var to: EthereumAddress?55    public var value: UInt25656    public var data: Bytes57    public var accessList: [AccessListEntry]5859    public struct AccessListEntry: Equatable, Sendable {60        public var address: EthereumAddress61        public var storageKeys: [Bytes]62        public init(address: EthereumAddress, storageKeys: [Bytes]) {63            self.address = address64            self.storageKeys = storageKeys65        }66    }6768    public enum Error: Swift.Error, Equatable {69        case notType270        case malformed71        case invalidSignature72        case feeOrder73    }7475    public init(chainID: UInt64, nonce: UInt64, maxPriorityFeePerGas: UInt256, maxFeePerGas: UInt256, gasLimit: UInt64,76                to: EthereumAddress?, value: UInt256, data: Bytes = [], accessList: [AccessListEntry] = []) {77        self.chainID = chainID78        self.nonce = nonce79        self.maxPriorityFeePerGas = maxPriorityFeePerGas80        self.maxFeePerGas = maxFeePerGas81        self.gasLimit = gasLimit82        self.to = to83        self.value = value84        self.data = data85        self.accessList = accessList86    }8788    fileprivate var fields: [RLP] {89        [90            .uint(chainID), .uint(nonce), .uint(maxPriorityFeePerGas), .uint(maxFeePerGas), .uint(gasLimit),91            .bytes(to?.bytes ?? []), .uint(value), .bytes(data),92            .list(accessList.map { .list([.bytes($0.address.bytes), .list($0.storageKeys.map { .bytes($0) })]) }),93        ]94    }9596    /// 0x02 ‖ rlp([chainId, nonce, maxPriorityFeePerGas, maxFeePerGas, gasLimit, to, value, data, accessList])97    public var unsignedPayload: Bytes { [0x02] + RLP.list(fields).encoded }9899    /// Keccak-256 of the unsigned payload: the digest that is signed.100    public var signingHash: Bytes { SHA3.keccak256(unsignedPayload) }101102    /// The largest amount of wei the transaction can cost: gasLimit × maxFeePerGas + value. nil on overflow.103    public var maximumCost: UInt256? {104        let (fee, o1) = maxFeePerGas.multipliedReportingOverflow(by: gasLimit)105        let (total, o2) = fee.addingReportingOverflow(value)106        return o1 || o2 ? nil : total107    }108109    /// Signs with a secp256k1 private key (RFC 6979 nonce, low s as EIP-2 requires).110    public func sign(privateKey: Bytes) throws -> SignedEIP1559Transaction {111        guard maxPriorityFeePerGas <= maxFeePerGas else { throw Error.feeOrder }112        let sig = try Secp256k1.sign(digest: signingHash, privateKey: privateKey)113        guard sig.recoveryID < 2 else { throw Error.invalidSignature }114        return SignedEIP1559Transaction(transaction: self, yParity: sig.recoveryID, r: sig.r, s: sig.s)115    }116117    /// Decodes an unsigned payload (0x02 ‖ rlp of nine fields), e.g. received by QR code in cold mode.118    public static func decodeUnsigned(_ payload: Bytes) throws -> EIP1559Transaction {119        guard payload.first == 0x02 else { throw Error.notType2 }120        guard let items = try RLP.decode(Bytes(payload.dropFirst())).listValue, items.count == 9 else { throw Error.malformed }121        return try decodeFields(items)122    }123124    static func decodeFields(_ items: [RLP]) throws -> EIP1559Transaction {125        guard let chain = items[0].uintValue?.uint64, let nonce = items[1].uintValue?.uint64,126              let tip = items[2].uintValue, let maxFee = items[3].uintValue, let gas = items[4].uintValue?.uint64,127              let toBytes = items[5].bytesValue, toBytes.isEmpty || toBytes.count == 20,128              let value = items[6].uintValue, let data = items[7].bytesValue, let access = items[8].listValue129        else { throw Error.malformed }130        var list = [AccessListEntry]()131        for entry in access {132            guard let pair = entry.listValue, pair.count == 2, let a = pair[0].bytesValue, let address = EthereumAddress(bytes: a),133                  let keys = pair[1].listValue else { throw Error.malformed }134            var storage = [Bytes]()135            for k in keys {136                guard let kb = k.bytesValue, kb.count == 32 else { throw Error.malformed }137                storage.append(kb)138            }139            list.append(AccessListEntry(address: address, storageKeys: storage))140        }141        return EIP1559Transaction(chainID: chain, nonce: nonce, maxPriorityFeePerGas: tip, maxFeePerGas: maxFee, gasLimit: gas,142                                  to: toBytes.isEmpty ? nil : EthereumAddress(bytes: toBytes), value: value, data: data, accessList: list)143    }144}145146public struct SignedEIP1559Transaction: Equatable, Sendable {147    public let transaction: EIP1559Transaction148    public let yParity: UInt8149    public let r: Bytes150    public let s: Bytes151152    /// The raw transaction to broadcast (eth_sendRawTransaction).153    public var raw: Bytes {154        let strip: (Bytes) -> Bytes = { Bytes($0.drop(while: { $0 == 0 })) }155        // The nine fields that were signed, taken from the transaction itself (no decode of our own encoding, no trap).156        let items = transaction.fields + [.uint(UInt64(yParity)), .bytes(strip(r)), .bytes(strip(s))]157        return [0x02] + RLP.list(items).encoded158    }159160    /// Transaction hash: Keccak-256 of the raw bytes.161    public var hash: Bytes { SHA3.keccak256(raw) }162163    public var hashHex: String { "0x" + Hex.encode(hash) }164165    /// The sender recovered from the signature.166    public func sender() throws -> EthereumAddress {167        let pk = try Secp256k1.recoverPublicKey(compactSignature: r + s, recoveryID: yParity, digest: transaction.signingHash, compressed: false)168        return try EthereumAddress(publicKey: pk)169    }170171    /// Decodes a raw signed type-2 transaction and checks the signature shape (low s, recoverable sender).172    public static func decode(_ raw: Bytes) throws -> SignedEIP1559Transaction {173        guard raw.first == 0x02 else { throw EIP1559Transaction.Error.notType2 }174        guard let items = try RLP.decode(Bytes(raw.dropFirst())).listValue, items.count == 12,175              let parity = items[9].uintValue?.uint64, parity < 2,176              let r = items[10].uintValue, let s = items[11].uintValue, !r.isZero, !s.isZero177        else { throw EIP1559Transaction.Error.malformed }178        let tx = try EIP1559Transaction.decodeFields(Array(items[0..<9]))179        let signed = SignedEIP1559Transaction(transaction: tx, yParity: UInt8(parity), r: r.bytes32, s: s.bytes32)180        guard Secp256k1.verify(compactSignature: signed.r + signed.s, digest: tx.signingHash,181                               publicKey: try Secp256k1.recoverPublicKey(compactSignature: signed.r + signed.s, recoveryID: signed.yParity, digest: tx.signingHash))182        else { throw EIP1559Transaction.Error.invalidSignature }183        return signed184    }185}186187/// EIP-191 "personal_sign" messages.188public enum PersonalMessage {189    public static func hash(_ message: Bytes) -> Bytes {190        SHA3.keccak256(Bytes("\u{19}Ethereum Signed Message:\n\(message.count)".utf8) + message)191    }192193    /// 65-byte signature r ‖ s ‖ v with v = 27 or 28.194    public static func sign(_ message: Bytes, privateKey: Bytes) throws -> Bytes {195        let sig = try Secp256k1.sign(digest: hash(message), privateKey: privateKey)196        return sig.compact + [27 + sig.recoveryID]197    }198199    public static func recoverSigner(_ message: Bytes, signature: Bytes) throws -> EthereumAddress {200        guard signature.count == 65, signature[64] == 27 || signature[64] == 28 else { throw Secp256k1.Error.invalidSignature }201        let pk = try Secp256k1.recoverPublicKey(compactSignature: Bytes(signature[0..<64]), recoveryID: signature[64] - 27, digest: hash(message), compressed: false)202        return try EthereumAddress(publicKey: pk)203    }204}205
Files main
Menu

Theme