-
Notifications
You must be signed in to change notification settings - Fork 220
/
Copy pathServer.hs
3837 lines (3560 loc) · 138 KB
/
Server.hs
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
{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedLabels #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
-- |
-- Copyright: © 2018-2020 IOHK
-- License: Apache-2.0
--
-- API handlers and server using the underlying wallet layer to provide
-- endpoints reachable through HTTP.
module Cardano.Wallet.Api.Server
(
-- * Server Configuration
Listen (..)
, ListenError (..)
, HostPreference
, TlsConfiguration (..)
-- * Server Setup
, start
, serve
, withListeningSocket
-- * ApiLayer
, newApiLayer
-- * Handlers
, delegationFee
, deleteTransaction
, deleteWallet
, derivePublicKey
, getNetworkClock
, getNetworkInformation
, getNetworkParameters
, getUTxOsStatistics
, getWalletUtxoSnapshot
, getWallet
, joinStakePool
, listAssets
, getAsset
, getAssetDefault
, listAddresses
, listTransactions
, getTransaction
, constructTransaction
, listWallets
, listStakeKeys
, createMigrationPlan
, migrateWallet
, postExternalTransaction
, postIcarusWallet
, postLedgerWallet
, postRandomAddress
, postRandomWallet
, postRandomWalletFromXPrv
, signTransaction
, postTransactionOld
, postTransactionFeeOld
, postTrezorWallet
, postWallet
, postShelleyWallet
, postAccountWallet
, putByronWalletPassphrase
, putRandomAddress
, putRandomAddresses
, putWallet
, putWalletPassphrase
, quitStakePool
, selectCoins
, selectCoinsForJoin
, selectCoinsForQuit
, signMetadata
, postAccountPublicKey
, getAccountPublicKey
, postSharedWallet
, patchSharedWallet
, mkSharedWallet
, mintBurnAssets
-- * Server error responses
, IsServerError(..)
, liftHandler
, apiError
-- * Internals
, mkShelleyWallet
, mkLegacyWallet
, withLegacyLayer
, withLegacyLayer'
, rndStateChange
, withWorkerCtx
, getCurrentEpoch
-- * Workers
, manageRewardBalance
, idleWorker
-- * Logging
, WalletEngineLog (..)
) where
import Prelude
import Cardano.Address.Derivation
( XPrv, XPub, xpubPublicKey, xpubToBytes )
import Cardano.Address.Script
( Cosigner (..), ScriptTemplate (..), ValidationLevel (..) )
import Cardano.Api
( AnyCardanoEra (..), CardanoEra (..), SerialiseAsCBOR (..) )
import Cardano.BM.Tracing
( HasPrivacyAnnotation (..), HasSeverityAnnotation (..) )
import Cardano.Mnemonic
( SomeMnemonic )
import Cardano.Wallet
( ErrAddCosignerKey (..)
, ErrCannotJoin (..)
, ErrCannotQuit (..)
, ErrConstructSharedWallet (..)
, ErrConstructTx (..)
, ErrCreateMigrationPlan (..)
, ErrCreateRandomAddress (..)
, ErrDecodeSignedTx (..)
, ErrDerivePublicKey (..)
, ErrFetchRewards (..)
, ErrGetTransaction (..)
, ErrImportAddress (..)
, ErrImportRandomAddress (..)
, ErrInvalidDerivationIndex (..)
, ErrJoinStakePool (..)
, ErrListTransactions (..)
, ErrListUTxOStatistics (..)
, ErrMintBurnAssets (..)
, ErrMkTx (..)
, ErrNoSuchTransaction (..)
, ErrNoSuchWallet (..)
, ErrNotASequentialWallet (..)
, ErrPostTx (..)
, ErrQuitStakePool (..)
, ErrReadAccountPublicKey (..)
, ErrReadRewardAccount (..)
, ErrRemoveTx (..)
, ErrSelectAssets (..)
, ErrSignMetadataWith (..)
, ErrSignPayment (..)
, ErrStartTimeLaterThanEndTime (..)
, ErrSubmitExternalTx (..)
, ErrSubmitTx (..)
, ErrUpdatePassphrase (..)
, ErrWalletAlreadyExists (..)
, ErrWalletNotResponding (..)
, ErrWithRootKey (..)
, ErrWithdrawalNotWorth (..)
, ErrWrongPassphrase (..)
, FeeEstimation (..)
, HasNetworkLayer
, TxSubmitLog
, genesisData
, manageRewardBalance
, networkLayer
)
import Cardano.Wallet.Api
( ApiLayer (..)
, HasDBFactory
, HasTokenMetadataClient
, HasWorkerRegistry
, WalletLock (..)
, dbFactory
, tokenMetadataClient
, workerRegistry
, walletLocks
)
import Cardano.Wallet.Api.Server.Tls
( TlsConfiguration (..), requireClientAuth )
import Cardano.Wallet.Api.Types
( AccountPostData (..)
, AddressAmount (..)
, ApiAccountPublicKey (..)
, ApiActiveSharedWallet (..)
, ApiAddress (..)
, ApiAsset (..)
, ApiBlockInfo (..)
, ApiBlockReference (..)
, ApiByronWallet (..)
, ApiByronWalletBalance (..)
, ApiBytesT (..)
, ApiCoinSelection (..)
, ApiCoinSelectionChange (..)
, ApiCoinSelectionInput (..)
, ApiCoinSelectionOutput (..)
, ApiCoinSelectionWithdrawal (..)
, ApiConstructTransaction (..)
, ApiConstructTransactionData
, ApiEpochInfo (ApiEpochInfo)
, ApiEra (..)
, ApiErrorCode (..)
, ApiFee (..)
, ApiForeignStakeKey (..)
, ApiMintedBurnedTransaction (..)
, ApiMnemonicT (..)
, ApiNetworkClock (..)
, ApiNetworkInformation
, ApiNetworkParameters (..)
, ApiNullStakeKey (..)
, ApiOurStakeKey (..)
, ApiPaymentDestination (..)
, ApiPendingSharedWallet (..)
, ApiPoolId (..)
, ApiPostAccountKeyDataWithPurpose (..)
, ApiPostRandomAddressData (..)
, ApiPutAddressesData (..)
, ApiScriptTemplateEntry (..)
, ApiSelectCoinsPayments
, ApiSharedWallet (..)
, ApiSharedWalletPatchData (..)
, ApiSharedWalletPostData (..)
, ApiSharedWalletPostDataFromAccountPubX (..)
, ApiSharedWalletPostDataFromMnemonics (..)
, ApiSignTransactionPostData (..)
, ApiSignedTransaction
, ApiSlotId (..)
, ApiSlotReference (..)
, ApiStakeKeys (..)
, ApiT (..)
, ApiTransaction (..)
, ApiTxId (..)
, ApiTxInput (..)
, ApiTxMetadata (..)
, ApiUtxoStatistics (..)
, ApiWallet (..)
, ApiWalletAssetsBalance (..)
, ApiWalletBalance (..)
, ApiWalletDelegation (..)
, ApiWalletDelegationNext (..)
, ApiWalletDelegationStatus (..)
, ApiWalletMigrationBalance (..)
, ApiWalletMigrationPlan (..)
, ApiWalletMigrationPlanPostData (..)
, ApiWalletMigrationPostData (..)
, ApiWalletPassphrase (..)
, ApiWalletPassphraseInfo (..)
, ApiWalletSignData (..)
, ApiWalletUtxoSnapshot (..)
, ApiWalletUtxoSnapshotEntry (..)
, ApiWithdrawal (..)
, ApiWithdrawalPostData (..)
, ByronWalletFromXPrvPostData
, ByronWalletPostData (..)
, ByronWalletPutPassphraseData (..)
, Iso8601Time (..)
, KeyFormat (..)
, KnownDiscovery (..)
, MinWithdrawal (..)
, PostTransactionFeeOldData (..)
, PostTransactionOldData (..)
, VerificationKeyHashing (..)
, WalletOrAccountPostData (..)
, WalletPostData (..)
, WalletPutData (..)
, WalletPutPassphraseData (..)
, XPubOrSelf (..)
, coinFromQuantity
, coinToQuantity
, getApiMnemonicT
, toApiAsset
, toApiEpochInfo
, toApiNetworkParameters
, toApiUtxoStatistics
)
import Cardano.Wallet.Compat
( (^?) )
import Cardano.Wallet.DB
( DBFactory (..) )
import Cardano.Wallet.Network
( NetworkLayer, fetchRewardAccountBalances, timeInterpreter )
import Cardano.Wallet.Primitive.AddressDerivation
( DelegationAddress (..)
, Depth (..)
, DerivationIndex (..)
, DerivationType (..)
, HardDerivation (..)
, Index (..)
, MkKeyFingerprint
, NetworkDiscriminant (..)
, Passphrase (..)
, PaymentAddress (..)
, RewardAccount (..)
, Role
, SoftDerivation (..)
, WalletKey (..)
, deriveRewardAccount
, digest
, preparePassphrase
, publicKey
)
import Cardano.Wallet.Primitive.AddressDerivation.Byron
( ByronKey, mkByronKeyFromMasterKey )
import Cardano.Wallet.Primitive.AddressDerivation.Icarus
( IcarusKey )
import Cardano.Wallet.Primitive.AddressDerivation.SharedKey
( SharedKey (..) )
import Cardano.Wallet.Primitive.AddressDerivation.Shelley
( ShelleyKey )
import Cardano.Wallet.Primitive.AddressDiscovery
( CompareDiscovery
, GenChange (ArgGenChange)
, GetAccount
, GetPurpose (..)
, IsOurs
, IsOwned
, KnownAddresses
)
import Cardano.Wallet.Primitive.AddressDiscovery.Random
( RndState, mkRndState )
import Cardano.Wallet.Primitive.AddressDiscovery.Sequential
( DerivationPrefix (..)
, ParentContext (..)
, SeqState (..)
, context
, defaultAddressPoolGap
, gap
, mkSeqStateFromAccountXPub
, mkSeqStateFromRootXPrv
, purposeCIP1852
)
import Cardano.Wallet.Primitive.AddressDiscovery.Shared
( CredentialType (..)
, ErrAddCosigner (..)
, ErrScriptTemplate (..)
, SharedState (..)
, SharedStateFields (..)
, SharedStatePending (..)
, mkSharedStateFromAccountXPub
, mkSharedStateFromRootXPrv
, validateScriptTemplates
)
import Cardano.Wallet.Primitive.CoinSelection.MA.RoundRobin
( SelectionError (..)
, SelectionResult (..)
, UnableToConstructChangeError (..)
, balanceMissing
, missingOutputAssets
, selectionDelta
)
import Cardano.Wallet.Primitive.Delegation.UTxO
( stakeKeyCoinDistr )
import Cardano.Wallet.Primitive.Migration
( MigrationPlan (..) )
import Cardano.Wallet.Primitive.Model
( Wallet
, availableBalance
, availableUTxO
, currentTip
, getState
, totalBalance
)
import Cardano.Wallet.Primitive.Slotting
( PastHorizonException
, RelativeTime
, TimeInterpreter
, currentEpoch
, currentRelativeTime
, expectAndThrowFailures
, hoistTimeInterpreter
, interpretQuery
, neverFails
, ongoingSlotAt
, slotToUTCTime
, timeOfEpoch
, toSlotId
, unsafeExtendSafeZone
)
import Cardano.Wallet.Primitive.SyncProgress
( SyncProgress (..), SyncTolerance, syncProgress )
import Cardano.Wallet.Primitive.Types
( Block
, BlockHeader (..)
, NetworkParameters (..)
, PassphraseScheme (..)
, PoolId
, PoolLifeCycleStatus (..)
, Signature (..)
, SlotId
, SlotNo
, SortOrder (..)
, WalletId (..)
, WalletMetadata (..)
)
import Cardano.Wallet.Primitive.Types.Address
( Address (..), AddressState (..) )
import Cardano.Wallet.Primitive.Types.Coin
( Coin (..), coinQuantity )
import Cardano.Wallet.Primitive.Types.Hash
( Hash (..) )
import Cardano.Wallet.Primitive.Types.TokenBundle
( Flat (..), TokenBundle (..) )
import Cardano.Wallet.Primitive.Types.TokenMap
( AssetId (..) )
import Cardano.Wallet.Primitive.Types.TokenPolicy
( TokenName (..), TokenPolicyId (..), nullTokenName )
import Cardano.Wallet.Primitive.Types.Tx
( SerialisedTx (..)
, TransactionInfo (TransactionInfo)
, Tx (..)
, TxChange (..)
, TxIn (..)
, TxOut (..)
, TxStatus (..)
, UnsignedTx (..)
, txOutCoin
)
import Cardano.Wallet.Registry
( HasWorkerCtx (..)
, MkWorker (..)
, WorkerLog (..)
, defaultWorkerAfter
, workerResource
)
import Cardano.Wallet.TokenMetadata
( TokenMetadataClient, fillMetadata )
import Cardano.Wallet.Transaction
( DelegationAction (..)
, ErrOutputTokenBundleSizeExceedsLimit (..)
, ErrOutputTokenQuantityExceedsLimit (..)
, ErrSelectionCriteria (..)
, TransactionCtx (..)
, TransactionLayer
, Withdrawal (..)
, defaultTransactionCtx
)
import Cardano.Wallet.Unsafe
( unsafeRunExceptT )
import Control.Arrow
( second )
import Control.DeepSeq
( NFData )
import Control.Error.Util
( failWith )
import Control.Monad
( forM, forever, join, void, when, (>=>) )
import Control.Monad.IO.Class
( MonadIO, liftIO )
import Control.Monad.Trans.Except
( ExceptT (..), runExceptT, throwE, withExceptT )
import Control.Monad.Trans.Maybe
( MaybeT (..), exceptToMaybeT )
import Control.Tracer
( Tracer, contramap )
import Crypto.Hash.Utils
( blake2b224 )
import Data.Aeson
( (.=) )
import Data.Bifunctor
( first )
import Data.ByteString
( ByteString )
import Data.Coerce
( coerce )
import Data.Either.Extra
( eitherToMaybe )
import Data.Function
( (&) )
import Data.Functor
( (<&>) )
import Data.Functor.Identity
( Identity (..) )
import Data.Generics.Internal.VL.Lens
( Lens', view, (.~), (^.) )
import Data.Generics.Labels
()
import Data.List
( isInfixOf, isPrefixOf, isSubsequenceOf, sortOn, (\\) )
import Data.List.NonEmpty
( NonEmpty (..) )
import Data.Map.Strict
( Map )
import Data.Maybe
( catMaybes, fromMaybe, isJust, isNothing, mapMaybe, maybeToList )
import Data.Proxy
( Proxy (..) )
import Data.Quantity
( Quantity (..) )
import Data.Set
( Set )
import Data.Streaming.Network
( HostPreference, bindPortTCP, bindRandomPortTCP )
import Data.Text
( Text )
import Data.Text.Class
( FromText (..), ToText (..) )
import Data.Time
( UTCTime )
import Data.Type.Equality
( (:~:) (..), type (==), testEquality )
import Data.Word
( Word32 )
import Fmt
( blockListF, indentF, pretty )
import GHC.Stack
( HasCallStack )
import Network.HTTP.Media.RenderHeader
( renderHeader )
import Network.HTTP.Types.Header
( hContentType )
import Network.Ntp
( NtpClient, getNtpStatus )
import Network.Socket
( Socket, close )
import Network.Wai
( Request, pathInfo )
import Network.Wai.Handler.Warp
( Port )
import Network.Wai.Middleware.Logging
( ApiLog (..), newApiLoggerSettings, obfuscateKeys, withApiLogger )
import Network.Wai.Middleware.ServerError
( handleRawError )
import Numeric.Natural
( Natural )
import Servant
( Application
, JSON
, NoContent (..)
, contentType
, err400
, err403
, err404
, err409
, err500
, err501
, err503
, serve
)
import Servant.Server
( Handler (..), ServerError (..), runHandler )
import System.IO.Error
( ioeGetErrorType
, isAlreadyInUseError
, isDoesNotExistError
, isPermissionError
, isUserError
)
import System.Random
( getStdRandom, random )
import Type.Reflection
( Typeable, typeRep )
import UnliftIO.Async
( race_ )
import UnliftIO.Concurrent
( threadDelay )
import UnliftIO.Exception
( IOException, bracket, throwIO, tryAnyDeep, tryJust )
import qualified Cardano.Wallet as W
import qualified Cardano.Wallet.Api.Types as Api
import qualified Cardano.Wallet.Network as NW
import qualified Cardano.Wallet.Primitive.AddressDerivation.Byron as Byron
import qualified Cardano.Wallet.Primitive.AddressDerivation.Icarus as Icarus
import qualified Cardano.Wallet.Primitive.Types as W
import qualified Cardano.Wallet.Primitive.Types.Coin as Coin
import qualified Cardano.Wallet.Primitive.Types.TokenBundle as TokenBundle
import qualified Cardano.Wallet.Primitive.Types.Tx as W
import qualified Cardano.Wallet.Primitive.Types.UTxO as UTxO
import qualified Cardano.Wallet.Registry as Registry
import qualified Control.Concurrent.Concierge as Concierge
import qualified Data.Aeson as Aeson
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BL
import qualified Data.Foldable as F
import qualified Data.List.NonEmpty as NE
import qualified Data.Map.Strict as Map
import qualified Data.Set as Set
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Network.Wai.Handler.Warp as Warp
import qualified Network.Wai.Handler.WarpTLS as Warp
-- | How the server should listen for incoming requests.
data Listen
= ListenOnPort Port
-- ^ Listen on given TCP port
| ListenOnRandomPort
-- ^ Listen on an unused TCP port, selected at random
deriving (Show, Eq)
-- | Start the application server, using the given settings and a bound socket.
start
:: Warp.Settings
-> Tracer IO ApiLog
-> Maybe TlsConfiguration
-> Socket
-> Application
-> IO ()
start settings tr tlsConfig socket application = do
logSettings <- newApiLoggerSettings <&> obfuscateKeys (const sensitive)
runSocket
$ handleRawError (curry toServerError)
$ withApiLogger tr logSettings
application
where
runSocket :: Application -> IO ()
runSocket = case tlsConfig of
Nothing -> Warp.runSettingsSocket settings socket
Just tls -> Warp.runTLSSocket (requireClientAuth tls) settings socket
sensitive :: [Text]
sensitive =
[ "passphrase"
, "old_passphrase"
, "new_passphrase"
, "mnemonic_sentence"
, "mnemonic_second_factor"
]
-- | Run an action with a TCP socket bound to a port specified by the `Listen`
-- parameter.
withListeningSocket
:: HostPreference
-- ^ Which host to bind.
-> Listen
-- ^ Whether to listen on a given port, or random port.
-> (Either ListenError (Port, Socket) -> IO a)
-- ^ Action to run with listening socket.
-> IO a
withListeningSocket hostPreference portOpt = bracket acquire release
where
acquire = tryJust handleErr bindAndListen
-- Note: These Data.Streaming.Network functions also listen on the socket,
-- even though their name just says "bind".
bindAndListen = case portOpt of
ListenOnPort port -> (port,) <$> bindPortTCP port hostPreference
ListenOnRandomPort -> bindRandomPortTCP hostPreference
release (Right (_, socket)) = liftIO $ close socket
release (Left _) = pure ()
handleErr = ioToListenError hostPreference portOpt
data ListenError
= ListenErrorAddressAlreadyInUse (Maybe Port)
| ListenErrorOperationNotPermitted
| ListenErrorHostDoesNotExist HostPreference
| ListenErrorInvalidAddress HostPreference
deriving (Show, Eq)
ioToListenError :: HostPreference -> Listen -> IOException -> Maybe ListenError
ioToListenError hostPreference portOpt e
-- A socket is already listening on that address and port
| isAlreadyInUseError e =
Just (ListenErrorAddressAlreadyInUse (listenPort portOpt))
-- Usually caused by trying to listen on a privileged port
| isPermissionError e =
Just ListenErrorOperationNotPermitted
-- Bad hostname -- Linux and Darwin
| isDoesNotExistError e =
Just (ListenErrorHostDoesNotExist hostPreference)
-- Bad hostname (bind: WSAEOPNOTSUPP) -- Windows
| isUserError e && (hasDescription "11001" || hasDescription "10045") =
Just (ListenErrorHostDoesNotExist hostPreference)
-- Address is valid, but can't be used for listening -- Linux
| show (ioeGetErrorType e) == "invalid argument" =
Just (ListenErrorInvalidAddress hostPreference)
-- Address is valid, but can't be used for listening -- Darwin
| show (ioeGetErrorType e) == "unsupported operation" =
Just (ListenErrorInvalidAddress hostPreference)
-- Address is valid, but can't be used for listening -- Windows
| isOtherError e &&
(hasDescription "WSAEINVAL" || hasDescription "WSAEADDRNOTAVAIL") =
Just (ListenErrorInvalidAddress hostPreference)
-- Listening on an unavailable or privileged port -- Windows
| isOtherError e && hasDescription "WSAEACCESS" =
Just (ListenErrorAddressAlreadyInUse (listenPort portOpt))
| otherwise =
Nothing
where
listenPort (ListenOnPort port) = Just port
listenPort ListenOnRandomPort = Nothing
isOtherError ex = show (ioeGetErrorType ex) == "failed"
hasDescription text = text `isInfixOf` show e
{-------------------------------------------------------------------------------
Wallet Constructors
-------------------------------------------------------------------------------}
type MkApiWallet ctx s w
= ctx
-> WalletId
-> Wallet s
-> WalletMetadata
-> Set Tx
-> SyncProgress
-> Handler w
--------------------- Shelley
postWallet
:: forall ctx s k n.
( s ~ SeqState n k
, ctx ~ ApiLayer s k
, SoftDerivation k
, MkKeyFingerprint k (Proxy n, k 'AddressK XPub)
, MkKeyFingerprint k Address
, WalletKey k
, Bounded (Index (AddressIndexDerivationType k) 'AddressK)
, HasDBFactory s k ctx
, HasWorkerRegistry s k ctx
, IsOurs s RewardAccount
, Typeable s
, Typeable n
, (k == SharedKey) ~ 'False
)
=> ctx
-> ((SomeMnemonic, Maybe SomeMnemonic) -> Passphrase "encryption" -> k 'RootK XPrv)
-> (XPub -> k 'AccountK XPub)
-> WalletOrAccountPostData
-> Handler ApiWallet
postWallet ctx generateKey liftKey (WalletOrAccountPostData body) = case body of
Left body' ->
postShelleyWallet ctx generateKey body'
Right body' ->
postAccountWallet ctx mkShelleyWallet liftKey
(W.manageRewardBalance @_ @s @k (Proxy @n)) body'
postShelleyWallet
:: forall ctx s k n.
( s ~ SeqState n k
, ctx ~ ApiLayer s k
, SoftDerivation k
, MkKeyFingerprint k (Proxy n, k 'AddressK XPub)
, MkKeyFingerprint k Address
, WalletKey k
, Bounded (Index (AddressIndexDerivationType k) 'AddressK)
, HasDBFactory s k ctx
, HasWorkerRegistry s k ctx
, IsOurs s RewardAccount
, Typeable s
, Typeable n
, (k == SharedKey) ~ 'False
)
=> ctx
-> ((SomeMnemonic, Maybe SomeMnemonic) -> Passphrase "encryption" -> k 'RootK XPrv)
-> WalletPostData
-> Handler ApiWallet
postShelleyWallet ctx generateKey body = do
let state = mkSeqStateFromRootXPrv (rootXPrv, pwd) purposeCIP1852 g
void $ liftHandler $ createWalletWorker @_ @s @k ctx wid
(\wrk -> W.createWallet @(WorkerCtx ctx) @_ @s @k wrk wid wName state)
(\wrk _ -> W.manageRewardBalance @(WorkerCtx ctx) @s @k (Proxy @n) wrk wid)
withWorkerCtx @_ @s @k ctx wid liftE liftE $ \wrk -> liftHandler $
W.attachPrivateKeyFromPwd @_ @s @k wrk wid (rootXPrv, pwd)
fst <$> getWallet ctx (mkShelleyWallet @_ @s @k) (ApiT wid)
where
seed = getApiMnemonicT (body ^. #mnemonicSentence)
secondFactor = getApiMnemonicT <$> (body ^. #mnemonicSecondFactor)
pwd = preparePassphrase EncryptWithPBKDF2 $ getApiT (body ^. #passphrase)
rootXPrv = generateKey (seed, secondFactor) pwd
g = maybe defaultAddressPoolGap getApiT (body ^. #addressPoolGap)
wid = WalletId $ digest $ publicKey rootXPrv
wName = getApiT (body ^. #name)
postAccountWallet
:: forall ctx s k n w.
( s ~ SeqState n k
, ctx ~ ApiLayer s k
, SoftDerivation k
, MkKeyFingerprint k (Proxy n, k 'AddressK XPub)
, MkKeyFingerprint k Address
, WalletKey k
, HasWorkerRegistry s k ctx
, IsOurs s RewardAccount
, Typeable n
, (k == SharedKey) ~ 'False
)
=> ctx
-> MkApiWallet ctx s w
-> (XPub -> k 'AccountK XPub)
-> (WorkerCtx ctx -> WalletId -> IO ())
-- ^ Action to run concurrently with restore action
-> AccountPostData
-> Handler w
postAccountWallet ctx mkWallet liftKey coworker body = do
let state = mkSeqStateFromAccountXPub (liftKey accXPub) purposeCIP1852 g
void $ liftHandler $ createWalletWorker @_ @s @k ctx wid
(\wrk -> W.createWallet @(WorkerCtx ctx) @_ @s @k wrk wid wName state)
coworker
fst <$> getWallet ctx mkWallet (ApiT wid)
where
g = maybe defaultAddressPoolGap getApiT (body ^. #addressPoolGap)
wName = getApiT (body ^. #name)
(ApiAccountPublicKey accXPubApiT) = body ^. #accountPublicKey
accXPub = getApiT accXPubApiT
wid = WalletId $ digest (liftKey accXPub)
mkShelleyWallet
:: forall ctx s k n.
( ctx ~ ApiLayer s k
, s ~ SeqState n k
, IsOurs s Address
, IsOurs s RewardAccount
, HasWorkerRegistry s k ctx
)
=> MkApiWallet ctx s ApiWallet
mkShelleyWallet ctx wid cp meta pending progress = do
reward <- withWorkerCtx @_ @s @k ctx wid liftE liftE $ \wrk ->
-- never fails - returns zero if balance not found
liftIO $ W.fetchRewardBalance @_ @s @k wrk wid
let ti = timeInterpreter $ ctx ^. networkLayer
-- In the Shelley era of Byron;Shelley;Allegra toApiWalletDelegation using
-- an unextended @ti@ will simply fail because of uncertainty about the next
-- fork.
--
-- @unsafeExtendSafeZone@ performs the calculation as if no fork will occur.
-- This should be fine because:
-- 1. We expect the next few eras to have the same epoch length as Shelley
-- 2. It shouldn't be the end of the world to return the wrong time.
--
-- But ultimately, we might want to make the uncertainty transparent to API
-- users. TODO: ADP-575
apiDelegation <- liftIO $ toApiWalletDelegation (meta ^. #delegation)
(unsafeExtendSafeZone ti)
tip' <- liftIO $ getWalletTip
(neverFails "getWalletTip wallet tip should be behind node tip" ti)
cp
let available = availableBalance pending cp
let total = totalBalance pending reward cp
pure ApiWallet
{ addressPoolGap = ApiT $ getState cp ^. #externalPool . #gap
, balance = ApiWalletBalance
{ available = coinToQuantity (available ^. #coin)
, total = coinToQuantity (total ^. #coin)
, reward = coinToQuantity reward
}
, assets = ApiWalletAssetsBalance
{ available = ApiT (available ^. #tokens)
, total = ApiT (total ^. #tokens)
}
, delegation = apiDelegation
, id = ApiT wid
, name = ApiT $ meta ^. #name
, passphrase = ApiWalletPassphraseInfo
<$> fmap (view #lastUpdatedAt) (meta ^. #passphraseInfo)
, state = ApiT progress
, tip = tip'
}
toApiWalletDelegation
:: W.WalletDelegation
-> TimeInterpreter IO
-> IO ApiWalletDelegation
toApiWalletDelegation W.WalletDelegation{active,next} ti = do
apiNext <- forM next $ \W.WalletDelegationNext{status,changesAt} -> do
info <- interpretQuery ti $ toApiEpochInfo changesAt
return $ toApiWalletDelegationNext (Just info) status
return $ ApiWalletDelegation
{ active = toApiWalletDelegationNext Nothing active
, next = apiNext
}
where
toApiWalletDelegationNext mepochInfo = \case
W.Delegating pid -> ApiWalletDelegationNext
{ status = Delegating
, target = Just (ApiT pid)
, changesAt = mepochInfo
}
W.NotDelegating -> ApiWalletDelegationNext
{ status = NotDelegating
, target = Nothing
, changesAt = mepochInfo
}
--------------------- Shared Wallet
postSharedWallet
:: forall ctx s k n.
( s ~ SharedState n k
, ctx ~ ApiLayer s k
, SoftDerivation k
, MkKeyFingerprint k (Proxy n, k 'AddressK XPub)
, MkKeyFingerprint k Address
, WalletKey k
, HasDBFactory s k ctx
, HasWorkerRegistry s k ctx
, Typeable n
, k ~ SharedKey
)
=> ctx
-> ((SomeMnemonic, Maybe SomeMnemonic) -> Passphrase "encryption" -> k 'RootK XPrv)
-> (XPub -> k 'AccountK XPub)
-> ApiSharedWalletPostData
-> Handler ApiSharedWallet
postSharedWallet ctx generateKey liftKey postData =
case postData of
ApiSharedWalletPostData (Left body) ->
postSharedWalletFromRootXPrv ctx generateKey body
ApiSharedWalletPostData (Right body) ->
postSharedWalletFromAccountXPub ctx liftKey body
postSharedWalletFromRootXPrv
:: forall ctx s k n.
( s ~ SharedState n k
, ctx ~ ApiLayer s k
, SoftDerivation k
, MkKeyFingerprint k (Proxy n, k 'AddressK XPub)
, MkKeyFingerprint k Address
, WalletKey k
, HasDBFactory s k ctx
, HasWorkerRegistry s k ctx
, Typeable n
, k ~ SharedKey
)
=> ctx
-> ((SomeMnemonic, Maybe SomeMnemonic) -> Passphrase "encryption" -> k 'RootK XPrv)
-> ApiSharedWalletPostDataFromMnemonics
-> Handler ApiSharedWallet
postSharedWalletFromRootXPrv ctx generateKey body = do
case validateScriptTemplates accXPub scriptValidation pTemplate dTemplateM of
Left err ->
liftHandler $ throwE $ ErrConstructSharedWalletWrongScriptTemplate err
Right _ -> pure ()
ix' <- liftHandler $ withExceptT ErrConstructSharedWalletInvalidIndex $
W.guardHardIndex ix
let state = mkSharedStateFromRootXPrv (rootXPrv, pwd) ix' g pTemplate dTemplateM
void $ liftHandler $ createWalletWorker @_ @s @k ctx wid
(\wrk -> W.createWallet @(WorkerCtx ctx) @_ @s @k wrk wid wName state)
idleWorker
withWorkerCtx @_ @s @k ctx wid liftE liftE $ \wrk -> liftHandler $
W.attachPrivateKeyFromPwd @_ @s @k wrk wid (rootXPrv, pwd)
fst <$> getWallet ctx (mkSharedWallet @_ @s @k) (ApiT wid)
where
seed = getApiMnemonicT (body ^. #mnemonicSentence)
secondFactor = getApiMnemonicT <$> (body ^. #mnemonicSecondFactor)
pwd = preparePassphrase EncryptWithPBKDF2 $ getApiT (body ^. #passphrase)
rootXPrv = generateKey (seed, secondFactor) pwd
g = defaultAddressPoolGap
ix = getApiT (body ^. #accountIndex)
wid = WalletId $ digest $ publicKey rootXPrv
pTemplate = scriptTemplateFromSelf (getRawKey accXPub) $ body ^. #paymentScriptTemplate
dTemplateM = scriptTemplateFromSelf (getRawKey accXPub) <$> body ^. #delegationScriptTemplate
wName = getApiT (body ^. #name)
accXPub = publicKey $ deriveAccountPrivateKey pwd rootXPrv (Index $ getDerivationIndex ix)
scriptValidation = maybe RecommendedValidation getApiT (body ^. #scriptValidation)
postSharedWalletFromAccountXPub
:: forall ctx s k n.
( s ~ SharedState n k
, ctx ~ ApiLayer s k
, SoftDerivation k
, MkKeyFingerprint k (Proxy n, k 'AddressK XPub)
, MkKeyFingerprint k Address
, WalletKey k
, HasDBFactory s k ctx
, HasWorkerRegistry s k ctx
, Typeable n
, k ~ SharedKey
)
=> ctx
-> (XPub -> k 'AccountK XPub)
-> ApiSharedWalletPostDataFromAccountPubX
-> Handler ApiSharedWallet
postSharedWalletFromAccountXPub ctx liftKey body = do
case validateScriptTemplates (liftKey accXPub) scriptValidation pTemplate dTemplateM of
Left err ->
liftHandler $ throwE $ ErrConstructSharedWalletWrongScriptTemplate err
Right _ -> pure ()
acctIx <- liftHandler $ withExceptT ErrConstructSharedWalletInvalidIndex $
W.guardHardIndex ix
let state = mkSharedStateFromAccountXPub (liftKey accXPub) acctIx g pTemplate dTemplateM
void $ liftHandler $ createWalletWorker @_ @s @k ctx wid
(\wrk -> W.createWallet @(WorkerCtx ctx) @_ @s @k wrk wid wName state)
idleWorker
fst <$> getWallet ctx (mkSharedWallet @_ @s @k) (ApiT wid)
where
g = defaultAddressPoolGap
ix = getApiT (body ^. #accountIndex)
pTemplate = scriptTemplateFromSelf accXPub $ body ^. #paymentScriptTemplate
dTemplateM = scriptTemplateFromSelf accXPub <$> body ^. #delegationScriptTemplate
wName = getApiT (body ^. #name)
(ApiAccountPublicKey accXPubApiT) = body ^. #accountPublicKey
accXPub = getApiT accXPubApiT
wid = WalletId $ digest (liftKey accXPub)
scriptValidation = maybe RecommendedValidation getApiT (body ^. #scriptValidation)
scriptTemplateFromSelf :: XPub -> ApiScriptTemplateEntry -> ScriptTemplate
scriptTemplateFromSelf xpub (ApiScriptTemplateEntry cosigners' template') =
ScriptTemplate cosignersWithoutSelf template'