|
| 1 | +import Foundation |
| 2 | +import CryptoKit |
| 3 | + |
| 4 | +// MARK: - Supporting Models |
| 5 | + |
| 6 | +struct StellarSignXDRResult: Codable { |
| 7 | + let signedXDR: String |
| 8 | + let signerAddress: String? |
| 9 | +} |
| 10 | + |
| 11 | +struct StellarSignAndSubmitXDRResult: Codable { |
| 12 | + let tx_hash: String? |
| 13 | + let signedXDR: String? |
| 14 | +} |
| 15 | + |
| 16 | +// MARK: - StellarTVFCollector |
| 17 | + |
| 18 | +class StellarTVFCollector: ChainTVFCollector { |
| 19 | + // MARK: - Constants |
| 20 | + |
| 21 | + static let STELLAR_SIGN_XDR = "stellar_signXDR" |
| 22 | + static let STELLAR_SIGN_AND_SUBMIT_XDR = "stellar_signAndSubmitXDR" |
| 23 | + |
| 24 | + private static let pubnetPassphrase = "Public Global Stellar Network ; September 2015" |
| 25 | + private static let testnetPassphrase = "Test SDF Network ; September 2015" |
| 26 | + |
| 27 | + // XDR EnvelopeType discriminants |
| 28 | + private static let envelopeTypeTxV0: UInt32 = 0 |
| 29 | + private static let envelopeTypeTx: UInt32 = 2 |
| 30 | + private static let envelopeTypeTxFeeBump: UInt32 = 5 |
| 31 | + |
| 32 | + // DecoratedSignature with an ed25519 signature: hint (4) + length (4, =64) + signature (64) |
| 33 | + private static let decoratedSignatureLength = 72 |
| 34 | + private static let ed25519SignatureLength: UInt32 = 64 |
| 35 | + private static let maxEnvelopeSignatures = 20 |
| 36 | + |
| 37 | + // MARK: - Supported Methods |
| 38 | + |
| 39 | + private var supportedMethods: [String] { |
| 40 | + [Self.STELLAR_SIGN_XDR, Self.STELLAR_SIGN_AND_SUBMIT_XDR] |
| 41 | + } |
| 42 | + |
| 43 | + func supportsMethod(_ method: String) -> Bool { |
| 44 | + return supportedMethods.contains(method) |
| 45 | + } |
| 46 | + |
| 47 | + // MARK: - Implementation |
| 48 | + |
| 49 | + func extractContractAddresses(rpcMethod: String, rpcParams: AnyCodable) -> [String]? { |
| 50 | + // Stellar doesn't extract contract addresses for TVF in this implementation |
| 51 | + return nil |
| 52 | + } |
| 53 | + |
| 54 | + func parseTxHashes(rpcMethod: String, rpcResult: RPCResult?, rpcParams: AnyCodable?) -> [String]? { |
| 55 | + // If rpcResult is nil or is an error, we can't parse anything |
| 56 | + guard let rpcResult = rpcResult, case .response(let anycodable) = rpcResult else { |
| 57 | + return nil |
| 58 | + } |
| 59 | + |
| 60 | + // Only process Stellar transaction methods |
| 61 | + guard supportedMethods.contains(rpcMethod) else { |
| 62 | + return nil |
| 63 | + } |
| 64 | + |
| 65 | + // `rpcResult` already holds the unwrapped JSON-RPC `result` value — the `result` |
| 66 | + // key is stripped during RPCResponse decoding — so decode directly off `anycodable`, |
| 67 | + // matching the Solana/EVM collectors and the JS reference implementation. |
| 68 | + switch rpcMethod { |
| 69 | + case Self.STELLAR_SIGN_AND_SUBMIT_XDR: |
| 70 | + if let result = try? anycodable.get(StellarSignAndSubmitXDRResult.self), |
| 71 | + let txHash = result.tx_hash { |
| 72 | + return [txHash] |
| 73 | + } |
| 74 | + return nil |
| 75 | + |
| 76 | + case Self.STELLAR_SIGN_XDR: |
| 77 | + guard let result = try? anycodable.get(StellarSignXDRResult.self) else { |
| 78 | + return nil |
| 79 | + } |
| 80 | + let chain = extractChain(from: rpcParams) |
| 81 | + return Self.computeTransactionHash(signedXDR: result.signedXDR, chain: chain).map { [$0] } |
| 82 | + |
| 83 | + default: |
| 84 | + return nil |
| 85 | + } |
| 86 | + } |
| 87 | + |
| 88 | + private func extractChain(from rpcParams: AnyCodable?) -> String? { |
| 89 | + guard let rpcParams = rpcParams, |
| 90 | + let params = try? rpcParams.get([String: AnyCodable].self), |
| 91 | + let chainAny = params["chain"], |
| 92 | + let chain = try? chainAny.get(String.self) else { |
| 93 | + return nil |
| 94 | + } |
| 95 | + return chain |
| 96 | + } |
| 97 | + |
| 98 | + // MARK: - Hash Computation |
| 99 | + |
| 100 | + /// Computes the Stellar transaction hash from a base64-encoded, signed TransactionEnvelope XDR |
| 101 | + /// as `sha256(network_id || envelope_type || transaction_body)`. Signatures are computed over |
| 102 | + /// the hash, so the trailing signature array is stripped rather than hashed. For fee-bump |
| 103 | + /// envelopes this yields the canonical fee-bump hash. |
| 104 | + /// |
| 105 | + /// - Parameters: |
| 106 | + /// - signedXDR: base64-encoded TransactionEnvelope XDR (V0, V1 or fee-bump) |
| 107 | + /// - chain: CAIP-2 chain id (`stellar:pubnet` / `stellar:testnet`), defaults to pubnet |
| 108 | + /// - Returns: lowercase hex transaction hash (64 chars), or nil for malformed envelopes |
| 109 | + static func computeTransactionHash(signedXDR: String, chain: String?) -> String? { |
| 110 | + guard let bytes = Data(base64Encoded: signedXDR), bytes.count >= 8 else { |
| 111 | + return nil |
| 112 | + } |
| 113 | + |
| 114 | + let discriminant = readUInt32BE(bytes, 0) |
| 115 | + let envelopeType: UInt32 |
| 116 | + let bodyStart: Int |
| 117 | + switch discriminant { |
| 118 | + case envelopeTypeTxV0: |
| 119 | + // V0 transactions are hashed as ENVELOPE_TYPE_TX over the envelope bytes INCLUDING |
| 120 | + // the leading 4 zero bytes - they double as the legacy AccountID key-type tag |
| 121 | + envelopeType = envelopeTypeTx |
| 122 | + bodyStart = 0 |
| 123 | + case envelopeTypeTx: |
| 124 | + envelopeType = envelopeTypeTx |
| 125 | + bodyStart = 4 |
| 126 | + case envelopeTypeTxFeeBump: |
| 127 | + envelopeType = envelopeTypeTxFeeBump |
| 128 | + bodyStart = 4 |
| 129 | + default: |
| 130 | + return nil |
| 131 | + } |
| 132 | + |
| 133 | + guard let signatureArrayOffset = findSignatureArrayOffset(bytes) else { |
| 134 | + return nil |
| 135 | + } |
| 136 | + |
| 137 | + let reference = chain?.components(separatedBy: ":").last ?? "pubnet" |
| 138 | + let passphrase: String |
| 139 | + switch reference { |
| 140 | + case "pubnet": passphrase = pubnetPassphrase |
| 141 | + case "testnet": passphrase = testnetPassphrase |
| 142 | + default: return nil |
| 143 | + } |
| 144 | + |
| 145 | + let networkId = Data(SHA256.hash(data: Data(passphrase.utf8))) |
| 146 | + var payload = networkId |
| 147 | + payload.append(contentsOf: [0, 0, 0, UInt8(envelopeType)]) |
| 148 | + payload.append(bytes.subdata(in: bodyStart..<signatureArrayOffset)) |
| 149 | + |
| 150 | + return SHA256.hash(data: payload).map { String(format: "%02x", $0) }.joined() |
| 151 | + } |
| 152 | + |
| 153 | + /// Locates the start of the trailing `DecoratedSignature signatures<20>` XDR array without |
| 154 | + /// parsing the transaction body. Assumes ed25519 signatures (fixed 72-byte entries), which is |
| 155 | + /// what the WalletConnect Stellar RPC spec mandates wallets emit. |
| 156 | + private static func findSignatureArrayOffset(_ bytes: Data) -> Int? { |
| 157 | + // Scan from the maximum count downward: a real multi-signature array must be found |
| 158 | + // before the vacuously-matching zero count, which would otherwise win whenever a |
| 159 | + // signature happens to end in four zero bytes. |
| 160 | + for signatureCount in stride(from: maxEnvelopeSignatures, through: 0, by: -1) { |
| 161 | + let offset = bytes.count - 4 - decoratedSignatureLength * signatureCount |
| 162 | + if offset < 4 { continue } |
| 163 | + if readUInt32BE(bytes, offset) != UInt32(signatureCount) { continue } |
| 164 | + |
| 165 | + var isValid = true |
| 166 | + for i in 0..<signatureCount { |
| 167 | + let entryOffset = offset + 4 + decoratedSignatureLength * i |
| 168 | + // each entry's signature length field must be exactly 64 (ed25519) |
| 169 | + if readUInt32BE(bytes, entryOffset + 4) != ed25519SignatureLength { |
| 170 | + isValid = false |
| 171 | + break |
| 172 | + } |
| 173 | + } |
| 174 | + if isValid { return offset } |
| 175 | + } |
| 176 | + return nil |
| 177 | + } |
| 178 | + |
| 179 | + private static func readUInt32BE(_ bytes: Data, _ offset: Int) -> UInt32 { |
| 180 | + let index = bytes.startIndex + offset |
| 181 | + return (UInt32(bytes[index]) << 24) |
| 182 | + | (UInt32(bytes[index + 1]) << 16) |
| 183 | + | (UInt32(bytes[index + 2]) << 8) |
| 184 | + | UInt32(bytes[index + 3]) |
| 185 | + } |
| 186 | +} |
0 commit comments