@@ -21,7 +21,6 @@ import (
2121 "encoding/json"
2222 "errors"
2323 "fmt"
24- "io/ioutil"
2524 "math/big"
2625 "reflect"
2726
@@ -39,17 +38,17 @@ const (
3938 // numberOfAccountsToDerive For hardware wallets, the number of accounts to derive
4039 numberOfAccountsToDerive = 10
4140 // ExternalAPIVersion -- see extapi_changelog.md
42- ExternalAPIVersion = "5 .0.0"
41+ ExternalAPIVersion = "6 .0.0"
4342 // InternalAPIVersion -- see intapi_changelog.md
44- InternalAPIVersion = "3.2 .0"
43+ InternalAPIVersion = "4.0 .0"
4544)
4645
4746// ExternalAPI defines the external API through which signing requests are made.
4847type ExternalAPI interface {
4948 // List available accounts
5049 List (ctx context.Context ) ([]common.Address , error )
5150 // New request to create a new account
52- New (ctx context.Context ) (accounts. Account , error )
51+ New (ctx context.Context ) (common. Address , error )
5352 // SignTransaction request to sign the specified transaction
5453 SignTransaction (ctx context.Context , args SendTxArgs , methodSelector * string ) (* ethapi.SignTransactionResult , error )
5554 // SignData - request to sign the given data (plus prefix)
@@ -58,17 +57,13 @@ type ExternalAPI interface {
5857 SignTypedData (ctx context.Context , addr common.MixedcaseAddress , data TypedData ) (hexutil.Bytes , error )
5958 // EcRecover - recover public key from given message and signature
6059 EcRecover (ctx context.Context , data hexutil.Bytes , sig hexutil.Bytes ) (common.Address , error )
61- // Export - request to export an account
62- Export (ctx context.Context , addr common.Address ) (json.RawMessage , error )
63- // Import - request to import an account
64- // Should be moved to Internal API, in next phase when we have
65- // bi-directional communication
66- //Import(ctx context.Context, keyJSON json.RawMessage) (Account, error)
60+ // Version info about the APIs
6761 Version (ctx context.Context ) (string , error )
6862}
6963
70- // SignerUI specifies what method a UI needs to implement to be able to be used as a UI for the signer
71- type SignerUI interface {
64+ // UIClientAPI specifies what method a UI needs to implement to be able to be used as a
65+ // UI for the signer
66+ type UIClientAPI interface {
7267 // ApproveTx prompt the user for confirmation to request to sign Transaction
7368 ApproveTx (request * SignTxRequest ) (SignTxResponse , error )
7469 // ApproveSignData prompt the user for confirmation to request to sign data
@@ -95,13 +90,15 @@ type SignerUI interface {
9590 // OnInputRequired is invoked when clef requires user input, for example master password or
9691 // pin-code for unlocking hardware wallets
9792 OnInputRequired (info UserInputRequest ) (UserInputResponse , error )
93+ // RegisterUIServer tells the UI to use the given UIServerAPI for ui->clef communication
94+ RegisterUIServer (api * UIServerAPI )
9895}
9996
10097// SignerAPI defines the actual implementation of ExternalAPI
10198type SignerAPI struct {
10299 chainID * big.Int
103100 am * accounts.Manager
104- UI SignerUI
101+ UI UIClientAPI
105102 validator * Validator
106103 rejectMode bool
107104}
@@ -115,6 +112,37 @@ type Metadata struct {
115112 Origin string `json:"Origin"`
116113}
117114
115+ func StartClefAccountManager (ksLocation string , nousb , lightKDF bool ) * accounts.Manager {
116+ var (
117+ backends []accounts.Backend
118+ n , p = keystore .StandardScryptN , keystore .StandardScryptP
119+ )
120+ if lightKDF {
121+ n , p = keystore .LightScryptN , keystore .LightScryptP
122+ }
123+ // support password based accounts
124+ if len (ksLocation ) > 0 {
125+ backends = append (backends , keystore .NewKeyStore (ksLocation , n , p ))
126+ }
127+ if ! nousb {
128+ // Start a USB hub for Ledger hardware wallets
129+ if ledgerhub , err := usbwallet .NewLedgerHub (); err != nil {
130+ log .Warn (fmt .Sprintf ("Failed to start Ledger hub, disabling: %v" , err ))
131+ } else {
132+ backends = append (backends , ledgerhub )
133+ log .Debug ("Ledger support enabled" )
134+ }
135+ // Start a USB hub for Trezor hardware wallets
136+ if trezorhub , err := usbwallet .NewTrezorHub (); err != nil {
137+ log .Warn (fmt .Sprintf ("Failed to start Trezor hub, disabling: %v" , err ))
138+ } else {
139+ backends = append (backends , trezorhub )
140+ log .Debug ("Trezor support enabled" )
141+ }
142+ }
143+ return accounts .NewManager (backends ... )
144+ }
145+
118146// MetadataFromContext extracts Metadata from a given context.Context
119147func MetadataFromContext (ctx context.Context ) Metadata {
120148 m := Metadata {"NA" , "NA" , "NA" , "" , "" } // batman
@@ -199,11 +227,11 @@ type (
199227 Password string `json:"password"`
200228 }
201229 ListRequest struct {
202- Accounts []Account `json:"accounts"`
203- Meta Metadata `json:"meta"`
230+ Accounts []accounts. Account `json:"accounts"`
231+ Meta Metadata `json:"meta"`
204232 }
205233 ListResponse struct {
206- Accounts []Account `json:"accounts"`
234+ Accounts []accounts. Account `json:"accounts"`
207235 }
208236 Message struct {
209237 Text string `json:"text"`
@@ -234,38 +262,11 @@ var ErrRequestDenied = errors.New("Request denied")
234262// key that is generated when a new Account is created.
235263// noUSB disables USB support that is required to support hardware devices such as
236264// ledger and trezor.
237- func NewSignerAPI (chainID int64 , ksLocation string , noUSB bool , ui SignerUI , abidb * AbiDb , lightKDF bool , advancedMode bool ) * SignerAPI {
238- var (
239- backends []accounts.Backend
240- n , p = keystore .StandardScryptN , keystore .StandardScryptP
241- )
242- if lightKDF {
243- n , p = keystore .LightScryptN , keystore .LightScryptP
244- }
245- // support password based accounts
246- if len (ksLocation ) > 0 {
247- backends = append (backends , keystore .NewKeyStore (ksLocation , n , p ))
248- }
265+ func NewSignerAPI (am * accounts.Manager , chainID int64 , noUSB bool , ui UIClientAPI , abidb * AbiDb , advancedMode bool ) * SignerAPI {
249266 if advancedMode {
250267 log .Info ("Clef is in advanced mode: will warn instead of reject" )
251268 }
252- if ! noUSB {
253- // Start a USB hub for Ledger hardware wallets
254- if ledgerhub , err := usbwallet .NewLedgerHub (); err != nil {
255- log .Warn (fmt .Sprintf ("Failed to start Ledger hub, disabling: %v" , err ))
256- } else {
257- backends = append (backends , ledgerhub )
258- log .Debug ("Ledger support enabled" )
259- }
260- // Start a USB hub for Trezor hardware wallets
261- if trezorhub , err := usbwallet .NewTrezorHub (); err != nil {
262- log .Warn (fmt .Sprintf ("Failed to start Trezor hub, disabling: %v" , err ))
263- } else {
264- backends = append (backends , trezorhub )
265- log .Debug ("Trezor support enabled" )
266- }
267- }
268- signer := & SignerAPI {big .NewInt (chainID ), accounts .NewManager (backends ... ), ui , NewValidator (abidb ), ! advancedMode }
269+ signer := & SignerAPI {big .NewInt (chainID ), am , ui , NewValidator (abidb ), ! advancedMode }
269270 if ! noUSB {
270271 signer .startUSBListener ()
271272 }
@@ -358,12 +359,9 @@ func (api *SignerAPI) startUSBListener() {
358359// List returns the set of wallet this signer manages. Each wallet can contain
359360// multiple accounts.
360361func (api * SignerAPI ) List (ctx context.Context ) ([]common.Address , error ) {
361- var accs []Account
362+ var accs []accounts. Account
362363 for _ , wallet := range api .am .Wallets () {
363- for _ , acc := range wallet .Accounts () {
364- acc := Account {Typ : "Account" , URL : wallet .URL (), Address : acc .Address }
365- accs = append (accs , acc )
366- }
364+ accs = append (accs , wallet .Accounts ()... )
367365 }
368366 result , err := api .UI .ApproveListing (& ListRequest {Accounts : accs , Meta : MetadataFromContext (ctx )})
369367 if err != nil {
@@ -373,7 +371,6 @@ func (api *SignerAPI) List(ctx context.Context) ([]common.Address, error) {
373371 return nil , ErrRequestDenied
374372
375373 }
376-
377374 addresses := make ([]common.Address , 0 )
378375 for _ , acc := range result .Accounts {
379376 addresses = append (addresses , acc .Address )
@@ -385,10 +382,10 @@ func (api *SignerAPI) List(ctx context.Context) ([]common.Address, error) {
385382// New creates a new password protected Account. The private key is protected with
386383// the given password. Users are responsible to backup the private key that is stored
387384// in the keystore location thas was specified when this API was created.
388- func (api * SignerAPI ) New (ctx context.Context ) (accounts. Account , error ) {
385+ func (api * SignerAPI ) New (ctx context.Context ) (common. Address , error ) {
389386 be := api .am .Backends (keystore .KeyStoreType )
390387 if len (be ) == 0 {
391- return accounts. Account {}, errors .New ("password based accounts not supported" )
388+ return common. Address {}, errors .New ("password based accounts not supported" )
392389 }
393390 var (
394391 resp NewAccountResponse
@@ -398,20 +395,21 @@ func (api *SignerAPI) New(ctx context.Context) (accounts.Account, error) {
398395 for i := 0 ; i < 3 ; i ++ {
399396 resp , err = api .UI .ApproveNewAccount (& NewAccountRequest {MetadataFromContext (ctx )})
400397 if err != nil {
401- return accounts. Account {}, err
398+ return common. Address {}, err
402399 }
403400 if ! resp .Approved {
404- return accounts. Account {}, ErrRequestDenied
401+ return common. Address {}, ErrRequestDenied
405402 }
406403 if pwErr := ValidatePasswordFormat (resp .Password ); pwErr != nil {
407404 api .UI .ShowError (fmt .Sprintf ("Account creation attempt #%d failed due to password requirements: %v" , (i + 1 ), pwErr ))
408405 } else {
409406 // No error
410- return be [0 ].(* keystore.KeyStore ).NewAccount (resp .Password )
407+ acc , err := be [0 ].(* keystore.KeyStore ).NewAccount (resp .Password )
408+ return acc .Address , err
411409 }
412410 }
413411 // Otherwise fail, with generic error message
414- return accounts. Account {}, errors .New ("account creation failed" )
412+ return common. Address {}, errors .New ("account creation failed" )
415413}
416414
417415// logDiff logs the difference between the incoming (original) transaction and the one returned from the signer.
@@ -521,57 +519,6 @@ func (api *SignerAPI) SignTransaction(ctx context.Context, args SendTxArgs, meth
521519
522520}
523521
524- // Export returns encrypted private key associated with the given address in web3 keystore format.
525- func (api * SignerAPI ) Export (ctx context.Context , addr common.Address ) (json.RawMessage , error ) {
526- res , err := api .UI .ApproveExport (& ExportRequest {Address : addr , Meta : MetadataFromContext (ctx )})
527-
528- if err != nil {
529- return nil , err
530- }
531- if ! res .Approved {
532- return nil , ErrRequestDenied
533- }
534- // Look up the wallet containing the requested signer
535- wallet , err := api .am .Find (accounts.Account {Address : addr })
536- if err != nil {
537- return nil , err
538- }
539- if wallet .URL ().Scheme != keystore .KeyStoreScheme {
540- return nil , fmt .Errorf ("Account is not a keystore-account" )
541- }
542- return ioutil .ReadFile (wallet .URL ().Path )
543- }
544-
545- // Import tries to import the given keyJSON in the local keystore. The keyJSON data is expected to be
546- // in web3 keystore format. It will decrypt the keyJSON with the given passphrase and on successful
547- // decryption it will encrypt the key with the given newPassphrase and store it in the keystore.
548- // OBS! This method is removed from the public API. It should not be exposed on the external API
549- // for a couple of reasons:
550- // 1. Even though it is encrypted, it should still be seen as sensitive data
551- // 2. It can be used to DoS clef, by using malicious data with e.g. extreme large
552- // values for the kdfparams.
553- func (api * SignerAPI ) Import (ctx context.Context , keyJSON json.RawMessage ) (Account , error ) {
554- be := api .am .Backends (keystore .KeyStoreType )
555-
556- if len (be ) == 0 {
557- return Account {}, errors .New ("password based accounts not supported" )
558- }
559- res , err := api .UI .ApproveImport (& ImportRequest {Meta : MetadataFromContext (ctx )})
560-
561- if err != nil {
562- return Account {}, err
563- }
564- if ! res .Approved {
565- return Account {}, ErrRequestDenied
566- }
567- acc , err := be [0 ].(* keystore.KeyStore ).Import (keyJSON , res .OldPassword , res .NewPassword )
568- if err != nil {
569- api .UI .ShowError (err .Error ())
570- return Account {}, err
571- }
572- return Account {Typ : "Account" , URL : acc .URL , Address : acc .Address }, nil
573- }
574-
575522// Returns the external api version. This method does not require user acceptance. Available methods are
576523// available via enumeration anyway, and this info does not contain user-specific data
577524func (api * SignerAPI ) Version (ctx context.Context ) (string , error ) {
0 commit comments