SPB Git

Repository Public

SolanaMessage.swift 24.2 KB 489 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraSolana/SolanaMessage.swift8// Module           : Qyvora Solana9// Repository       : https://git.spboucher.ai/qyvora10// Project Website  : Not specified11// Created          : 2026-12-0512// Last Modified    : 2026-12-0513//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 QyvoraCore42import QyvoraEd2551943import QyvoraMath4445/// Solana's variable-length encoding of a 16-bit length ("compact-u16", "short vec"): 7 bits per byte, least46/// significant first, at most three bytes.47public enum SolanaCompactU16 {48    public static func encode(_ value: UInt16) -> Bytes {49        var v = value50        var out = Bytes()51        while true {52            let low = UInt8(v & 0x7f)53            v >>= 754            if v == 0 {55                out.append(low)56                return out57            }58            out.append(low | 0x80)59        }60    }6162    /// Strict decoding at `offset`: the shortest encoding only (no padding zero byte), at most three bytes, value below63    /// 2^16. Advances `offset`; nil on truncated or non-canonical input.64    public static func decode(_ bytes: Bytes, at offset: inout Int) -> UInt16? {65        var value: UInt32 = 066        for i in 0..<3 {67            guard offset < bytes.count else { return nil }68            let byte = bytes[offset]69            offset += 170            value |= UInt32(byte & 0x7f) << UInt32(7 * i)71            if byte & 0x80 == 0 {72                // a final zero byte after the first one is an over-long encoding73                if i > 0 && byte == 0 { return nil }74                return value <= 0xffff ? UInt16(value) : nil75            }76        }77        return nil78    }79}8081/// An account referenced by an instruction, with what the instruction may do with it.82public struct SolanaAccountMeta: Equatable, Hashable, Sendable {83    public let publicKey: SolanaPublicKey84    public let isSigner: Bool85    public let isWritable: Bool8687    public init(_ publicKey: SolanaPublicKey, isSigner: Bool, isWritable: Bool) {88        self.publicKey = publicKey89        self.isSigner = isSigner90        self.isWritable = isWritable91    }92}9394/// A call to a program: the program, the accounts it receives (in order) and opaque data.95public struct SolanaInstruction: Equatable, Sendable {96    public let programID: SolanaPublicKey97    public let accounts: [SolanaAccountMeta]98    public let data: Bytes99100    public init(programID: SolanaPublicKey, accounts: [SolanaAccountMeta], data: Bytes) {101        self.programID = programID102        self.accounts = accounts103        self.data = data104    }105}106107/// An instruction as it travels: indices into the account list of the message.108public struct SolanaCompiledInstruction: Equatable, Sendable {109    public let programIDIndex: UInt8110    public let accountIndices: [UInt8]111    public let data: Bytes112}113114/// Version-0 messages only: accounts loaded from an on-chain address lookup table. Their addresses are not in the115/// message, so they cannot be shown without reading the table from the chain.116public struct SolanaAddressTableLookup: Equatable, Sendable {117    public let tableAddress: SolanaPublicKey118    public let writableIndices: [UInt8]119    public let readonlyIndices: [UInt8]120}121122/// The part of a transaction that is signed.123///124/// Legacy layout: header (3 bytes) ‖ compact-u16 n ‖ n account keys ‖ recent blockhash ‖ compact-u16 m ‖ m compiled125/// instructions. A version-0 message has a first byte 0x80 and ends with its address table lookups; this type126/// **builds legacy messages only** and parses both.127///128/// Account order (it defines the roles): writable signers (the fee payer first), read-only signers, writable129/// non-signers, read-only non-signers.130public struct SolanaMessage: Equatable, Sendable {131    public enum Version: Equatable, Sendable {132        case legacy133        case v0134    }135136    public let version: Version137    public let numRequiredSignatures: UInt8138    public let numReadonlySignedAccounts: UInt8139    public let numReadonlyUnsignedAccounts: UInt8140    public let accountKeys: [SolanaPublicKey]141    /// 32 bytes: a recent blockhash (the message is valid for about 150 blocks after it) or a durable nonce.142    public let recentBlockhash: Bytes143    public let instructions: [SolanaCompiledInstruction]144    public let addressTableLookups: [SolanaAddressTableLookup]145146    /// Compiles a legacy message, with the account order of the Solana SDK (`Message::new_with_blockhash`): the fee147    /// payer, then inside each role the accounts in byte order. The fee payer is a writable signer whatever the148    /// instructions say; an account is a signer or writable as soon as one instruction needs it to be.149    public init(feePayer: SolanaPublicKey, instructions: [SolanaInstruction], recentBlockhash: Bytes) throws {150        guard recentBlockhash.count == 32 else { throw SolanaError.invalidBlockhash }151        var flags = [SolanaPublicKey: (signer: Bool, writable: Bool)]()152        for instruction in instructions {153            let program = flags[instruction.programID] ?? (false, false)154            flags[instruction.programID] = program155            for account in instruction.accounts {156                let f = flags[account.publicKey] ?? (false, false)157                flags[account.publicKey] = (f.signer || account.isSigner, f.writable || account.isWritable)158            }159        }160        flags[feePayer] = nil161        let others = flags.keys.sorted()162        let writableSigners = others.filter { flags[$0]!.signer && flags[$0]!.writable }163        let readonlySigners = others.filter { flags[$0]!.signer && !flags[$0]!.writable }164        let writable = others.filter { !flags[$0]!.signer && flags[$0]!.writable }165        let readonly = others.filter { !flags[$0]!.signer && !flags[$0]!.writable }166        let keys = [feePayer] + writableSigners + readonlySigners + writable + readonly167        guard keys.count <= 256 else { throw SolanaError.tooManyAccounts }168        var index = [SolanaPublicKey: UInt8]()169        for (i, key) in keys.enumerated() { index[key] = UInt8(i) }170171        version = .legacy172        numRequiredSignatures = UInt8(truncatingIfNeeded: 1 + writableSigners.count + readonlySigners.count)173        guard 1 + writableSigners.count + readonlySigners.count <= 255 else { throw SolanaError.tooManyAccounts }174        numReadonlySignedAccounts = UInt8(readonlySigners.count)175        numReadonlyUnsignedAccounts = UInt8(truncatingIfNeeded: readonly.count)176        accountKeys = keys177        self.recentBlockhash = recentBlockhash178        self.instructions = try instructions.map { instruction in179            guard instruction.accounts.count <= 0xffff, instruction.data.count <= 0xffff else {180                throw SolanaError.invalidInstruction("instruction too large")181            }182            return SolanaCompiledInstruction(programIDIndex: index[instruction.programID]!,183                                             accountIndices: instruction.accounts.map { index[$0.publicKey]! }, data: instruction.data)184        }185        guard instructions.count <= 0xffff else { throw SolanaError.invalidInstruction("too many instructions") }186        addressTableLookups = []187    }188189    init(version: Version, header: (UInt8, UInt8, UInt8), accountKeys: [SolanaPublicKey], recentBlockhash: Bytes,190         instructions: [SolanaCompiledInstruction], addressTableLookups: [SolanaAddressTableLookup]) {191        self.version = version192        numRequiredSignatures = header.0193        numReadonlySignedAccounts = header.1194        numReadonlyUnsignedAccounts = header.2195        self.accountKeys = accountKeys196        self.recentBlockhash = recentBlockhash197        self.instructions = instructions198        self.addressTableLookups = addressTableLookups199    }200201    /// The account that pays the fee: always the first one.202    public var feePayer: SolanaPublicKey { accountKeys[0] }203204    /// The accounts that must sign, in signature order.205    public var signers: [SolanaPublicKey] { Array(accountKeys.prefix(Int(numRequiredSignatures))) }206207    public var recentBlockhashBase58: String { Base58.bitcoin.encode(recentBlockhash) }208209    /// Number of accounts loaded from address lookup tables (version 0 only), which follow the static keys in the210    /// index space of the instructions: writable ones of every table first, then read-only ones.211    public var lookedUpAccountCount: Int {212        addressTableLookups.reduce(0) { $0 + $1.writableIndices.count + $1.readonlyIndices.count }213    }214215    /// True when the static account at `index` signs the transaction.216    public func isSigner(index: Int) -> Bool { index < Int(numRequiredSignatures) }217218    /// True when the message marks the static account at `index` as writable.219    public func isWritable(index: Int) -> Bool {220        let signed = Int(numRequiredSignatures)221        if index < signed { return index < signed - Int(numReadonlySignedAccounts) }222        return index < accountKeys.count - Int(numReadonlyUnsignedAccounts)223    }224225    /// The instruction at `position` with its accounts resolved; nil when it references an account that is only226    /// known through an address lookup table.227    public func instruction(at position: Int) -> SolanaInstruction? {228        guard instructions.indices.contains(position) else { return nil }229        let compiled = instructions[position]230        guard Int(compiled.programIDIndex) < accountKeys.count, compiled.accountIndices.allSatisfy({ Int($0) < accountKeys.count }) else { return nil }231        return SolanaInstruction(programID: accountKeys[Int(compiled.programIDIndex)], accounts: compiled.accountIndices.map {232            SolanaAccountMeta(accountKeys[Int($0)], isSigner: isSigner(index: Int($0)), isWritable: isWritable(index: Int($0)))233        }, data: compiled.data)234    }235236    /// The bytes that are signed.237    public func serialize() -> Bytes {238        var out = Bytes()239        if version == .v0 { out.append(0x80) }240        out += [numRequiredSignatures, numReadonlySignedAccounts, numReadonlyUnsignedAccounts]241        out += SolanaCompactU16.encode(UInt16(accountKeys.count))242        for key in accountKeys { out += key.bytes }243        out += recentBlockhash244        out += SolanaCompactU16.encode(UInt16(instructions.count))245        for instruction in instructions {246            out.append(instruction.programIDIndex)247            out += SolanaCompactU16.encode(UInt16(instruction.accountIndices.count))248            out += instruction.accountIndices249            out += SolanaCompactU16.encode(UInt16(instruction.data.count))250            out += instruction.data251        }252        if version == .v0 {253            out += SolanaCompactU16.encode(UInt16(addressTableLookups.count))254            for lookup in addressTableLookups {255                out += lookup.tableAddress.bytes256                out += SolanaCompactU16.encode(UInt16(lookup.writableIndices.count))257                out += lookup.writableIndices258                out += SolanaCompactU16.encode(UInt16(lookup.readonlyIndices.count))259                out += lookup.readonlyIndices260            }261        }262        return out263    }264265    /// Strict parsing of a serialized message (legacy or version 0); the whole input must be consumed.266    ///267    /// Refused: truncated or trailing bytes, over-long lengths, a version other than 0, no signer, a read-only fee268    /// payer, header counts that exceed the account list, more than 256 accounts, a repeated account key, an269    /// instruction whose program or account index is out of range, a program taken from a lookup table.270    public static func decode(_ bytes: Bytes) throws -> SolanaMessage {271        var offset = 0272        let message = try decode(bytes, at: &offset)273        guard offset == bytes.count else { throw SolanaError.malformed("trailing bytes after the message") }274        return message275    }276277    static func decode(_ bytes: Bytes, at offset: inout Int) throws -> SolanaMessage {278        func take(_ count: Int, _ what: String) throws -> Bytes {279            guard count >= 0, offset + count <= bytes.count else { throw SolanaError.malformed("truncated \(what)") }280            defer { offset += count }281            return Bytes(bytes[offset..<offset + count])282        }283        func length(_ what: String) throws -> Int {284            guard let n = SolanaCompactU16.decode(bytes, at: &offset) else { throw SolanaError.malformed("invalid length of \(what)") }285            return Int(n)286        }287288        var version = Version.legacy289        guard offset < bytes.count else { throw SolanaError.malformed("empty message") }290        if bytes[offset] & 0x80 != 0 {291            guard bytes[offset] == 0x80 else { throw SolanaError.malformed("unsupported message version \(bytes[offset] & 0x7f)") }292            version = .v0293            offset += 1294        }295        let header = try take(3, "header")296        let keyCount = try length("account keys")297        guard keyCount <= 256 else { throw SolanaError.malformed("more than 256 account keys") }298        var keys = [SolanaPublicKey]()299        keys.reserveCapacity(keyCount)300        for _ in 0..<keyCount { keys.append(SolanaPublicKey(bytes: try take(32, "account key"))!) }301        guard Set(keys).count == keys.count else { throw SolanaError.malformed("repeated account key") }302        let signed = Int(header[0]), readonlySigned = Int(header[1]), readonlyUnsigned = Int(header[2])303        guard signed >= 1 else { throw SolanaError.malformed("no required signature") }304        guard readonlySigned < signed else { throw SolanaError.malformed("the fee payer is not writable") }305        guard signed + readonlyUnsigned <= keyCount else { throw SolanaError.malformed("header counts exceed the account keys") }306        let blockhash = try take(32, "recent blockhash")307308        let instructionCount = try length("instructions")309        var compiled = [SolanaCompiledInstruction]()310        for _ in 0..<instructionCount {311            let program = try take(1, "program index")[0]312            let accounts = try take(try length("instruction accounts"), "instruction accounts")313            let data = try take(try length("instruction data"), "instruction data")314            compiled.append(SolanaCompiledInstruction(programIDIndex: program, accountIndices: accounts, data: data))315        }316317        var lookups = [SolanaAddressTableLookup]()318        if version == .v0 {319            let lookupCount = try length("address table lookups")320            for _ in 0..<lookupCount {321                let table = SolanaPublicKey(bytes: try take(32, "lookup table address"))!322                let writable = try take(try length("lookup writable indices"), "lookup writable indices")323                let readonly = try take(try length("lookup read-only indices"), "lookup read-only indices")324                guard !writable.isEmpty || !readonly.isEmpty else { throw SolanaError.malformed("empty address table lookup") }325                lookups.append(SolanaAddressTableLookup(tableAddress: table, writableIndices: writable, readonlyIndices: readonly))326            }327            guard Set(lookups.map(\.tableAddress)).count == lookups.count else { throw SolanaError.malformed("repeated lookup table") }328        }329        let message = SolanaMessage(version: version, header: (header[0], header[1], header[2]), accountKeys: keys, recentBlockhash: blockhash,330                                    instructions: compiled, addressTableLookups: lookups)331        let total = keyCount + message.lookedUpAccountCount332        guard total <= 256 else { throw SolanaError.malformed("more than 256 accounts") }333        for instruction in compiled {334            // a program is always a static key, and never the fee payer335            guard Int(instruction.programIDIndex) < keyCount, instruction.programIDIndex != 0 else {336                throw SolanaError.malformed("program index out of range")337            }338            guard instruction.accountIndices.allSatisfy({ Int($0) < total }) else { throw SolanaError.malformed("account index out of range") }339        }340        return message341    }342}343344/// A transaction: one 64-byte Ed25519 signature per required signer, in the order of the first account keys, then345/// the message. The first signature is the transaction identifier.346public struct SolanaTransaction: Equatable, Sendable {347    /// Largest serialized transaction a validator accepts (one UDP packet: 1280 − 40 − 8 bytes).348    public static let maximumSize = 1232349350    /// One entry per required signer; 64 zero bytes while that signer has not signed.351    public private(set) var signatures: [Bytes]352    public let message: SolanaMessage353354    /// An unsigned transaction (every signature is zero): what `simulateTransaction` accepts with `sigVerify: false`.355    public init(message: SolanaMessage) {356        self.message = message357        signatures = Array(repeating: Bytes(repeating: 0, count: 64), count: Int(message.numRequiredSignatures))358    }359360    /// Signs the serialized message with the 32-byte Ed25519 seed of one of the required signers and stores the361    /// signature at that signer's position. Throws `notASigner` when the key is not a required signer.362    public mutating func sign(privateSeed: Bytes) throws {363        guard let publicKey = try? Ed25519.publicKey(seed: privateSeed) else { throw SolanaError.invalidSeed }364        guard let position = message.signers.firstIndex(where: { $0.bytes == publicKey }) else { throw SolanaError.notASigner }365        guard let signature = try? Ed25519.sign(message: message.serialize(), seed: privateSeed) else { throw SolanaError.invalidSeed }366        signatures[position] = signature367    }368369    /// True when no signature slot is empty.370    public var isFullySigned: Bool { signatures.allSatisfy { $0 != Bytes(repeating: 0, count: 64) } }371372    /// True when every signature is a valid Ed25519 signature of the message by the corresponding signer373    /// (strict verification, as validators do).374    public func verifySignatures() -> Bool {375        let bytes = message.serialize()376        let signers = message.signers377        guard signatures.count == signers.count else { return false }378        return zip(signatures, signers).allSatisfy { Ed25519.verify(signature: $0, message: bytes, publicKey: $1.bytes) }379    }380381    /// The transaction identifier (base58 of the first signature); nil while the fee payer has not signed.382    public var id: String? {383        guard let first = signatures.first, first != Bytes(repeating: 0, count: 64) else { return nil }384        return Base58.bitcoin.encode(first)385    }386387    /// Wire format: compact-u16 signature count ‖ signatures ‖ message. Throws when it exceeds `maximumSize`.388    public func serialize() throws -> Bytes {389        var out = SolanaCompactU16.encode(UInt16(signatures.count))390        for signature in signatures { out += signature }391        out += message.serialize()392        guard out.count <= Self.maximumSize else { throw SolanaError.transactionTooLarge(out.count) }393        return out394    }395396    /// The wire format in base64, as `sendTransaction` and `simulateTransaction` expect with `encoding: base64`.397    public func base64() throws -> String { SolanaBase64.encode(try serialize()) }398399    /// Strict parsing of a serialized transaction, signed or not. The number of signatures must equal the number of400    /// required signers of the message, and nothing may follow the message. Signatures are **not** verified here401    /// (`verifySignatures`).402    public static func decode(_ bytes: Bytes) throws -> SolanaTransaction {403        guard bytes.count <= maximumSize else { throw SolanaError.transactionTooLarge(bytes.count) }404        var offset = 0405        guard let count = SolanaCompactU16.decode(bytes, at: &offset) else { throw SolanaError.malformed("invalid signature count") }406        guard offset + Int(count) * 64 <= bytes.count else { throw SolanaError.malformed("truncated signatures") }407        var signatures = [Bytes]()408        for _ in 0..<Int(count) {409            signatures.append(Bytes(bytes[offset..<offset + 64]))410            offset += 64411        }412        let message = try SolanaMessage.decode(bytes, at: &offset)413        guard offset == bytes.count else { throw SolanaError.malformed("trailing bytes after the transaction") }414        guard signatures.count == Int(message.numRequiredSignatures) else { throw SolanaError.malformed("signature count differs from the required signers") }415        var transaction = SolanaTransaction(message: message)416        transaction.signatures = signatures417        return transaction418    }419420    public static func decode(base64 text: String) throws -> SolanaTransaction {421        guard let bytes = SolanaBase64.decode(text) else { throw SolanaError.malformed("invalid base64") }422        return try decode(bytes)423    }424}425426/// Standard base64 (RFC 4648 §4) with padding. The decoder is strict: alphabet characters only, correct padding,427/// no white space, canonical trailing bits.428public enum SolanaBase64 {429    private static let alphabet = Array("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".utf8)430431    public static func encode(_ bytes: Bytes) -> String {432        var out = Bytes()433        out.reserveCapacity((bytes.count + 2) / 3 * 4)434        var i = 0435        while i < bytes.count {436            let b0 = bytes[i]437            let b1: UInt8 = i + 1 < bytes.count ? bytes[i + 1] : 0438            let b2: UInt8 = i + 2 < bytes.count ? bytes[i + 2] : 0439            out.append(alphabet[Int(b0 >> 2)])440            out.append(alphabet[Int((b0 & 3) << 4 | b1 >> 4)])441            out.append(i + 1 < bytes.count ? alphabet[Int((b1 & 15) << 2 | b2 >> 6)] : UInt8(ascii: "="))442            out.append(i + 2 < bytes.count ? alphabet[Int(b2 & 63)] : UInt8(ascii: "="))443            i += 3444        }445        return String(decoding: out, as: UTF8.self)446    }447448    public static func decode(_ text: String) -> Bytes? {449        let input = Array(text.utf8)450        guard input.count % 4 == 0 else { return nil }451        func value(_ c: UInt8) -> UInt32? {452            switch c {453            case 0x41...0x5a: return UInt32(c - 0x41)454            case 0x61...0x7a: return UInt32(c - 0x61 + 26)455            case 0x30...0x39: return UInt32(c - 0x30 + 52)456            case 0x2b: return 62457            case 0x2f: return 63458            default: return nil459            }460        }461        var out = Bytes()462        out.reserveCapacity(input.count / 4 * 3)463        var i = 0464        while i < input.count {465            let last = i + 4 == input.count466            let pad = last ? (input[i + 3] == 0x3d ? (input[i + 2] == 0x3d ? 2 : 1) : 0) : 0467            guard let v0 = value(input[i]), let v1 = value(input[i + 1]) else { return nil }468            var v2: UInt32 = 0, v3: UInt32 = 0469            if pad < 2 {470                guard let v = value(input[i + 2]) else { return nil }471                v2 = v472            }473            if pad < 1 {474                guard let v = value(input[i + 3]) else { return nil }475                v3 = v476            }477            let word = v0 << 18 | v1 << 12 | v2 << 6 | v3478            out.append(UInt8(truncatingIfNeeded: word >> 16))479            if pad < 2 { out.append(UInt8(truncatingIfNeeded: word >> 8)) }480            if pad < 1 { out.append(UInt8(truncatingIfNeeded: word)) }481            // the bits that are not part of the data must be zero482            if pad == 2, v1 & 15 != 0 { return nil }483            if pad == 1, v2 & 3 != 0 { return nil }484            i += 4485        }486        return out487    }488}489
Files main
Menu

Theme