-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathThresholdKey.swift
1116 lines (1017 loc) · 47 KB
/
ThresholdKey.swift
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
import Foundation
#if canImport(lib)
import lib
#endif
import FetchNodeDetails
import TorusUtils
public class ThresholdKey {
private(set) var pointer: OpaquePointer?
private(set) var use_tss: Bool = false
internal let curveN = "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"
internal let tkeyQueue = DispatchQueue(label: "thresholdkey.queue")
/// Instantiate a `ThresholdKey` object,
///
/// - Parameters:
/// - metadata: Existing metadata to be used, optional.
/// - shares: Existing shares to be used, optional.
/// - storage_layer: Storage layer to be used.
/// - service_provider: Service provider to be used, optional only in the most basic usage of tKey.
/// - local_matadata_transitions: Existing local transitions to be used.
/// - last_fetch_cloud_metadata: Existing cloud metadata to be used.
/// - enable_logging: Determines whether logging is available or not (pending).
/// - manual_sync: Determines if changes to the metadata are automatically synced.
/// - rss_comm: RSS client, required for TSS.
///
/// - Returns: `ThresholdKey`
///
/// - Throws: `RuntimeError`, indicates invalid parameters.
public init(metadata: Metadata? = nil, shares: ShareStorePolyIdIndexMap? = nil, storage_layer: StorageLayer, service_provider: ServiceProvider? = nil, local_matadata_transitions: LocalMetadataTransitions? = nil, last_fetch_cloud_metadata: Metadata? = nil, enable_logging: Bool, manual_sync: Bool, rss_comm: RssComm? = nil) throws {
var errorCode: Int32 = -1
var providerPointer: OpaquePointer?
if case let .some(provider) = service_provider {
providerPointer = provider.pointer
}
var sharesPointer: OpaquePointer?
var metadataPointer: OpaquePointer?
var cloudMetadataPointer: OpaquePointer?
var transitionsPointer: OpaquePointer?
var rssCommPtr: OpaquePointer?
if shares != nil {
sharesPointer = shares!.pointer
}
if metadata != nil {
metadataPointer = metadata!.pointer
}
if last_fetch_cloud_metadata != nil {
cloudMetadataPointer = last_fetch_cloud_metadata!.pointer
}
if local_matadata_transitions != nil {
transitionsPointer = local_matadata_transitions!.pointer
}
if rss_comm != nil {
rssCommPtr = rss_comm!.pointer
use_tss = true
}
let result = withUnsafeMutablePointer(to: &errorCode, { error -> OpaquePointer in
threshold_key(metadataPointer, sharesPointer, storage_layer.pointer, providerPointer, transitionsPointer, cloudMetadataPointer, enable_logging, manual_sync, rssCommPtr, error)
})
guard errorCode == 0 else {
throw RuntimeError("Error in ThresholdKey")
}
pointer = result
}
/// Returns the metadata,
///
/// - Returns: `Metadata`
///
/// - Throws: `RuntimeError`, indicates invalid underlying poiner.
public func get_metadata() throws -> Metadata {
var errorCode: Int32 = -1
let result = withUnsafeMutablePointer(to: &errorCode, { error in threshold_key_get_current_metadata(pointer, error) })
guard errorCode == 0 else {
throw RuntimeError("Error in ThresholdKey get_metadata")
}
return Metadata(pointer: result!)
}
private func initialize(import_metdata_key: String?, input: ShareStore?, never_initialize_new_key: Bool?, include_local_metadata_transitions: Bool?, completion: @escaping (Result<KeyDetails, Error>) -> Void) {
tkeyQueue.async {
do {
var errorCode: Int32 = -1
var keyPointer: UnsafeMutablePointer<Int8>?
var device_index: Int32 = 2
let useTss = false
if import_metdata_key != nil {
keyPointer = UnsafeMutablePointer<Int8>(mutating: NSString(string: import_metdata_key!).utf8String)
}
var storePtr: OpaquePointer?
if input != nil {
storePtr = input!.pointer
}
let neverInitializeNewKey = never_initialize_new_key ?? false
let includeLocalMetadataTransitions = include_local_metadata_transitions ?? false
let curvePointer = UnsafeMutablePointer<Int8>(mutating: NSString(string: self.curveN).utf8String)
let ptr = withUnsafeMutablePointer(to: &device_index, { tssDeviceIndexPointer in withUnsafeMutablePointer(to: &errorCode, { error in
threshold_key_initialize(self.pointer, keyPointer, storePtr, neverInitializeNewKey, includeLocalMetadataTransitions, false, curvePointer, useTss, nil, tssDeviceIndexPointer, nil, error) }) })
guard errorCode == 0 else {
throw RuntimeError("Error in ThresholdKey Initialize")
}
let result = try! KeyDetails(pointer: ptr!)
completion(.success(result))
} catch {
completion(.failure(error))
}
}
}
/// Initializes a `ThresholdKey` object.
///
/// - Parameters:
/// - import_metdata_key: Metadata key to be imported, optional.
/// - input: `ShareStore` to be used, optional.
/// - never_initialize_new_key: Do not initialize a new tKey if an existing one is found.
/// - include_local_matadata_transitions: Proritize existing metadata transitions over cloud fetched transitions.
///
/// - Returns: `KeyDetails`
///
/// - Throws: `RuntimeError`, indicates invalid parameters.
public func initialize(import_metdata_key: String? = nil, input: ShareStore? = nil, never_initialize_new_key: Bool? = nil, include_local_metadata_transitions: Bool? = nil ) async throws -> KeyDetails {
return try await withCheckedThrowingContinuation {
continuation in
self.initialize(import_metdata_key: import_metdata_key, input: input, never_initialize_new_key: never_initialize_new_key, include_local_metadata_transitions: include_local_metadata_transitions ) {
result in
switch result {
case let .success(result):
continuation.resume(returning: result)
case let .failure(error):
continuation.resume(throwing: error)
}
}
}
}
private func reconstruct(completion: @escaping (Result<KeyReconstructionDetails, Error>) -> Void) {
tkeyQueue.async {
do {
var errorCode: Int32 = -1
let curvePointer = UnsafeMutablePointer<Int8>(mutating: (self.curveN as NSString).utf8String)
let ptr = withUnsafeMutablePointer(to: &errorCode, { error in
threshold_key_reconstruct(self.pointer, curvePointer, error) })
guard errorCode == 0 else {
throw RuntimeError("Error in ThresholdKey Reconstruct")
}
let result = try! KeyReconstructionDetails(pointer: ptr!)
completion(.success(result))
} catch {
completion(.failure(error))
}
}
}
/// Reconstructs the private key, this assumes that the number of shares inserted into the `ThresholdKey` are equal or greater than the threshold.
///
/// - Returns: `KeyReconstructionDetails`
///
/// - Throws: `RuntimeError`.
public func reconstruct() async throws -> KeyReconstructionDetails {
return try await withCheckedThrowingContinuation {
continuation in
self.reconstruct {
result in
switch result {
case let .success(result):
continuation.resume(returning: result)
case let .failure(error):
continuation.resume(throwing: error)
}
}
}
}
/// Returns the latest polynomial.
///
/// - Returns: `Polynomial`
///
/// - Throws: `RuntimeError`, indicates invalid `ThresholdKey`.
public func reconstruct_latest_poly() throws -> Polynomial {
var errorCode: Int32 = -1
let curvePointer = UnsafeMutablePointer<Int8>(mutating: (curveN as NSString).utf8String)
let result = withUnsafeMutablePointer(to: &errorCode, { error in
threshold_key_reconstruct_latest_poly(pointer, curvePointer, error)
})
guard errorCode == 0 else {
throw RuntimeError("Error in ThresholdKey reconstruct_latest_poly")
}
return Polynomial(pointer: result!)
}
/// Returns share stores for the latest polynomial.
///
/// - Returns: `ShareStoreArray`
///
/// - Throws: `RuntimeError`, indicates invalid `ThresholdKey`.
public func get_all_share_stores_for_latest_polynomial() throws -> ShareStoreArray {
var errorCode: Int32 = -1
let curvePointer = UnsafeMutablePointer<Int8>(mutating: (curveN as NSString).utf8String)
let result = withUnsafeMutablePointer(to: &errorCode, { error in
threshold_key_get_all_share_stores_for_latest_polynomial(pointer, curvePointer, error)
})
guard errorCode == 0 else {
throw RuntimeError("Error in ThresholdKey get_all_share_stores_for_latest_polynomial")
}
return ShareStoreArray(pointer: result!)
}
private func generate_new_share(completion: @escaping (Result<GenerateShareStoreResult, Error>) -> Void) {
tkeyQueue.async {
do {
let useTss = false
var errorCode: Int32 = -1
let curvePointer = UnsafeMutablePointer<Int8>(mutating: (self.curveN as NSString).utf8String)
let ptr = withUnsafeMutablePointer(to: &errorCode, { error in
threshold_key_generate_share(self.pointer, curvePointer, useTss, nil, error)
})
guard errorCode == 0 else {
throw RuntimeError("Error in ThresholdKey generate_new_share")
}
let result = try GenerateShareStoreResult(pointer: ptr!)
completion(.success(result))
} catch {
completion(.failure(error))
}
}
}
/// Generates a new share.
///
/// - Returns: `GenerateShareStoreResult`
///
/// - Throws: `RuntimeError`, indicates invalid `ThresholdKey`.
public func generate_new_share() async throws -> GenerateShareStoreResult {
return try await withCheckedThrowingContinuation {
continuation in self.generate_new_share() {
result in
switch result {
case let .success(result):
continuation.resume(returning: result)
case let .failure(error):
continuation.resume(throwing: error)
}
}
}
}
private func delete_share(share_index: String, completion: @escaping (Result<Void, Error>) -> Void) {
tkeyQueue.async {
do {
var errorCode: Int32 = -1
let curvePointer = UnsafeMutablePointer<Int8>(mutating: (self.curveN as NSString).utf8String)
let shareIndexPointer = UnsafeMutablePointer<Int8>(mutating: (share_index as NSString).utf8String)
let useTss = false
withUnsafeMutablePointer(to: &errorCode, { error in
threshold_key_delete_share(self.pointer, shareIndexPointer, curvePointer, useTss, nil, error)
})
guard errorCode == 0 else {
throw RuntimeError("Error in Threshold while Deleting share")
}
completion(.success(()))
} catch {
completion(.failure(error))
}
}
}
/// Deletes a share at the specified index. Caution is advised to not try delete a share that would prevent the total number of shares being below the threshold.
/// - Parameters:
/// - share_index: Share index to be deleted.
/// - Throws: `RuntimeError`, indicates invalid share index or invalid `ThresholdKey`.
public func delete_share(share_index: String) async throws {
return try await withCheckedThrowingContinuation {
continuation in
self.delete_share(share_index: share_index) {
result in
switch result {
case let .success(result):
continuation.resume(returning: result)
case let .failure(error):
continuation.resume(throwing: error)
}
}
}
}
private func CRITICAL_delete_tkey(completion: @escaping (Result<Void, Error>) -> Void) {
tkeyQueue.async {
do {
var errorCode: Int32 = -1
let curvePointer = UnsafeMutablePointer<Int8>(mutating: (self.curveN as NSString).utf8String)
withUnsafeMutablePointer(to: &errorCode, { error in
threshold_key_delete_tkey(self.pointer, curvePointer, error)
})
guard errorCode == 0 else {
throw RuntimeError("Error in Threshold while Deleting tKey")
}
completion(.success(()))
} catch {
completion(.failure(error))
}
}
}
/// Permanently deletes a tKey, this process is irrecoverable.
///
/// - Throws: `RuntimeError`, indicates invalid `ThresholdKey`.
public func CRITICAL_delete_tkey() async throws {
return try await withCheckedThrowingContinuation {
continuation in
self.CRITICAL_delete_tkey {
result in
switch result {
case let .success(result):
continuation.resume(returning: result)
case let .failure(error):
continuation.resume(throwing: error)
}
}
}
}
/// Returns the key details, mainly used after reconstruction.
///
/// - Returns: `KeyDetails`
///
/// - Throws: `RuntimeError`, indicates invalid `ThresholdKey`.
public func get_key_details() throws -> KeyDetails {
var errorCode: Int32 = -1
let result = withUnsafeMutablePointer(to: &errorCode, { error in
threshold_key_get_key_details(pointer, error)
})
guard errorCode == 0 else {
throw RuntimeError("Error in Threshold while Getting Key Details")
}
return try! KeyDetails(pointer: result!)
}
/// Retrieves a specific share.
///
/// - Parameters:
/// - shareIndex: The index of the share to output.
/// - shareType: The format of the output, can be `"mnemonic"`, optional.
/// - Returns: `String`
///
/// - Throws: `RuntimeError`, indicates invalid parameters or invalid `ThresholdKey`.
public func output_share(shareIndex: String, shareType: String? = nil) throws -> String {
var errorCode: Int32 = -1
let curvePointer = UnsafeMutablePointer<Int8>(mutating: (curveN as NSString).utf8String)
let cShareIndex = UnsafeMutablePointer<Int8>(mutating: (shareIndex as NSString).utf8String)
var cShareType: UnsafeMutablePointer<Int8>?
if shareType != nil {
cShareType = UnsafeMutablePointer<Int8>(mutating: (shareType! as NSString).utf8String)
}
let result = withUnsafeMutablePointer(to: &errorCode, { error in
threshold_key_output_share(pointer, cShareIndex, cShareType, curvePointer, error)
})
guard errorCode == 0 else {
throw RuntimeError("Error in ThresholdKey output_share")
}
let string = String(cString: result!)
string_free(result)
return string
}
/// Converts a share to a `ShareStore`.
///
/// - Parameters:
/// - share: Hexadecimal representation of a share as `String`.
/// - Returns: `ShareStore`
///
/// - Throws: `RuntimeError`, indicates invalid parameter.
public func share_to_share_store(share: String) throws -> ShareStore {
var errorCode: Int32 = -1
let curvePointer = UnsafeMutablePointer<Int8>(mutating: (curveN as NSString).utf8String)
let sharePointer = UnsafeMutablePointer<Int8>(mutating: (share as NSString).utf8String)
let result = withUnsafeMutablePointer(to: &errorCode, { error in
threshold_key_share_to_share_store(pointer, sharePointer, curvePointer, error)
})
guard errorCode == 0 else {
throw RuntimeError("Error in ThresholdKey share_to_share_store")
}
return ShareStore(pointer: result!)
}
private func input_share(share: String, shareType: String?, completion: @escaping (Result<Void, Error>) -> Void) {
tkeyQueue.async {
do {
var errorCode: Int32 = -1
let curvePointer = UnsafeMutablePointer<Int8>(mutating: (self.curveN as NSString).utf8String)
let cShare = UnsafeMutablePointer<Int8>(mutating: (share as NSString).utf8String)
var cShareType: UnsafeMutablePointer<Int8>?
if shareType != nil {
cShareType = UnsafeMutablePointer<Int8>(mutating: (shareType! as NSString).utf8String)
}
withUnsafeMutablePointer(to: &errorCode, { error in
threshold_key_input_share(self.pointer, cShare, cShareType, curvePointer, error)
})
guard errorCode == 0 else {
throw RuntimeError("Error in ThresholdKey input share")
}
completion(.success(()))
} catch {
completion(.failure(error))
}
}
}
/// Inserts a share into `ThresholdKey`, this is used prior to reconstruction in order to ensure the number of shares meet the threshold.
///
/// - Parameters:
/// - share: Hex representation of a share as `String`.
/// - shareType: The format of the share, can be `"mnemonic"`, optional.
///
/// - Throws: `RuntimeError`, indicates invalid parameter of invalid `ThresholdKey`.
public func input_share(share: String, shareType: String?) async throws {
return try await withCheckedThrowingContinuation {
continuation in
self.input_share(share: share, shareType: shareType) {
result in
switch result {
case let .success(result):
continuation.resume(returning: result)
case let .failure(error):
continuation.resume(throwing: error)
}
}
}
}
/// Retrieves a specific `ShareStore`.
///
/// - Parameters:
/// - shareIndex: The index of the share to output.
/// - polyID: The polynomial id to be used for the output, optional
/// - Returns: `ShareStore`
///
/// - Throws: `RuntimeError`, indicates invalid parameters or invalid `ThresholdKey`.
public func output_share_store(shareIndex: String, polyId: String?) throws -> ShareStore {
var errorCode: Int32 = -1
let curvePointer = UnsafeMutablePointer<Int8>(mutating: (curveN as NSString).utf8String)
let cShareIndex = UnsafeMutablePointer<Int8>(mutating: (shareIndex as NSString).utf8String)
var cPolyId: UnsafeMutablePointer<Int8>?
if let polyId = polyId {
cPolyId = UnsafeMutablePointer<Int8>(mutating: (polyId as NSString).utf8String)
}
let result = withUnsafeMutablePointer(to: &errorCode, { error in
threshold_key_output_share_store(pointer, cShareIndex, cPolyId, curvePointer, error)
})
guard errorCode == 0 else {
throw RuntimeError("Error in ThresholdKey output share store")
}
return ShareStore(pointer: result!)
}
private func input_share_store(shareStore: ShareStore, completion: @escaping (Result<Void, Error>) -> Void) {
tkeyQueue.async {
do {
var errorCode: Int32 = -1
withUnsafeMutablePointer(to: &errorCode, { error in
threshold_key_input_share_store(self.pointer, shareStore.pointer, error)
})
guard errorCode == 0 else {
throw RuntimeError("Error in ThresholdKey input share store")
}
completion(.success(()))
} catch {
completion(.failure(error))
}
}
}
/// Inserts a `ShareStore` into `ThresholdKey`, useful for insertion before reconstruction to ensure the number of shares meet the minimum threshold.
///
/// - Parameters:
/// - shareStore: The `ShareStore` to be inserted
///
/// - Throws: `RuntimeError`, indicates invalid parameters or invalid `ThresholdKey`.
public func input_share_store(shareStore: ShareStore) async throws {
return try await withCheckedThrowingContinuation {
continuation in
self.input_share_store(shareStore: shareStore) {
result in
switch result {
case let .success(result):
continuation.resume(returning: result)
case let .failure(error):
continuation.resume(throwing: error)
}
}
}
}
private func input_factor_key(factorKey: String, completion: @escaping (Result<Void, Error>) -> Void) {
tkeyQueue.async {
do {
var errorCode: Int32 = -1
let cFactorKey = UnsafeMutablePointer<Int8>(mutating: (factorKey as NSString).utf8String)
withUnsafeMutablePointer(to: &errorCode, { error in
threshold_key_input_factor_key(self.pointer, cFactorKey, error)
})
guard errorCode == 0 else {
throw RuntimeError("Error in ThresholdKey input_factor_key")
}
completion(.success(()))
} catch {
completion(.failure(error))
}
}
}
/// Inserts a `ShareStore` into `ThresholdKey` using `FactorKey`, useful for insertion before reconstruction to ensure the number of shares meet the minimum threshold.
///
/// - Parameters:
/// - factorKey : The `factorKey` to be inserted
///
/// - Throws: `RuntimeError`, indicates invalid parameters or invalid `ThresholdKey`.
public func input_factor_key(factorKey: String) async throws {
return try await withCheckedThrowingContinuation {
continuation in
self.input_factor_key(factorKey: factorKey) {
result in
switch result {
case let .success(result):
continuation.resume(returning: result)
case let .failure(error):
continuation.resume(throwing: error)
}
}
}
}
/// Retrieves all share indexes for a `ThresholdKey`.
///
/// - Returns: Array of String
///
/// - Throws: `RuntimeError`, indicates invalid `ThresholdKey`.
public func get_shares_indexes() throws -> [String] {
var errorCode: Int32 = -1
let result = withUnsafeMutablePointer(to: &errorCode, { error in
threshold_key_get_shares_indexes(pointer, error)
})
guard errorCode == 0 else {
throw RuntimeError("Error in ThresholdKey get_share_indexes")
}
let string = String(cString: result!)
let indexes = try! JSONSerialization.jsonObject(with: string.data(using: String.Encoding.utf8)!, options: .allowFragments) as! [String]
string_free(result)
return indexes
}
/// Encrypts a message.
///
/// - Returns: `String`
///
/// - Throws: `RuntimeError`, indicates invalid parameters or invalid `ThresholdKey`.
public func encrypt(msg: String) throws -> String {
var errorCode: Int32 = -1
let curvePointer = UnsafeMutablePointer<Int8>(mutating: (curveN as NSString).utf8String)
let msgPointer = UnsafeMutablePointer<Int8>(mutating: (msg as NSString).utf8String)
let result = withUnsafeMutablePointer(to: &errorCode, { error in
threshold_key_encrypt(pointer, msgPointer, curvePointer, error)
})
guard errorCode == 0 else {
throw RuntimeError("Error in ThresholdKey encrypt")
}
let string = String(cString: result!)
string_free(result)
return string
}
/// Decrypts a message.
///
/// - Returns: `String`
///
/// - Throws: `RuntimeError`, indicates invalid parameters or invalid `ThresholdKey`.
public func decrypt(msg: String) throws -> String {
var errorCode: Int32 = -1
let msgPointer = UnsafeMutablePointer<Int8>(mutating: (msg as NSString).utf8String)
let result = withUnsafeMutablePointer(to: &errorCode, { error in
threshold_key_decrypt(pointer, msgPointer, error)
})
guard errorCode == 0 else {
throw RuntimeError("Error in ThresholdKey decrypt")
}
let string = String(cString: result!)
string_free(result)
return string
}
/// Returns last metadata fetched from the cloud.
///
/// - Returns: `Metadata`
///
/// - Throws: `RuntimeError`, indicates invalid parameters or invalid `ThresholdKey`.
public func get_last_fetched_cloud_metadata() throws -> Metadata {
var errorCode: Int32 = -1
let result = withUnsafeMutablePointer(to: &errorCode, { error in threshold_key_get_last_fetched_cloud_metadata(pointer, error) })
guard errorCode == 0 else {
throw RuntimeError("Error in ThresholdKey get_last_fetched_cloud_metadata")
}
return Metadata(pointer: result)
}
/// Returns current metadata transitions not yet synchronised.
///
/// - Returns: `LocalMetadataTransitions`
///
/// - Throws: `RuntimeError`, indicates invalid parameters or invalid `ThresholdKey`.
public func get_local_metadata_transitions() throws -> LocalMetadataTransitions {
var errorCode: Int32 = -1
let result = withUnsafeMutablePointer(to: &errorCode, { error in threshold_key_get_local_metadata_transitions(pointer, error) })
guard errorCode == 0 else {
throw RuntimeError("Error in ThresholdKey get_local_metadata_transitions")
}
return LocalMetadataTransitions(pointer: result!)
}
/// Returns add metadata transitions , need sync localmetadata transistion to update server data
///
/// - Parameters:
/// - input_json: input in json string
/// - private_key: private key used to encrypt and store.
///
/// - Throws: `RuntimeError`, indicates invalid parameters or invalid `ThresholdKey`.
public func add_local_metadata_transitions( input_json: String, private_key: String ) throws {
var errorCode: Int32 = -1
let curve = UnsafeMutablePointer<Int8>(mutating: (curveN as NSString).utf8String)
let input = UnsafeMutablePointer<Int8>(mutating: (input_json as NSString).utf8String)
let privateKey = UnsafeMutablePointer<Int8>(mutating: (private_key as NSString).utf8String)
withUnsafeMutablePointer(to: &errorCode, { error in threshold_key_add_local_metadata_transitions(pointer, input, privateKey, curve, error)})
guard errorCode == 0 else {
throw RuntimeError("Error in ThresholdKey add_local_metadata_transitions")
}
}
/// Returns the tKey store for a module.
///
/// - Parameters:
/// - moduleName: Specific name of the module.
///
/// - Returns: Array of objects.
///
/// - Throws: `RuntimeError`, indicates invalid parameters or invalid `ThresholdKey`.
public func get_tkey_store(moduleName: String) throws -> [[String: Any]] {
var errorCode: Int32 = -1
let modulePointer = UnsafeMutablePointer<Int8>(mutating: (moduleName as NSString).utf8String)
let result = withUnsafeMutablePointer(to: &errorCode, { error in
threshold_key_get_tkey_store(pointer, modulePointer, error)
})
guard errorCode == 0 else {
throw RuntimeError("Error in ThresholdKey get_tkey_store")
}
let string = String(cString: result!)
string_free(result)
let jsonArray = try! JSONSerialization.jsonObject(with: string.data(using: .utf8)!, options: .allowFragments) as! [[String: Any]]
return jsonArray
}
/// Returns the specific tKey store item json for a module.
///
/// - Parameters:
/// - moduleName: Specific name of the module.
/// - id: Identifier of the item.
///
/// - Returns: `String`
///
/// - Throws: `RuntimeError`, indicates invalid parameters or invalid `ThresholdKey`.
public func get_tkey_store_item(moduleName: String, id: String) throws -> [String: Any] {
var errorCode: Int32 = -1
let modulePointer = UnsafeMutablePointer<Int8>(mutating: (moduleName as NSString).utf8String)
let idPointer = UnsafeMutablePointer<Int8>(mutating: (id as NSString).utf8String)
let result = withUnsafeMutablePointer(to: &errorCode, { error in
threshold_key_get_tkey_store_item(pointer, modulePointer, idPointer, error)
})
guard errorCode == 0 else {
throw RuntimeError("Error in ThresholdKey get_tkey_store_item")
}
let string = String(cString: result!)
string_free(result)
let json = try! JSONSerialization.jsonObject(with: string.data(using: .utf8)!, options: .allowFragments) as! [String: Any]
return json
}
/// Returns all shares according to their mapping.
///
/// - Returns: `ShareStorePolyIdIndexMap`
///
/// - Throws: `RuntimeError`, indicates invalid parameters or invalid `ThresholdKey`.
public func get_shares() throws -> ShareStorePolyIdIndexMap {
var errorCode: Int32 = -1
let result = withUnsafeMutablePointer(to: &errorCode, { error in
threshold_key_get_shares(pointer, error)
})
guard errorCode == 0 else {
throw RuntimeError("Error in ThresholdKey get_shares")
}
return try ShareStorePolyIdIndexMap(pointer: result!)
}
private func sync_local_metadata_transistions(completion: @escaping (Result<Void, Error>) -> Void) {
tkeyQueue.async {
do {
var errorCode: Int32 = -1
let curvePointer = UnsafeMutablePointer<Int8>(mutating: NSString(string: self.curveN).utf8String)
withUnsafeMutablePointer(to: &errorCode, { error in
threshold_key_sync_local_metadata_transitions(self.pointer, curvePointer, error)
})
guard errorCode == 0 else {
throw RuntimeError("Error in ThresholdKey sync_local_metadata_transistions")
}
completion(.success(()))
} catch {
completion(.failure(error))
}
}
}
/// Syncronises metadata transitions, only used if manual sync is enabled.
///
/// - Throws: `RuntimeError`, indicates invalid parameters or invalid `ThresholdKey`.
public func sync_local_metadata_transistions() async throws {
return try await withCheckedThrowingContinuation {
continuation in
self.sync_local_metadata_transistions {
result in
switch result {
case let .success(result):
continuation.resume(returning: result)
case let .failure(error):
continuation.resume(throwing: error)
}
}
}
}
/// Returns all shares descriptions.
///
/// - Returns: Array of objects.
///
/// - Throws: `RuntimeError`, indicates invalid parameters or invalid `ThresholdKey`.
public func get_share_descriptions() throws -> [String: [String]] {
var errorCode: Int32 = -1
let result = withUnsafeMutablePointer(to: &errorCode, { error in
threshold_key_get_share_descriptions(pointer, error)
})
guard errorCode == 0 else {
throw RuntimeError("Error in ThresholdKey get_share_descriptions")
}
let string = String(cString: result!)
string_free(result)
let json = try! JSONSerialization.jsonObject(with: string.data(using: .utf8)!, options: .allowFragments) as! [String: [String]]
return json
}
private func add_share_description(key: String, description: String, update_metadata: Bool, completion: @escaping (Result<Void, Error>) -> Void) {
tkeyQueue.async {
do {
var errorCode: Int32 = -1
let curvePointer = UnsafeMutablePointer<Int8>(mutating: (self.curveN as NSString).utf8String)
let keyPointer = UnsafeMutablePointer<Int8>(mutating: (key as NSString).utf8String)
let descriptionPointer = UnsafeMutablePointer<Int8>(mutating: (description as NSString).utf8String)
withUnsafeMutablePointer(to: &errorCode, { error in
threshold_key_add_share_description(self.pointer, keyPointer, descriptionPointer, update_metadata, curvePointer, error) })
guard errorCode == 0 else {
throw RuntimeError("Error in ThresholdKey add_share_description")
}
completion(.success(()))
} catch {
completion(.failure(error))
}
}
}
/// Adds a share description.
///
/// - Parameters:
/// - key: The key, usually the share index.
/// - description: Description for the key.
/// - update_metadata: Whether the metadata is synced immediately or not.
///
/// - Throws: `RuntimeError`, indicates invalid parameters or invalid `ThresholdKey`.
public func add_share_description(key: String, description: String, update_metadata: Bool = true) async throws {
return try await withCheckedThrowingContinuation {
continuation in
self.add_share_description(key: key, description: description, update_metadata: update_metadata) {
result in
switch result {
case let .success(result):
continuation.resume(returning: result)
case let .failure(error):
continuation.resume(throwing: error)
}
}
}
}
private func update_share_description(key: String, oldDescription: String, newDescription: String, update_metadata: Bool, completion: @escaping (Result<Void, Error>) -> Void) {
tkeyQueue.async {
do {
var errorCode: Int32 = -1
let curvePointer = UnsafeMutablePointer<Int8>(mutating: (self.curveN as NSString).utf8String)
let keyPointer = UnsafeMutablePointer<Int8>(mutating: (key as NSString).utf8String)
let oldDescriptionPointer = UnsafeMutablePointer<Int8>(mutating: (oldDescription as NSString).utf8String)
let newDescriptionPointer = UnsafeMutablePointer<Int8>(mutating: (newDescription as NSString).utf8String)
withUnsafeMutablePointer(to: &errorCode, { error in
threshold_key_update_share_description(self.pointer, keyPointer, oldDescriptionPointer, newDescriptionPointer, update_metadata, curvePointer, error) })
guard errorCode == 0 else {
throw RuntimeError("Error in ThresholdKey update_share_description")
}
completion(.success(()))
} catch {
completion(.failure(error))
}
}
}
/// Updates a share description.
///
/// - Parameters:
/// - key: The relevant key.
/// - oldDescription: Old description used for the key
/// - newDescription: New description for the key.
/// - update_metadata: Whether the metadata is synced immediately or not.
///
/// - Throws: `RuntimeError`, indicates invalid parameters or invalid `ThresholdKey`.
public func update_share_description(key: String, oldDescription: String, newDescription: String, update_metadata: Bool = true) async throws {
return try await withCheckedThrowingContinuation {
continuation in
self.update_share_description(key: key, oldDescription: oldDescription, newDescription: newDescription, update_metadata: update_metadata) {
result in
switch result {
case let .success(result):
continuation.resume(returning: result)
case let .failure(error):
continuation.resume(throwing: error)
}
}
}
}
private func delete_share_description(key: String, description: String, update_metadata: Bool, completion: @escaping (Result<Void, Error>) -> Void) {
tkeyQueue.async {
do {
var errorCode: Int32 = -1
let curvePointer = UnsafeMutablePointer<Int8>(mutating: (self.curveN as NSString).utf8String)
let keyPointer = UnsafeMutablePointer<Int8>(mutating: (key as NSString).utf8String)
let descriptionPointer = UnsafeMutablePointer<Int8>(mutating: (description as NSString).utf8String)
withUnsafeMutablePointer(to: &errorCode, { error in
threshold_key_delete_share_description(self.pointer, keyPointer, descriptionPointer, update_metadata, curvePointer, error) })
guard errorCode == 0 else {
throw RuntimeError("Error in ThresholdKey delete_share_description")
}
completion(.success(()))
} catch {
completion(.failure(error))
}
}
}
/// Deletes a share description.
///
/// - Parameters:
/// - key: The relevant key.
/// - description: Current description for the key.
/// - update_metadata: Whether the metadata is synced immediately or not.
///
/// - Throws: `RuntimeError`, indicates invalid parameters or invalid `ThresholdKey`.
public func delete_share_description(key: String, description: String, update_metadata: Bool = true) async throws {
return try await withCheckedThrowingContinuation {
continuation in
self.delete_share_description(key: key, description: description, update_metadata: update_metadata) {
result in
switch result {
case let .success(result):
continuation.resume(returning: result)
case let .failure(error):
continuation.resume(throwing: error)
}
}
}
}
private func storage_layer_get_metadata(private_key: String?, completion: @escaping (Result<String, Error>) -> Void) {
tkeyQueue.async {
do {
var errorCode: Int32 = -1
var privateKeyPointer: UnsafeMutablePointer<Int8>?
if private_key != nil {
privateKeyPointer = UnsafeMutablePointer<Int8>(mutating: NSString(string: private_key!).utf8String)
}
let ptr = withUnsafeMutablePointer(to: &errorCode, { error in threshold_key_get_metadata(self.pointer, privateKeyPointer, error) })
guard errorCode == 0 else {
throw RuntimeError("Error in ThresholdKey get_metadata")
}
let string = String(cString: ptr!)
string_free(ptr)
completion(.success(string))
} catch {
completion(.failure(error))
}
}
}
/// Function to retrieve the metadata directly from the network, only used in very specific instances.
///
/// - Parameters:
/// - private_key: The reconstructed key, optional.
///
/// - Throws: `RuntimeError`, indicates invalid parameters or invalid `ThresholdKey`.
public func storage_layer_get_metadata(private_key: String?) async throws -> String {
return try await withCheckedThrowingContinuation {
continuation in
self.storage_layer_get_metadata(private_key: private_key) {
result in
switch result {
case let .success(result):
continuation.resume(returning: result)
case let .failure(error):
continuation.resume(throwing: error)
}
}
}
}
private func storage_layer_set_metadata(private_key: String?, json: String, completion: @escaping (Result<Void, Error>) -> Void) {
tkeyQueue.async {
do {
var errorCode: Int32 = -1
var privateKeyPointer: UnsafeMutablePointer<Int8>?
if private_key != nil {
privateKeyPointer = UnsafeMutablePointer<Int8>(mutating: NSString(string: private_key!).utf8String)
}
let curvePointer = UnsafeMutablePointer<Int8>(mutating: (self.curveN as NSString).utf8String)
let valuePointer = UnsafeMutablePointer<Int8>(mutating: (json as NSString).utf8String)
withUnsafeMutablePointer(to: &errorCode, { error in threshold_key_set_metadata(self.pointer, privateKeyPointer, valuePointer, curvePointer, error) })
guard errorCode == 0 else {
throw RuntimeError("Error in ThresholdKey set_metadata")
}
completion(.success(()))
} catch {
completion(.failure(error))
}
}
}
/// Function to set the metadata directly to the network, only used for specific instances.
///
/// - Parameters:
/// - private_key: The reconstructed key.
/// - json: Relevant json to be set
///
/// - Throws: `RuntimeError`, indicates invalid parameters or invalid `ThresholdKey`.
public func storage_layer_set_metadata(private_key: String?, json: String) async throws {
return try await withCheckedThrowingContinuation {
continuation in
self.storage_layer_set_metadata(private_key: private_key, json: json) {
result in
switch result {