-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathAccount.fs
810 lines (702 loc) · 38 KB
/
Account.fs
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
namespace GWallet.Backend
open System
open System.Linq
open System.IO
open System.Threading.Tasks
open GWallet.Backend.FSharpUtil.UwpHacks
// this exception, if it happens, it would cause a crash because we don't handle it yet
type UnhandledCurrencyServerException(currency: Currency,
innerException: Exception) =
inherit Exception (SPrintF2 "Issue when retrieving %A currency balance: %s"
currency
innerException.Message,
innerException)
module Account =
let private isInitialized (accounts: seq<IAccount>) = lazy(
Config.Init()
#if !NATIVE_SEGWIT
let _readonlyUtxoAccounts =
#else
let readonlyUtxoAccounts =
#endif
accounts.Where(fun acc -> acc.Currency.IsUtxo()).OfType<ReadOnlyAccount>()
#if NATIVE_SEGWIT
UtxoCoin.Account.MigrateReadOnlyAccountsToNativeSegWit readonlyUtxoAccounts
#endif
()
)
let private GetShowableBalanceAndImminentPaymentInternal (account: IAccount)
(mode: ServerSelectionMode)
(cancelSourceOption: Option<CustomCancelSource>)
: Async<Option<decimal*Option<bool>>> =
match account with
| :? UtxoCoin.IUtxoAccount as utxoAccount ->
if not (account.Currency.IsUtxo()) then
failwith <| SPrintF1 "Currency %A not Utxo-type but account is? report this bug (balance)"
account.Currency
UtxoCoin.Account.GetShowableBalanceAndImminentIncomingPayment utxoAccount mode cancelSourceOption
| _ ->
if not (account.Currency.IsEtherBased()) then
failwith <| SPrintF1 "Currency %A not ether based and not UTXO either? not supported, report this bug (balance)"
account.Currency
Ether.Account.GetShowableBalanceAndImminentIncomingPayment account mode cancelSourceOption
let GetShowableBalanceAndImminentIncomingPayment (account: IAccount)
(mode: ServerSelectionMode)
(cancelSourceOption: Option<CustomCancelSource>)
: Async<MaybeCached<decimal>*Option<bool>> =
async {
if Config.NoNetworkBalanceForDebuggingPurposes then
return Fresh 1m,Some false
else
try
let! maybeBalanceAndImminentIncomingPayment =
GetShowableBalanceAndImminentPaymentInternal account mode cancelSourceOption
match maybeBalanceAndImminentIncomingPayment with
| None ->
let cachedBalance = Caching.Instance.RetrieveLastCompoundBalance account.PublicAddress account.Currency
return (NotFresh cachedBalance, None)
| Some (balance,imminentIncomingPayment) ->
if account.Currency = Currency.SAI && balance > 0m then
Infrastructure.ReportWarningMessage ("Some user is still using SAI (informative telemetry to avoid phasing out this currency too early)")
|> ignore<bool>
let compoundBalance,_ =
Caching.Instance.RetrieveAndUpdateLastCompoundBalance account.PublicAddress
account.Currency
balance
return (Fresh compoundBalance, imminentIncomingPayment)
with
| ex ->
return raise <| UnhandledCurrencyServerException(account.Currency, ex)
}
let mutable wiped = false
let private WipeConfig () =
#if DEBUG
if not wiped then
Config.Wipe ()
wiped <- true
#else
()
#endif
let internal GetAccountFromFile accountFile (currency: Currency) kind: IAccount =
if currency.IsUtxo() then
UtxoCoin.Account.GetAccountFromFile accountFile currency kind
elif currency.IsEtherBased() then
Ether.Account.GetAccountFromFile accountFile currency kind
else
failwith <| SPrintF1 "Currency (%A) not supported for this API" currency
let GetAllActiveAccounts(): seq<IAccount> =
let allCurrencies = Currency.GetAll()
// uncomment this block below, manually, if when testing you need to go back to test the WelcomePage.xaml
#if FALSE
WipeConfig ()
Caching.Instance.ClearAll()
failwith "OK, all accounts and cache is clear, you can disable this code block again"
#endif
let getAccountsOfKind (kinds: seq<AccountKind>) =
seq {
for currency in allCurrencies do
for kind in kinds do
for accountFile in Config.GetAccountFilesWithCurrency currency kind do
yield GetAccountFromFile accountFile currency kind
}
let allAccounts = getAccountsOfKind [AccountKind.Normal; AccountKind.ReadOnly]
let _checkInit: unit =
(isInitialized allAccounts).Value
allAccounts
let GetNormalAccountsPairingInfoForWatchWallet(): Option<WatchWalletInfo> =
let allCurrencies = Currency.GetAll()
let utxoCurrencyAccountFiles =
Config.GetAccountFiles (allCurrencies.Where(fun currency -> currency.IsUtxo())) AccountKind.Normal
let etherCurrencyAccountFiles =
Config.GetAccountFiles (allCurrencies.Where(fun currency -> currency.IsEtherBased())) AccountKind.Normal
if (not (utxoCurrencyAccountFiles.Any())) || (not (etherCurrencyAccountFiles.Any())) then
None
else
let firstUtxoAccountFile = utxoCurrencyAccountFiles.First()
let utxoCoinPublicKey = UtxoCoin.Account.GetPublicKeyFromNormalAccountFile firstUtxoAccountFile
let firstEtherAccountFile = etherCurrencyAccountFiles.First()
let etherPublicAddress = Ether.Account.GetPublicAddressFromNormalAccountFile firstEtherAccountFile
Some {
UtxoCoinPublicKey = utxoCoinPublicKey.ToString()
EtherPublicAddress = etherPublicAddress
}
let GetArchivedAccountsWithPositiveBalance (cancelSourceOption: Option<CustomCancelSource>)
: Async<seq<ArchivedAccount*decimal>> =
let asyncJobs = seq<Async<ArchivedAccount*Option<decimal>>> {
let allCurrencies = Currency.GetAll()
for currency in allCurrencies do
let fromUnencryptedPrivateKeyToPublicAddressFunc =
if currency.IsUtxo() then
UtxoCoin.Account.GetPublicAddressFromUnencryptedPrivateKey currency
elif currency.IsEtherBased() then
Ether.Account.GetPublicAddressFromUnencryptedPrivateKey
else
failwith <| SPrintF1 "Unknown currency %A" currency
let fromConfigAccountFileToPublicAddressFunc (accountConfigFile: FileRepresentation) =
let privateKeyFromConfigFile = accountConfigFile.Content()
fromUnencryptedPrivateKeyToPublicAddressFunc privateKeyFromConfigFile
for accountFile in Config.GetAccountFiles [currency] AccountKind.Archived do
let account = ArchivedAccount(currency, accountFile, fromConfigAccountFileToPublicAddressFunc)
let maybeBalanceJob = GetShowableBalanceAndImminentPaymentInternal account ServerSelectionMode.Fast
yield async {
let! maybeBalance = maybeBalanceJob cancelSourceOption
let positiveBalance =
match maybeBalance with
| Some (balance,_) ->
if (balance > 0m) then
Some(balance)
else
None
| _ ->
None
return account,positiveBalance
}
}
let executedBalances = Async.Parallel asyncJobs
async {
let! accountAndPositiveBalances = executedBalances
return seq {
for account,maybePositiveBalance in accountAndPositiveBalances do
match maybePositiveBalance with
| Some positiveBalance -> yield account,positiveBalance
| _ -> ()
}
}
// TODO: add tests for these (just in case address validation breaks after upgrading our dependencies)
let ValidateAddress (currency: Currency) (address: string): Async<unit> = async {
if currency.IsEtherBased() then
do! Ether.Account.ValidateAddress currency address
elif currency.IsUtxo() then
UtxoCoin.Account.ValidateAddress currency address
else
failwith <| SPrintF1 "Unknown currency %A" currency
}
let ValidateUnknownCurrencyAddress (address: string): Async<List<Currency>> = async {
if address.StartsWith "0x" then
let someEtherCurrency = Currency.ETC
do! Ether.Account.ValidateAddress someEtherCurrency address
let allEtherCurrencies = [ Currency.ETC; Currency.ETH; Currency.DAI ]
return allEtherCurrencies
elif (address.StartsWith "L" || address.StartsWith "M") then
let ltc = Currency.LTC
UtxoCoin.Account.ValidateAddress ltc address
return [ ltc ]
else
let btc = Currency.BTC
UtxoCoin.Account.ValidateAddress btc address
return [ btc ]
}
let EstimateFee (account: IAccount) (amount: TransferAmount) destination: Async<IBlockchainFeeInfo> =
async {
match account with
| :? UtxoCoin.IUtxoAccount as utxoAccount ->
if not (account.Currency.IsUtxo()) then
failwith <| SPrintF1 "Currency %A not Utxo-type but account is? report this bug (estimatefee)"
account.Currency
let! fee = UtxoCoin.Account.EstimateFee utxoAccount amount destination
return fee :> IBlockchainFeeInfo
| _ ->
if not (account.Currency.IsEtherBased()) then
failwith <| SPrintF1 "Currency %A not ether based and not UTXO either? not supported, report this bug (estimatefee)"
account.Currency
let! fee = Ether.Account.EstimateFee account amount destination
return fee :> IBlockchainFeeInfo
}
let private SaveOutgoingTransactionInCache transactionProposal (fee: IBlockchainFeeInfo) txId =
let amountTransferredPlusFeeIfCurrencyFeeMatches =
if transactionProposal.Amount.BalanceAtTheMomentOfSending = transactionProposal.Amount.ValueToSend
|| transactionProposal.Amount.Currency <> fee.Currency then
transactionProposal.Amount.ValueToSend
else
transactionProposal.Amount.ValueToSend + fee.FeeValue
Caching.Instance.StoreOutgoingTransaction
transactionProposal.OriginMainAddress
transactionProposal.Amount.Currency
fee.Currency
txId
amountTransferredPlusFeeIfCurrencyFeeMatches
fee.FeeValue
// FIXME: if out of gas, miner fee is still spent, we should inspect GasUsed and use it for the call to
// SaveOutgoingTransactionInCache
let private CheckIfOutOfGas (transactionMetadata: IBlockchainFeeInfo) (txHash: string)
: Async<unit> =
async {
match transactionMetadata with
| :? Ether.TransactionMetadata as etherTxMetadata ->
try
let! outOfGas = Ether.Server.IsOutOfGas transactionMetadata.Currency txHash etherTxMetadata.Fee.GasLimit
if outOfGas then
return failwith <| SPrintF1 "Transaction ran out of gas: %s" txHash
with
| ex ->
return raise <| Exception(SPrintF1 "An issue occurred while trying to check if the following transaction ran out of gas: %s" txHash, ex)
| _ ->
()
}
// FIXME: broadcasting shouldn't just get N consistent replies from FaultTolerantClient,
// but send it to as many as possible, otherwise it could happen that some server doesn't
// broadcast it even if you sent it
let BroadcastTransaction (trans: SignedTransaction<_>) (ignoreHigherMinerFeeThanAmount: bool): Async<Uri> =
async {
let currency = trans.TransactionInfo.Proposal.Amount.Currency
let! txId =
if currency.IsEtherBased() then
Ether.Account.BroadcastTransaction trans ignoreHigherMinerFeeThanAmount
elif currency.IsUtxo() then
UtxoCoin.Account.BroadcastTransaction currency trans ignoreHigherMinerFeeThanAmount
else
failwith <| SPrintF1 "Unknown currency %A" currency
do! CheckIfOutOfGas trans.TransactionInfo.Metadata txId
SaveOutgoingTransactionInCache trans.TransactionInfo.Proposal trans.TransactionInfo.Metadata txId
let uri = BlockExplorer.GetTransaction currency txId
return uri
}
let SignTransaction (account: NormalAccount)
(destination: string)
(amount: TransferAmount)
(transactionMetadata: IBlockchainFeeInfo)
(password: string) =
match transactionMetadata with
| :? Ether.TransactionMetadata as etherTxMetadata ->
Ether.Account.SignTransaction
account
etherTxMetadata
destination
amount
password
| :? UtxoCoin.TransactionMetadata as btcTxMetadata ->
match account with
| :? UtxoCoin.NormalUtxoAccount as utxoAccount ->
UtxoCoin.Account.SignTransaction
utxoAccount
btcTxMetadata
destination
amount
password
| _ ->
failwith "An UtxoCoin.TransactionMetadata should come with a UtxoCoin.Account"
| _ -> failwith "fee type unknown"
let CheckValidPassword (password: string) (accountOpt: Option<NormalAccount>) =
let checkValidPasswordForSingleAccount account: bool =
if (account :> IAccount).Currency.IsEtherBased() then
try
Ether.Account.CheckValidPassword account password
true
with
| :? InvalidPassword ->
false
else
try
UtxoCoin.Account.CheckValidPassword account password
true
with
| :? InvalidPassword ->
false
let account =
match accountOpt with
| Some account -> account
| _ ->
// Because password check is expensive operation, only check it for one account.
// (Ether accounts take about 2 times longer to check, so rather use BTC/LTC)
let maybeBtcAccount =
GetAllActiveAccounts().OfType<NormalAccount>()
|> Seq.tryFind (fun acc -> (acc :> IAccount).Currency = Currency.BTC)
match maybeBtcAccount with
| Some btcAccount -> btcAccount
| None ->
let maybeLtcAccount =
GetAllActiveAccounts().OfType<NormalAccount>()
|> Seq.tryFind (fun acc -> (acc :> IAccount).Currency = Currency.LTC)
match maybeLtcAccount with
| Some ltcAccount -> ltcAccount
| None ->
let maybeSomeAccount =
GetAllActiveAccounts().OfType<NormalAccount>()
|> Seq.tryHead
match maybeSomeAccount with
| Some account -> account
| None ->
// the menu "Options" of GWallet.Frontend.Console shouldn't have shown this feature if no accounts
failwith "No accounts found to check valid password. Please report this bug"
async { return checkValidPasswordForSingleAccount account }
let private CreateArchivedAccount (currency: Currency) (unencryptedPrivateKey: string): ArchivedAccount =
let fromUnencryptedPrivateKeyToPublicAddressFunc =
if currency.IsUtxo() then
UtxoCoin.Account.GetPublicAddressFromUnencryptedPrivateKey currency
elif currency.IsEther() then
Ether.Account.GetPublicAddressFromUnencryptedPrivateKey
else
failwith <| SPrintF1 "Unknown currency %A" currency
let fromConfigFileToPublicAddressFunc (accountConfigFile: FileRepresentation) =
// there's no ETH unencrypted standard: https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition
// ... so we simply write the private key in string format
let privateKeyFromConfigFile = accountConfigFile.Content()
fromUnencryptedPrivateKeyToPublicAddressFunc privateKeyFromConfigFile
let fileName = fromUnencryptedPrivateKeyToPublicAddressFunc unencryptedPrivateKey
let conceptAccount = {
Currency = currency
FileRepresentation = { Name = fileName; Content = fun _ -> unencryptedPrivateKey }
ExtractPublicAddressFromConfigFileFunc = fromConfigFileToPublicAddressFunc
}
let newAccountFile = Config.AddAccount conceptAccount AccountKind.Archived
ArchivedAccount(currency, newAccountFile, fromConfigFileToPublicAddressFunc)
let Archive (account: NormalAccount)
(password: string)
: unit =
let currency = (account:>IAccount).Currency
let privateKeyAsString =
if currency.IsUtxo() then
let privKey = UtxoCoin.Account.GetPrivateKey account password
privKey.GetWif(UtxoCoin.Account.GetNetwork currency).ToWif()
elif currency.IsEther() then
let privKey = Ether.Account.GetPrivateKey account password
privKey.GetPrivateKey()
else
failwith <| SPrintF1 "Unknown currency %A" currency
CreateArchivedAccount currency privateKeyAsString
|> ignore<ArchivedAccount>
Config.RemoveNormalAccount account
let SweepArchivedFunds (account: ArchivedAccount)
(balance: decimal)
(destination: IAccount)
(txMetadata: IBlockchainFeeInfo)
(ignoreHigherMinerFeeThanAmount: bool) =
match txMetadata with
| :? Ether.TransactionMetadata as etherTxMetadata ->
Ether.Account.SweepArchivedFunds account balance destination etherTxMetadata ignoreHigherMinerFeeThanAmount
| :? UtxoCoin.TransactionMetadata as utxoTxMetadata ->
match account with
| :? UtxoCoin.ArchivedUtxoAccount as utxoAccount ->
UtxoCoin.Account.SweepArchivedFunds utxoAccount balance destination utxoTxMetadata ignoreHigherMinerFeeThanAmount
| _ ->
failwith "If tx metadata is UTXO type, archived account should be too"
| _ -> failwith "tx metadata type unknown"
// TODO: we should probably remove this function altogether, and make all frontend(s)
// use sign-off couple with broadcast, this way we can check the password is valid without
// trying to broadcast the transaction first (useful if user makes more than 1 guess for
// the password without having to prompt them about the miner fee in each try)
let SendPayment (account: NormalAccount)
(txMetadata: IBlockchainFeeInfo)
(destination: string)
(amount: TransferAmount)
(password: string)
(ignoreHigherMinerFeeThanAmount: bool)
: Async<Uri> =
let baseAccount = account :> IAccount
if (baseAccount.PublicAddress.Equals(destination, StringComparison.InvariantCultureIgnoreCase)) then
raise DestinationEqualToOrigin
let currency = baseAccount.Currency
async {
do! ValidateAddress currency destination
let! txId =
match txMetadata with
| :? UtxoCoin.TransactionMetadata as btcTxMetadata ->
if not (currency.IsUtxo()) then
failwith <| SPrintF1 "Currency %A not Utxo-type but tx metadata is? report this bug (sendpayment)"
currency
match account with
| :? UtxoCoin.NormalUtxoAccount as utxoAccount ->
UtxoCoin.Account.SendPayment utxoAccount btcTxMetadata destination amount password ignoreHigherMinerFeeThanAmount
| _ ->
failwith "Account not Utxo-type but tx metadata is? report this bug (sendpayment)"
| :? Ether.TransactionMetadata as etherTxMetadata ->
if not (currency.IsEtherBased()) then
failwith "Account not ether-type but tx metadata is? report this bug (sendpayment)"
Ether.Account.SendPayment account etherTxMetadata destination amount password ignoreHigherMinerFeeThanAmount
| _ ->
failwith "Unknown tx metadata type"
do! CheckIfOutOfGas txMetadata txId
let transactionProposal =
{
OriginMainAddress = baseAccount.PublicAddress
Amount = amount
DestinationAddress = destination
}
SaveOutgoingTransactionInCache transactionProposal txMetadata txId
let uri = BlockExplorer.GetTransaction currency txId
return uri
}
let SignUnsignedTransaction (account)
(unsignedTrans: UnsignedTransaction<IBlockchainFeeInfo>)
password =
let rawTransaction = SignTransaction account
unsignedTrans.Proposal.DestinationAddress
unsignedTrans.Proposal.Amount
unsignedTrans.Metadata
password
{ TransactionInfo = unsignedTrans; RawTransaction = rawTransaction }
let private ExportSignedTransaction (trans: SignedTransaction<_>) =
Marshalling.Serialize trans
let private SerializeSignedTransactionPlain (trans: SignedTransaction<_>): string =
let json =
match trans.TransactionInfo.Metadata.GetType() with
| t when t = typeof<Ether.TransactionMetadata> ->
let unsignedEthTx = {
Metadata = box trans.TransactionInfo.Metadata :?> Ether.TransactionMetadata;
Proposal = trans.TransactionInfo.Proposal;
Cache = trans.TransactionInfo.Cache;
}
let signedEthTx = {
TransactionInfo = unsignedEthTx;
RawTransaction = trans.RawTransaction;
}
ExportSignedTransaction signedEthTx
| t when t = typeof<UtxoCoin.TransactionMetadata> ->
let unsignedBtcTx = {
Metadata = box trans.TransactionInfo.Metadata :?> UtxoCoin.TransactionMetadata;
Proposal = trans.TransactionInfo.Proposal;
Cache = trans.TransactionInfo.Cache;
}
let signedBtcTx = {
TransactionInfo = unsignedBtcTx;
RawTransaction = trans.RawTransaction;
}
ExportSignedTransaction signedBtcTx
| _ -> failwith "Unknown miner fee type"
json
let SerializeSignedTransaction (transaction: SignedTransaction<_>)
(compressed: bool)
: string =
let json = SerializeSignedTransactionPlain transaction
if not compressed then
json
else
Marshalling.Compress json
let SaveSignedTransaction (trans: SignedTransaction<_>) (filePath: string) =
let json = SerializeSignedTransaction trans false
File.WriteAllText(filePath, json)
let CreateReadOnlyAccounts (watchWalletInfo: WatchWalletInfo): Async<unit> =
let ethJob = Ether.Account.CreateReadOnlyAccounts watchWalletInfo.EtherPublicAddress
let utxoJob =
async {
UtxoCoin.Account.CreateReadOnlyAccounts watchWalletInfo.UtxoCoinPublicKey
}
async {
do!
Async.Parallel [ethJob; utxoJob]
|> Async.Ignore
}
let Remove (account: ReadOnlyAccount) =
Config.RemoveReadOnlyAccount account
let private CreateConceptEtherAccountInternal (password: string) (seed: array<byte>)
: Async<FileRepresentation*(FileRepresentation->string)> =
async {
let! virtualFile = Ether.Account.Create password seed
return virtualFile, Ether.Account.GetPublicAddressFromNormalAccountFile
}
let private CreateConceptAccountInternal (currency: Currency) (password: string) (seed: array<byte>)
: Async<FileRepresentation*(FileRepresentation->string)> =
async {
if currency.IsUtxo() then
let! virtualFile = UtxoCoin.Account.Create currency password seed
return virtualFile, UtxoCoin.Account.GetPublicAddressFromNormalAccountFile currency
elif currency.IsEtherBased() then
return! CreateConceptEtherAccountInternal password seed
else
return failwith <| SPrintF1 "Unknown currency %A" currency
}
let CreateConceptAccount (currency: Currency) (password: string) (seed: array<byte>)
: Async<ConceptAccount> =
async {
let! virtualFile, fromEncPrivKeyToPublicAddressFunc =
CreateConceptAccountInternal currency password seed
return {
Currency = currency;
FileRepresentation = virtualFile
ExtractPublicAddressFromConfigFileFunc = fromEncPrivKeyToPublicAddressFunc;
}
}
let private CreateConceptAccountAux (currency: Currency) (password: string) (seed: array<byte>)
: Async<List<ConceptAccount>> =
async {
let! singleAccount = CreateConceptAccount currency password seed
return singleAccount::List.Empty
}
let CreateEtherNormalAccounts (password: string) (seed: array<byte>)
: Async<List<ConceptAccount>> =
let supportedEtherCurrencies = Currency.GetAll().Where(fun currency -> currency.IsEtherBased())
let etherAccounts = async {
let! virtualFile, fromEncPrivKeyToPublicAddressFunc =
CreateConceptEtherAccountInternal password seed
return seq {
for etherCurrency in supportedEtherCurrencies do
yield {
Currency = etherCurrency;
FileRepresentation = virtualFile
ExtractPublicAddressFromConfigFileFunc = fromEncPrivKeyToPublicAddressFunc
}
} |> List.ofSeq
}
etherAccounts
let CreateNormalAccount (conceptAccount: ConceptAccount): NormalAccount =
let newAccountFile = Config.AddAccount conceptAccount AccountKind.Normal
NormalAccount(conceptAccount.Currency, newAccountFile, conceptAccount.ExtractPublicAddressFromConfigFileFunc)
let GenerateMasterPrivateKey (passphrase: string)
(dobPartOfSalt: DateTime) (emailPartOfSalt: string)
: Async<array<byte>> =
async {
let salt = SPrintF2 "%s+%s" (dobPartOfSalt.Date.ToString("yyyyMMdd")) (emailPartOfSalt.ToLower())
let privateKeyBytes = WarpKey.CreatePrivateKey passphrase salt
return privateKeyBytes
}
let CreateAllConceptAccounts (privateKeyBytes: array<byte>) (encryptionPassword: string)
: Async<seq<ConceptAccount>> = async {
let etherAccounts = CreateEtherNormalAccounts encryptionPassword privateKeyBytes
let nonEthCurrencies = Currency.GetAll().Where(fun currency -> not (currency.IsEtherBased()))
let nonEtherAccounts: List<Async<List<ConceptAccount>>> =
seq {
// TODO: figure out if we can reuse CPU computation of WIF creation between BTC<C
for nonEthCurrency in nonEthCurrencies do
yield CreateConceptAccountAux nonEthCurrency encryptionPassword privateKeyBytes
} |> List.ofSeq
let allAccounts = etherAccounts::nonEtherAccounts
let createAllAccountsJob = Async.Parallel allAccounts
let! allCreatedConceptAccounts = createAllAccountsJob
let allConceptAccounts =
seq {
for accountGroup in allCreatedConceptAccounts do
for conceptAccount in accountGroup do
yield conceptAccount
}
return allConceptAccounts
}
let CreateAllAccounts (privateKeyBytes: array<byte>) (encryptionPassword: string): Async<unit> = async {
let! allConceptAccounts = CreateAllConceptAccounts privateKeyBytes encryptionPassword
for conceptAccount in allConceptAccounts do
CreateNormalAccount conceptAccount
|> ignore<NormalAccount>
}
let CheckValidSeed (passphrase: string)
(dobPartOfSalt: DateTime)
(emailPartOfSalt: string) =
async {
let! masterPrivateKey = GenerateMasterPrivateKey passphrase dobPartOfSalt emailPartOfSalt
let! allConceptAccounts = CreateAllConceptAccounts masterPrivateKey (Guid.NewGuid().ToString())
return allConceptAccounts.All(fun conceptAccount ->
GetAllActiveAccounts().Any(fun account ->
let publicAddressOfConceptAccount =
conceptAccount.ExtractPublicAddressFromConfigFileFunc conceptAccount.FileRepresentation
let publicAddressMatches = (account.PublicAddress = publicAddressOfConceptAccount)
publicAddressMatches
)
)
}
let WipeAll() =
Config.Wipe()
Caching.Instance.ClearAll()
let public ExportUnsignedTransactionToJson trans =
Marshalling.Serialize trans
let private SerializeUnsignedTransactionPlain (transProposal: UnsignedTransactionProposal)
(txMetadata: IBlockchainFeeInfo)
: string =
let readOnlyAccounts = GetAllActiveAccounts().OfType<ReadOnlyAccount>()
match txMetadata with
| :? Ether.TransactionMetadata as etherTxMetadata ->
Ether.Account.SaveUnsignedTransaction transProposal etherTxMetadata readOnlyAccounts
| :? UtxoCoin.TransactionMetadata as btcTxMetadata ->
UtxoCoin.Account.SaveUnsignedTransaction transProposal btcTxMetadata readOnlyAccounts
| _ -> failwith "fee type unknown"
let SerializeUnsignedTransaction (transProposal: UnsignedTransactionProposal)
(txMetadata: IBlockchainFeeInfo)
(compressed: bool)
: string =
let json = SerializeUnsignedTransactionPlain transProposal txMetadata
if not compressed then
json
else
Marshalling.Compress json
let SaveUnsignedTransaction (transProposal: UnsignedTransactionProposal)
(txMetadata: IBlockchainFeeInfo)
(filePath: string) =
let json = SerializeUnsignedTransaction transProposal txMetadata false
File.WriteAllText(filePath, json)
let public ImportUnsignedTransactionFromJson (jsonOrCompressedJson: string): UnsignedTransaction<IBlockchainFeeInfo> =
let json =
try
Marshalling.Decompress jsonOrCompressedJson
with
| :? Marshalling.CompressionOrDecompressionException ->
jsonOrCompressedJson
let transType = Marshalling.ExtractType json
match transType with
| _ when transType = typeof<UnsignedTransaction<UtxoCoin.TransactionMetadata>> ->
let deserializedBtcTransaction: UnsignedTransaction<UtxoCoin.TransactionMetadata> =
Marshalling.Deserialize json
deserializedBtcTransaction.ToAbstract()
| _ when transType = typeof<UnsignedTransaction<Ether.TransactionMetadata>> ->
let deserializedBtcTransaction: UnsignedTransaction<Ether.TransactionMetadata> =
Marshalling.Deserialize json
deserializedBtcTransaction.ToAbstract()
| _ when transType.GetGenericTypeDefinition() = typedefof<SignedTransaction<_>> ->
raise TransactionAlreadySigned
| unexpectedType ->
raise <| Exception(SPrintF1 "Unknown unsignedTransaction subtype: %s" unexpectedType.FullName)
let public ImportSignedTransactionFromJson (jsonOrCompressedJson: string): SignedTransaction<IBlockchainFeeInfo> =
let json =
try
Marshalling.Decompress jsonOrCompressedJson
with
| :? Marshalling.CompressionOrDecompressionException ->
jsonOrCompressedJson
let transType = Marshalling.ExtractType json
match transType with
| _ when transType = typeof<SignedTransaction<UtxoCoin.TransactionMetadata>> ->
let deserializedTransaction: SignedTransaction<UtxoCoin.TransactionMetadata> =
Marshalling.Deserialize json
deserializedTransaction.ToAbstract()
| _ when transType = typeof<SignedTransaction<Ether.TransactionMetadata>> ->
let deserializedTransaction: SignedTransaction<Ether.TransactionMetadata> =
Marshalling.Deserialize json
deserializedTransaction.ToAbstract()
| _ when transType.GetGenericTypeDefinition() = typedefof<UnsignedTransaction<_>> ->
raise TransactionNotSignedYet
| unexpectedType ->
raise <| Exception(SPrintF1 "Unknown signedTransaction subtype: %s" unexpectedType.FullName)
let public ImportTransactionFromJson (jsonOrCompressedJson: string): ImportedTransaction<IBlockchainFeeInfo> =
let json =
try
Marshalling.Decompress jsonOrCompressedJson
with
| :? Marshalling.CompressionOrDecompressionException ->
jsonOrCompressedJson
let transType = Marshalling.ExtractType json
match transType with
| _ when transType = typeof<UnsignedTransaction<UtxoCoin.TransactionMetadata>> ->
let deserializedTransaction: UnsignedTransaction<UtxoCoin.TransactionMetadata> =
Marshalling.Deserialize json
Unsigned(deserializedTransaction.ToAbstract())
| _ when transType = typeof<UnsignedTransaction<Ether.TransactionMetadata>> ->
let deserializedTransaction: UnsignedTransaction<Ether.TransactionMetadata> =
Marshalling.Deserialize json
Unsigned(deserializedTransaction.ToAbstract())
| _ when transType = typeof<SignedTransaction<UtxoCoin.TransactionMetadata>> ->
let deserializedTransaction: SignedTransaction<UtxoCoin.TransactionMetadata> =
Marshalling.Deserialize json
Signed(deserializedTransaction.ToAbstract())
| _ when transType = typeof<SignedTransaction<Ether.TransactionMetadata>> ->
let deserializedTransaction: SignedTransaction<Ether.TransactionMetadata> =
Marshalling.Deserialize json
Signed(deserializedTransaction.ToAbstract())
| unexpectedType ->
failwith <| SPrintF1 "Unknown unsignedTransaction subtype: %s" unexpectedType.FullName
let LoadSignedTransactionFromFile (filePath: string) =
let signedTransInJson = File.ReadAllText(filePath)
ImportSignedTransactionFromJson signedTransInJson
let LoadUnsignedTransactionFromFile (filePath: string): UnsignedTransaction<IBlockchainFeeInfo> =
let unsignedTransInJson = File.ReadAllText(filePath)
ImportUnsignedTransactionFromJson unsignedTransInJson
let GetSignedTransactionDetails<'T when 'T :> IBlockchainFeeInfo> (signedTransaction: SignedTransaction<'T>)
: ITransactionDetails =
let currency = signedTransaction.TransactionInfo.Proposal.Amount.Currency
if currency.IsUtxo () then
let readOnlyUtxoAccounts =
GetAllActiveAccounts().OfType<UtxoCoin.ReadOnlyUtxoAccount>()
UtxoCoin.Account.GetSignedTransactionDetails
signedTransaction.RawTransaction
currency
readOnlyUtxoAccounts
elif currency.IsEtherBased () then
Ether.Account.GetSignedTransactionDetails
signedTransaction
else
failwith <| (SPrintF1 "Unknown currency: %A" currency)