-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathUtils.swift
More file actions
1212 lines (1039 loc) · 48.5 KB
/
Utils.swift
File metadata and controls
1212 lines (1039 loc) · 48.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Copyright (c) 2025, Circle Internet Group, Inc. All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import Web3Core
import web3swift
import BigInt
import CryptoKit
/// A utility struct providing essential helper methods for encoding, verification, and data processing
/// related to blockchain operations, WebAuthn integration, and ABI handling.
///
/// The `Utils` struct serves as a centralized collection of static functions that simplify common
/// operations such as encoding ABI functions, verifying digital signatures, generating hashes for user
/// operations, and creating calldata for blockchain transactions.
///
/// ## Features
/// - Encode function data for ABI-based smart contracts.
/// - Verify digital signatures using WebAuthn public keys.
/// - Generate hashes for user operations to ensure data integrity.
/// - Encode ERC20 token transfers and general contract executions into calldata.
/// - Support for common blockchain standards like EIP-1559 and WebAuthn.
///
/// ## Use Cases
/// - Simplify integration with smart contract operations in decentralized applications.
/// - Facilitate secure authentication workflows using WebAuthn.
/// - Enable seamless user operation handling for blockchain networks.
///
/// ### Example Usage
/// ```swift
/// let encodedData = Utils.encodeFunctionData(
/// functionName: "transfer",
/// abiJson: tokenABI,
/// args: ["0xRecipientAddress", "1000"]
/// )
///
/// let isVerified = try Utils.verify(
/// hash: "0xHash",
/// publicKey: "0xPublicKey",
/// signature: "0xSignature",
/// webauthn: webAuthnData
/// )
/// ```
public struct Utils {
/// Encode abi function
///
/// - Parameters:
/// - functionName: ABI function name
/// - abiJson: ABI json
/// - args: Input array for the ABI function
///
/// - Returns: Encoded ABI function
public static func encodeFunctionData(functionName: String,
abiJson: String,
args: [Any]) -> String? {
guard let contract = try? EthereumContract(abiJson),
let callData = contract.method(functionName, parameters: args, extraData: nil) else {
logger.utils.notice("This abiJson cannot be parsed or the given contract method cannot be called with the given parameters")
return nil
}
logger.utils.notice("callData:\n\(HexUtils.dataToHex(callData))")
return HexUtils.dataToHex(callData)
}
/// Verifies a signature using the credential public key and the hash which was signed.
///
/// - Parameters:
/// - hash: (hex) string
/// - publicKey: (serialized hex) string
/// - signature: (serialized hex) string
/// - webauthn: WebAuthnData
///
/// - Returns: Verification success or failure
public static func verify(hash: String,
publicKey: String,
signature: String,
webauthn: WebAuthnData) throws -> Bool {
do {
let rawClientData = try webauthn.clientDataJSON.bytes
let clientData = try JSONDecoder().decode(CollectedClientData.self, from: Data(rawClientData))
let rawAuthenticatorData = try HexUtils.hexToBytes(hex: webauthn.authenticatorData)
let authenticatorData = try AuthenticatorData(bytes: rawAuthenticatorData)
guard let expectedChallengeData = HexUtils.hexToData(hex: hash) else {
logger.utils.error("Failed to decode the hash (\"\(hash)\") hex string into Data struct.")
return false
}
let publicKeyBytes = try HexUtils.hexToBytes(hex: publicKey)
guard let signature = HexUtils.hexToData(hex: signature) else {
logger.utils.error("Failed to decode the signature (\"\(signature)\") hex string into Data struct.")
return false
}
try _verify(
clientData: clientData,
rawClientData: rawClientData,
authenticatorData: authenticatorData,
rawAuthenticatorData: rawAuthenticatorData,
requireUserVerification: webauthn.userVerificationRequired,
expectedChallenge: expectedChallengeData.bytes,
credentialPublicKey: publicKeyBytes,
signature: signature
)
return true
} catch let error as DecodingError {
throw BaseError(shortMessage: "Failed to get the CollectedClientData object from rawClientData.",
args: .init(cause: error, name: String(describing: error)))
} catch let error as HexConversionError {
throw BaseError(shortMessage: "Failed to decode the authenticatorData/publicKey hex string into UInt8 array.",
args: .init(cause: error, name: String(describing: error)))
} catch let error as WebAuthnError {
throw BaseError(shortMessage: "Failed to get the AuthenticatorData object from rawAuthenticatorData.",
args: .init(cause: error, name: String(describing: error)))
} catch let error as BaseError {
logger.webAuthn.notice("Error: \(error)")
throw error
} catch {
logger.webAuthn.notice("Error: \(error)")
throw BaseError(shortMessage: error.localizedDescription,
args: .init(cause: error, name: String(describing: error)))
}
}
/// Generates the hash of a user operation.
///
/// - Parameters:
/// - chainId: The ID of the blockchain network.
/// - entryPointAddress: The address of the entry point contract. Defaults to the address of `EntryPoint.V07`.
/// - userOp: The user operation to hash.
///
/// - Returns: The hash of the user operation as a hex string.
public static func getUserOperationHash(
chainId: Int,
entryPointAddress: String = ENTRYPOINT_V07_ADDRESS,
userOp: UserOperationV07
) throws -> String {
var accountGasLimits = [UInt8]()
if let verificationGasLimit = userOp.verificationGasLimit,
let callGasLimit = userOp.callGasLimit {
let verificationGasLimitHex = try HexUtils.bigIntToHex(verificationGasLimit, withPrefix: false)
let verificationGasLimitHexWithPadding = verificationGasLimitHex.leftPadding(toLength: 32, withPad: "0")
let callGasLimitHex = try HexUtils.bigIntToHex(callGasLimit, withPrefix: false)
let callGasLimitHexWithPadding = callGasLimitHex.leftPadding(toLength: 32, withPad: "0")
let finalHex = verificationGasLimitHexWithPadding + callGasLimitHexWithPadding
if let accountGasLimitsData = HexUtils.hexToData(hex: finalHex) {
accountGasLimits = accountGasLimitsData.bytes
}
}
var callDataHashed = Data()
if let callDataHex = userOp.callData,
let callData = HexUtils.hexToData(hex: callDataHex) {
callDataHashed = callData.sha3(.keccak256)
}
var gasFees = [UInt8]()
if let maxPriorityFeePerGas = userOp.maxPriorityFeePerGas,
let maxFeePerGas = userOp.maxFeePerGas {
let maxPriorityFeePerGasHex = try HexUtils.bigIntToHex(maxPriorityFeePerGas, withPrefix: false)
let maxPriorityFeePerGasHexWithPadding = maxPriorityFeePerGasHex.leftPadding(toLength: 32, withPad: "0")
let maxFeePerGasHex = try HexUtils.bigIntToHex(maxFeePerGas, withPrefix: false)
let maxFeePerGasHexWithPadding = maxFeePerGasHex.leftPadding(toLength: 32, withPad: "0")
let finalHex = maxPriorityFeePerGasHexWithPadding + maxFeePerGasHexWithPadding
if let gasFeesData = HexUtils.hexToData(hex: finalHex) {
gasFees = gasFeesData.bytes
}
}
var initCodeHashed = Data()
var initCodeHex = "0x"
if let factory = userOp.factory,
let factoryData = userOp.factoryData {
initCodeHex = factory.noHexPrefix + factoryData.noHexPrefix
}
if let initCodeData = HexUtils.hexToData(hex: initCodeHex) {
initCodeHashed = initCodeData.sha3(.keccak256)
}
var paymasterAndDataHashed = Data()
var paymasterAndDataHex = "0x"
if let paymaster = userOp.paymaster {
let paymasterVerificationGasLimit = userOp.paymasterVerificationGasLimit ?? BigInt.zero
let verificationGasLimitHex = try HexUtils.bigIntToHex(paymasterVerificationGasLimit, withPrefix: false)
let verificationGasLimitHexWithPadding = verificationGasLimitHex.leftPadding(toLength: 32, withPad: "0")
let paymasterPostOpGasLimit = userOp.paymasterPostOpGasLimit ?? BigInt.zero
let postOpGasLimitHex = try HexUtils.bigIntToHex(paymasterPostOpGasLimit, withPrefix: false)
let postOpGasLimitHexWithPadding = postOpGasLimitHex.leftPadding(toLength: 32, withPad: "0")
let paymasterData = userOp.paymasterData?.noHexPrefix ?? ""
paymasterAndDataHex = paymaster + verificationGasLimitHexWithPadding + postOpGasLimitHexWithPadding + paymasterData
}
if let paymasterAndData = HexUtils.hexToData(hex: paymasterAndDataHex) {
paymasterAndDataHashed = paymasterAndData.sha3(.keccak256)
}
var types: [ABI.Element.ParameterType] = [
.address,
.uint(bits: 256),
.bytes(length: 32),
.bytes(length: 32),
.bytes(length: 32),
.uint(bits: 256),
.bytes(length: 32),
.bytes(length: 32)
]
var values = [Any]()
if let sender = userOp.sender,
let nonce = userOp.nonce,
let preVerificationGas = userOp.preVerificationGas {
values = [
sender,
nonce,
initCodeHashed,
callDataHashed,
accountGasLimits,
preVerificationGas,
gasFees,
paymasterAndDataHashed
]
}
var packedUserOpData = Data()
if let _packedUserOpData = ABIEncoder.encode(types: types, values: values) {
packedUserOpData = _packedUserOpData
}
let packedUserOpHashed = packedUserOpData.sha3(.keccak256)
logger.utils.debug("packedUserOp hashed : \(HexUtils.dataToHex(packedUserOpHashed))")
types = [.bytes(length: 32), .address, .uint(bits: 256)]
values = [packedUserOpHashed, entryPointAddress, chainId]
var userOpData = Data()
if let _userOpData = ABIEncoder.encode(types: types, values: values) {
userOpData = _userOpData
}
let userOpHashed = userOpData.sha3(.keccak256)
return HexUtils.dataToHex(userOpHashed)
}
/// Encodes an ERC20 token transfer into calldata for executing a User Operation.
///
/// - Parameters:
/// - to: The recipient address.
/// - token: The token contract address or the name of the `Token` enum.
/// - amount: The amount to transfer.
///
/// - Returns: The encoded transfer abi and contract address.
public static func encodeTransfer(to: String,
token: String,
amount: BigInt) -> EncodeTransferResult {
let abiParameters: [Any] = [to, amount]
let encodedAbi = self.encodeFunctionData(
functionName: "transfer",
abiJson: ERC20_ABI,
args: abiParameters
)
return EncodeTransferResult(data: encodedAbi ?? "0x",
to: CONTRACT_ADDRESS[token] ?? token)
}
/// Encodes a contract execution into calldata for executing a User Operation.
///
/// - Parameters:
/// - to: The recipient address.
/// - abiSignature: The ABI signature of the function.
/// - args: The arguments for the function call.
/// - value: The value to send with the transaction.
///
/// - Returns: The encoded call data.
public static func encodeContractExecution(
to: String,
abiSignature: String,
args: [Any] = [],
value: BigInt
) -> String {
let signatureParts = abiSignature.split(separator: "(", maxSplits: 1)
let functionName = String(signatureParts[0])
let parameterTypesString = signatureParts[1].dropLast()
let parameterTypes = parseParameterTypes(String(parameterTypesString))
let function = ABI.Element.Function(name: functionName,
inputs: parameterTypes,
outputs: [],
constant: false,
payable: false)
guard let encodedABI = function.encodeParameters(args) else {
logger.utils.notice("Failed to encode parameters (\(args) of a given contract method")
return ""
}
let arg = EncodeCallDataArg(
to: to,
value: value,
data: HexUtils.dataToHex(encodedABI)
)
return Utils.encodeCallData(arg: arg)
}
}
extension Utils {
private typealias InOut = ABI.Element.InOut
// MARK: Internal Usage
static func _verify(
clientData: CollectedClientData,
rawClientData: [UInt8],
authenticatorData: AuthenticatorData,
rawAuthenticatorData: [UInt8],
requireUserVerification: Bool,
expectedChallenge: [UInt8],
credentialPublicKey: [UInt8],
signature: Data
) throws {
try clientData.verify(storedChallenge: expectedChallenge,
ceremonyType: .assert)
guard authenticatorData.flags.userPresent else { throw WebAuthnError.userPresentFlagNotSet }
if requireUserVerification {
guard authenticatorData.flags.userVerified else { throw WebAuthnError.userVerifiedFlagNotSet }
}
let clientDataHash = SHA256.hash(data: rawClientData)
let signatureBase = rawAuthenticatorData + clientDataHash
let credentialPublicKey = try CredentialPublicKey(publicKeyBytes: credentialPublicKey)
try credentialPublicKey.verify(signature: signature, data: signatureBase)
}
/// ABI JSON:
/// https://github.com/wevm/viem/blob/main/src/account-abstraction/accounts/implementations/toCoinbaseSmartAccount.ts#L553-L562
static func encodeCallData(arg: EncodeCallDataArg) -> String {
let functionName = "execute"
let input1 = InOut(name: "target", type: .address)
let input2 = InOut(name: "value", type: .uint(bits: 256))
let input3 = InOut(name: "data", type: .dynamicBytes)
let function = ABI.Element.Function(name: functionName,
inputs: [input1, input2, input3],
outputs: [],
constant: false,
payable: true)
let params: [Any] = [arg.to, arg.value ?? BigInt(0), arg.data ?? "0x"]
let encodedData = function.encodeParameters(params)
return HexUtils.dataToHex(encodedData)
}
/// ABI JSON:
/// https://github.com/wevm/viem/blob/main/src/account-abstraction/accounts/implementations/toCoinbaseSmartAccount.ts#L563-L580
/// Logic:
/// https://github.com/wevm/viem/blob/main/src/account-abstraction/accounts/implementations/toCoinbaseSmartAccount.ts#L122-L140
static func encodeCallData(args: [EncodeCallDataArg]) -> String {
if args.count == 1 {
return encodeCallData(arg: args[0])
}
let functionName = "executeBatch"
let tupleTypes: [ABI.Element.ParameterType] = [
.address,
.uint(bits: 256),
.dynamicBytes
]
let input = InOut(name: "calls", type: .array(type: .tuple(types: tupleTypes), length: 0))
let function = ABI.Element.Function(name: functionName,
inputs: [input],
outputs: [],
constant: false,
payable: false)
let params: [Any] = args.map {
[$0.to, $0.value ?? BigInt(0), $0.data ?? "0x"]
}
let encodedData = function.encodeParameters([params])
return HexUtils.dataToHex(encodedData)
}
static func encodePacked(_ parameters: [Any]) -> String {
let encoded = parameters.reduce("") { (partialResult, parameter) in
return partialResult + HexUtils.dataToHex(try? ABIEncoder.abiEncode(parameter), withPrefix: false)
}
return encoded
}
static func isAddress(_ to: String) -> Bool {
return to.range(of: #"^0x[a-fA-F0-9]{40}$"#, options: .regularExpression) != nil
}
static func hashMessage(hex: String) -> String {
var bytes = [UInt8]()
if let _bytes = try? HexUtils.hexToBytes(hex: hex) {
bytes = _bytes
}
return hashMessage(byteArray: bytes)
}
static func hashMessage(byteArray: [UInt8]) -> String {
let hash = Utilities.hashPersonalMessage(Data(byteArray))
return HexUtils.dataToHex(hash)
}
static func parseFactoryAddressAndData(initCode: String) -> (factoryAddress: String, factoryData: String) {
guard initCode.count >= 42 else {
logger.utils.error("initCode must be at least 42 characters long")
return ("", "")
}
let factoryAddress = String(initCode.prefix(42))
let factoryData = "0x\(initCode.dropFirst(42))"
return (factoryAddress, factoryData)
}
static func parseParameterTypes(_ typesString: String) -> [ABI.Element.InOut] {
guard !typesString.isEmpty else {
return []
}
var currentTypeString = ""
var types = [ABI.Element.InOut]()
var tupleStack = [ABI.Element.ParameterType]()
var arrayBalance = 0
var tempTuple: ABI.Element.ParameterType?
func popLastTupleFormStack() -> [ABI.Element.ParameterType]? {
if let parameterType = tupleStack.popLast() {
switch parameterType {
case .tuple(types: let elements):
return elements
default:
// Tuple stack could only store tuple, if not just return nil
return nil
}
} else {
// Not a valid ABI signature
return nil
}
}
for i in 0..<typesString.count {
switch Array(typesString)[i] {
case "(":
tupleStack.append(.tuple(types: []))
case ")":
if currentTypeString.isEmpty {
guard let elements = popLastTupleFormStack() else {
return []
}
let tuple = ABI.Element.ParameterType.tuple(types: elements)
// check next char is array or not
if (i + 1) < typesString.count && Array(typesString)[i + 1] == "[" {
tempTuple = tuple
continue
}
if let elements = popLastTupleFormStack() {
tupleStack.append(.tuple(types: elements + [tuple]))
} else {
let type = ABI.Element.InOut(name: "", type: tuple)
types.append(type)
}
continue
}
guard let parsedABIType = try? ABITypeParser.parseTypeString(currentTypeString),
let elements = popLastTupleFormStack() else {
// Parse error
return []
}
currentTypeString = ""
let tuple = ABI.Element.ParameterType.tuple(types: elements + [parsedABIType])
// check next char is array or not
if (i + 1) < typesString.count && Array(typesString)[i + 1] == "[" {
tempTuple = tuple
continue
}
if let elements = popLastTupleFormStack() {
tupleStack.append(.tuple(types: elements + [tuple]))
} else {
let type = ABI.Element.InOut(name: "", type: tuple)
types.append(type)
}
case ",":
if currentTypeString.isEmpty {
continue
}
guard let parsedABIType = try? ABITypeParser.parseTypeString(currentTypeString) else {
// Parse error
return []
}
if let elements = popLastTupleFormStack() {
let tuple = ABI.Element.ParameterType.tuple(types: elements + [parsedABIType])
tupleStack.append(tuple)
} else {
let type = ABI.Element.InOut(name: "", type: parsedABIType)
types.append(type)
}
currentTypeString = ""
case "[":
arrayBalance += 1
case "]":
arrayBalance -= 1
if arrayBalance != 0 {
return []
}
if let tuple = tempTuple {
let arr = ABI.Element.ParameterType.array(type: tuple, length: 0)
if let elements = popLastTupleFormStack() {
let tuple = ABI.Element.ParameterType.tuple(types: elements + [arr])
tupleStack.append(tuple)
} else {
let type = ABI.Element.InOut(name: "", type: arr)
types.append(type)
}
tempTuple = nil
} else {
guard let parsedABIType = try? ABITypeParser.parseTypeString(currentTypeString) else {
return []
}
currentTypeString = ""
let arr = ABI.Element.ParameterType.array(type: parsedABIType, length: 0)
if let elements = popLastTupleFormStack() {
let tuple = ABI.Element.ParameterType.tuple(types: elements + [arr])
tupleStack.append(tuple)
} else {
let type = ABI.Element.InOut(name: "", type: arr)
types.append(type)
}
}
default:
currentTypeString.append(Array(typesString)[i])
}
}
// When there is no tuple
if !currentTypeString.isEmpty {
guard let parsedABIType = try? ABITypeParser.parseTypeString(currentTypeString) else {
return []
}
if popLastTupleFormStack() != nil {
// In this case, there's an opening parenthesis but no closing parenthesis.
// test case "(string"
return []
}
let type = ABI.Element.InOut(name: "", type: parsedABIType)
types.append(type)
}
return types
}
enum PollingError: Error {
case timeout
case noResult
}
/// Starts polling for a result by repeatedly executing a given asynchronous block.
///
/// - Parameters:
/// - pollingInterval: The time interval in milliseconds between each polling attempt.
/// - retryCount: The maximum number of times to retry polling if a result is not obtained.
/// - timeout: An optional timeout period in seconds. If provided, the polling will stop if this duration is exceeded.
/// - block: An asynchronous closure that returns a value of type T? which will be polled repeatedly.
///
/// - Throws:
/// - PollingError.timeoutError if the polling operation exceeds the specified timeout period.
///
/// - Returns: An optional value of type T? if a result is obtained within the allowed polling attempts and timeout period.
static func startPolling<T>(pollingInterval: Int,
retryCount: Int,
timeout: Int?,
block: @escaping () async throws -> T) async throws -> T {
logger.utils.debug("Start polling, retryCount: \(retryCount)")
var currentCount = 0
let startTime = Date() // Record the start time
while currentCount < retryCount {
logger.utils.debug("Polling currentCount: \(currentCount)")
if let result = try? await block() {
logger.utils.debug("Polling got result: \(currentCount)")
return result
}
// Check if the timeout has been exceeded
if let timeout = timeout, Date().timeIntervalSince(startTime) > Double(timeout) {
throw PollingError.timeout
}
currentCount += 1
try? await Task.sleep(nanoseconds: UInt64(pollingInterval) * 1_000_000) // Convert milliseconds to nanoseconds
}
throw PollingError.noResult
}
static func pemToCOSE(pemKey: String) throws -> [UInt8] {
// 1. Decode Base64URL string
guard let keyBytes = URLEncodedBase64(pemKey).decodedBytes else {
throw BaseError(shortMessage: "PEMToCOSE(pemKey: \"\(pemKey)\" Invalid Base64URL encoding")
}
// 2. Composition PEM Document format
let pemStrs = Data(keyBytes).base64EncodedString().split(every: 64)
var pemDocument = "-----BEGIN PUBLIC KEY-----\n"
pemStrs.forEach {
pemDocument += $0 + "\n"
}
pemDocument += "-----END PUBLIC KEY-----"
do {
// 3. Parse public key data
let publicKey = try P256.Signing.PublicKey(pemRepresentation: pemDocument)
// 4. Construct COSE format
var coseKey: [UInt8] = []
// COSE Key Common Parameters
coseKey.append(contentsOf: [
0xa5, // map of 5 pairs
0x01, 0x02, // kty: EC2
0x03, 0x26, // alg: ES256 (-7) in CBOR encoding
0x20, 0x01, // crv: P-256
])
// Public Key X coordinate
coseKey.append(0x21) // x coordinate (negative integer for key -2)
coseKey.append(0x58) // bytes
coseKey.append(0x20) // 32 bytes
coseKey.append(contentsOf: publicKey.rawRepresentation.prefix(32))
// Public Key Y coordinate
coseKey.append(0x22) // y coordinate (negative integer for key -3)
coseKey.append(0x58) // bytes
coseKey.append(0x20) // 32 bytes
coseKey.append(contentsOf: publicKey.rawRepresentation.suffix(32))
return coseKey
} catch {
throw BaseError(shortMessage: "Failed to parse public key data (\(error))",
args: .init(cause: error, name: String(describing: error)))
}
}
// Function to extract r and s from a DER-encoded ECDSA signature
static func extractRSFromDER(_ signatureHex: String) -> (r: Data, s: Data)? {
// 1. The signature in DER format should be encoded using ASN.1.
guard let signatureData = HexUtils.hexToData(hex: signatureHex) else {
logger.utils.notice("Invalid hexadecimal signature string")
return nil
}
// 2. Parse the DER-encoded signature
var offset = 0
// 3. Check the signature starts with the correct identifier for a SEQUENCE (0x30)
guard signatureData[offset] == 0x30 else {
logger.utils.notice("Invalid signature")
return nil
}
offset += 1
// 4. Check that the length of the SEQUENCE matches the total length of the signature data
guard signatureData[offset] == signatureData.count - 2 else {
logger.utils.notice("Invalid signature")
return nil
}
offset += 1
// 5. Check for the INTEGER identifier (0x02) and reads the length of r,
// then extracts the corresponding bytes.
guard signatureData[offset] == 0x02 else {
logger.utils.notice("Invalid signature")
return nil
}
offset += 1
let rLength = Int(signatureData[offset])
offset += 1
let r = signatureData[offset..<offset + rLength]
offset += rLength
// 6. Similar to r, it checks for the INTEGER identifier (0x02), reads the length of s,
// and then extracts the bytes.
guard signatureData[offset] == 0x02 else {
logger.utils.notice("Invalid signature")
return nil
}
offset += 1
let sLength = Int(signatureData[offset])
offset += 1
let s = signatureData[offset..<offset + sLength]
return (r, s)
}
// Function to create a DER-encoded ECDSA signature from r and s
static func packRSIntoDer(_ signature: (r: Data, s: Data)) -> String {
// 1. DER encoding format
let rLength = signature.r.count
let sLength = signature.s.count
// 2. Build the DER encoded data
var der = Data()
// 3. Add sequence tag
der.append(0x30) // SEQUENCE
der.append(UInt8(rLength + sLength + 4)) // Length of the entire sequence
// 4. Add r
der.append(0x02) // INTEGER
der.append(UInt8(rLength)) // Length of r
der.append(signature.r) // Value of s
// 5. Add s
der.append(0x02) // INTEGER
der.append(UInt8(sLength)) // Length of s
der.append(signature.s) // Value of s
return HexUtils.dataToHex(der)
}
/// Helper function to serialize ECDSA signature data into a hex string.
/// Combines r, s, and v components into a single hex string.
///
/// - Parameter signature: The ECDSA signature to serialize.
///
/// - Returns: The serialized signature as a hex string.
static func serializeSignature(_ signature: Data) -> String {
// web3swift signature format is: [r (32 bytes)][s (32 bytes)][v (1 byte)]
guard signature.count == 65 else {
return "0x" + signature.toHexString()
}
let r = signature.prefix(32)
let s = signature.subdata(in: 32..<64)
let v = signature.subdata(in: 64..<65)
return "0x" + r.toHexString() + s.toHexString() + v.toHexString()
}
/// Helper function to deserializes a signature string into an `UnmarshaledSignature` object.
///
/// - Parameter signature: The signature string in hex format.
///
/// - Returns: An `UnmarshaledSignature` object containing the v, r, and s components of the signature.
/// - Throws: `BaseError` if the signature format is invalid or cannot be parsed.
static func deserializeSignature(_ signature: String) throws -> SECP256K1.UnmarshaledSignature {
guard let signatureData = HexUtils.hexToData(hex: signature),
signatureData.count == 65 else {
throw BaseError(shortMessage: "Invalid signature format")
}
let r = signatureData.subdata(in: 0..<32)
let s = signatureData.subdata(in: 32..<64)
let v = signatureData[64]
return SECP256K1.UnmarshaledSignature(v: v, r: r, s: s)
}
static func toData(value: String) -> Data {
let data: Data
if value.isHex {
data = HexUtils.hexToData(hex: value) ?? .init()
} else {
data = Data(value.utf8)
}
return data
}
static func toSha3Data(message: String) -> Data {
let digest: Data
if message.isHex {
digest = (HexUtils.hexToData(hex: message) ?? .init()).sha3(.keccak256)
} else {
digest = Data(message.utf8).sha3(.keccak256)
}
return digest
}
// Function to pad Data to a specified size
static func pad(data: Data, size: Int = 32, isRight: Bool = false) -> Data {
// Check if the size of bytes exceeds the specified size
if data.count > size {
return data.suffix(size)
}
// Create a Data object for padded bytes
var paddedData = Data(repeating: 0, count: size)
for i in 0..<size {
let padEnd = isRight
if padEnd {
paddedData[i] = i < data.count ? data[i] : 0
} else {
paddedData[size - i - 1] = i < data.count ? data[data.count - i - 1] : 0
}
}
return paddedData
}
static func isValidSignature(
transport: Transport,
digest: String,
signature: String,
walletAddress: String
) async -> Bool {
let functionName = "isValidSignature"
let input1 = InOut(name: "digest", type: .bytes(length: 32))
let input2 = InOut(name: "signature", type: .dynamicBytes)
let output = InOut(name: "magicValue", type: .bytes(length: 4))
let function = ABI.Element.Function(name: functionName,
inputs: [input1, input2],
outputs: [output],
constant: true,
payable: false)
let params: [Any] = [digest, signature]
guard let data = function.encodeParameters(params) else {
logger.utils.notice("isValidSignature function encodeParameters failure")
return false
}
guard let address = EthereumAddress(walletAddress) else {
logger.utils.notice("Invalid walletAddress (\(walletAddress))")
return false
}
let transaction = CodableTransaction(to: address, data: data)
guard let callResult = try? await Utils().ethCall(transport: transport,
transaction: transaction) else {
logger.utils.notice("Failed to execute eth_call request for isValidSignature")
return false
}
guard let callResultData = HexUtils.hexToData(hex: callResult),
let decoded = try? function.decodeReturnData(callResultData) else {
logger.utils.notice("isValidSignature function decodeReturnData failure")
return false
}
guard let magicValue = decoded["0"] as? Data else {
logger.utils.notice("The data type returned by eth_call request is incorrect")
return false
}
return EIP1271_VALID_SIGNATURE == magicValue.bytes
}
static func getReplaySafeMessageHash(
transport: Transport,
account: String,
hash: String
) async throws -> String {
guard let hashData = HexUtils.hexToData(hex: hash) else {
logger.utils.notice("Invalid hash: \(hash)")
throw BaseError(shortMessage: "Invalid hash: \(hash)")
}
let functionName = "getReplaySafeMessageHash"
let input1 = InOut(name: "address", type: .address)
let input2 = InOut(name: "hash", type: .bytes(length: 32))
let output = InOut(name: "", type: .bytes(length: 32))
let function = ABI.Element.Function(name: functionName,
inputs: [input1, input2],
outputs: [output],
constant: true,
payable: false)
guard let toAddress = EthereumAddress(account) else {
logger.utils.notice("Invalid address: \(account)")
throw BaseError(shortMessage: "Invalid address: \(account)")
}
let params: [Any] = [account, hashData]
guard let data = function.encodeParameters(params) else {
logger.utils.notice("getReplaySafeMessageHash function encodeParameters failure (\(params))")
throw BaseError(shortMessage: "getReplaySafeMessageHash function encodeParameters failure (\(params))")
}
let transaction = CodableTransaction(to: toAddress, data: data)
guard let callResult = try? await Utils().ethCall(transport: transport,
transaction: transaction) else {
logger.utils.notice("Failed to execute eth_call request for getReplaySafeMessageHash")
throw BaseError(shortMessage: "Failed to execute eth_call request for getReplaySafeMessageHash")
}
guard let callResultData = HexUtils.hexToData(hex: callResult),
let decoded = try? function.decodeReturnData(callResultData) else {
logger.utils.notice("getReplaySafeMessageHash function decodeReturnData failure")
throw BaseError(shortMessage: "getReplaySafeMessageHash function decodeReturnData failure")
}
guard let result = decoded["0"] as? Data else {
logger.utils.notice("The data type returned by eth_call request is incorrect")
throw BaseError(shortMessage: "The data type returned by eth_call request is incorrect")
}
return HexUtils.dataToHex(result)
}
static func getDefaultWalletName(prefix: String) -> String {
return "\(prefix)-\(getCurrentDateTime())"
}
static func getCurrentDateTime() -> String {
let dateFormatter = ISO8601DateFormatter()
dateFormatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
let currentDate = Date()
return dateFormatter.string(from: currentDate)
}
/// Checks if an address is an owner of a specified account.
///
/// - Parameters:
/// - transport: The transport layer for making RPC calls
/// - account: The account address to check
/// - ownerToCheck: The potential owner address to verify
///
/// - Returns: Boolean indicating whether ownerToCheck is an owner of the account
static func isOwnerOf(
transport: Transport,
account: String,
ownerToCheck: String
) async throws -> Bool {
let functionName = "isOwnerOf"
let input1 = InOut(name: "account", type: .address)
let input2 = InOut(name: "ownerToCheck", type: .address)
let output = InOut(name: "", type: .bool)
let function = ABI.Element.Function(name: functionName,
inputs: [input1, input2],
outputs: [output],
constant: true,
payable: false)
guard let toAddress = EthereumAddress(CIRCLE_WEIGHTED_WEB_AUTHN_MULTISIG_PLUGIN) else {
logger.utils.notice("Invalid address: \(CIRCLE_WEIGHTED_WEB_AUTHN_MULTISIG_PLUGIN)")
throw BaseError(shortMessage: "Invalid address: \(CIRCLE_WEIGHTED_WEB_AUTHN_MULTISIG_PLUGIN)")
}
let params: [Any] = [account, ownerToCheck]
guard let data = function.encodeParameters(params) else {
logger.utils.notice("isOwnerOf function encodeParameters failure (\(params))")
throw BaseError(shortMessage: "isOwnerOf function encodeParameters failure (\(params))")
}
var transaction = CodableTransaction(to: toAddress, data: data)