48 lines
1.4 KiB
Swift
48 lines
1.4 KiB
Swift
//
|
|
// Wallet.swift
|
|
// SwiftChain
|
|
//
|
|
// Created by Victor on 27/11/2024.
|
|
//
|
|
|
|
import CryptoKit
|
|
import Foundation
|
|
|
|
public class Wallet {
|
|
private let privateKey: Curve25519.Signing.PrivateKey
|
|
let publicKey: Curve25519.Signing.PublicKey
|
|
public let address: String
|
|
|
|
public init() {
|
|
// Générer une nouvelle paire de clés
|
|
privateKey = Curve25519.Signing.PrivateKey()
|
|
publicKey = privateKey.publicKey
|
|
|
|
// Créer une adresse au format swift_(hash)
|
|
let pubKeyData = publicKey.rawRepresentation
|
|
let hash = SHA256.hash(data: pubKeyData)
|
|
let hashString = hash.compactMap { String(format: "%02x", $0) }.joined()
|
|
address = "swift_" + hashString.prefix(40)
|
|
}
|
|
|
|
// Signer une transaction
|
|
public func signTransaction(_ transaction: Transaction) -> Data? {
|
|
let messageData = transaction.messageToSign()
|
|
return try? privateKey.signature(for: messageData)
|
|
}
|
|
|
|
// Vérifier une signature
|
|
static func verifySignature(for transaction: Transaction, signature: Data, publicKeyData: Data) -> Bool {
|
|
guard let publicKey = try? Curve25519.Signing.PublicKey(rawRepresentation: publicKeyData) else {
|
|
return false
|
|
}
|
|
|
|
return publicKey.isValidSignature(signature, for: transaction.messageToSign())
|
|
}
|
|
|
|
// Obtenir la clé publique en format Data
|
|
public func getPublicKeyData() -> Data {
|
|
return publicKey.rawRepresentation
|
|
}
|
|
}
|