api.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. // Copyright 2018 The go-ethereum Authors
  2. // This file is part of go-ethereum.
  3. //
  4. // go-ethereum is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // go-ethereum is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
  16. package core
  17. import (
  18. "context"
  19. "encoding/json"
  20. "errors"
  21. "fmt"
  22. "io/ioutil"
  23. "math/big"
  24. "reflect"
  25. "github.com/ethereum/go-ethereum/accounts"
  26. "github.com/ethereum/go-ethereum/accounts/keystore"
  27. "github.com/ethereum/go-ethereum/accounts/usbwallet"
  28. "github.com/ethereum/go-ethereum/common"
  29. "github.com/ethereum/go-ethereum/common/hexutil"
  30. "github.com/ethereum/go-ethereum/crypto"
  31. "github.com/ethereum/go-ethereum/internal/ethapi"
  32. "github.com/ethereum/go-ethereum/log"
  33. "github.com/ethereum/go-ethereum/rlp"
  34. )
  35. // ExternalAPI defines the external API through which signing requests are made.
  36. type ExternalAPI interface {
  37. // List available accounts
  38. List(ctx context.Context) (Accounts, error)
  39. // New request to create a new account
  40. New(ctx context.Context) (accounts.Account, error)
  41. // SignTransaction request to sign the specified transaction
  42. SignTransaction(ctx context.Context, args SendTxArgs, methodSelector *string) (*ethapi.SignTransactionResult, error)
  43. // Sign - request to sign the given data (plus prefix)
  44. Sign(ctx context.Context, addr common.MixedcaseAddress, data hexutil.Bytes) (hexutil.Bytes, error)
  45. // EcRecover - request to perform ecrecover
  46. EcRecover(ctx context.Context, data, sig hexutil.Bytes) (common.Address, error)
  47. // Export - request to export an account
  48. Export(ctx context.Context, addr common.Address) (json.RawMessage, error)
  49. // Import - request to import an account
  50. Import(ctx context.Context, keyJSON json.RawMessage) (Account, error)
  51. }
  52. // SignerUI specifies what method a UI needs to implement to be able to be used as a UI for the signer
  53. type SignerUI interface {
  54. // ApproveTx prompt the user for confirmation to request to sign Transaction
  55. ApproveTx(request *SignTxRequest) (SignTxResponse, error)
  56. // ApproveSignData prompt the user for confirmation to request to sign data
  57. ApproveSignData(request *SignDataRequest) (SignDataResponse, error)
  58. // ApproveExport prompt the user for confirmation to export encrypted Account json
  59. ApproveExport(request *ExportRequest) (ExportResponse, error)
  60. // ApproveImport prompt the user for confirmation to import Account json
  61. ApproveImport(request *ImportRequest) (ImportResponse, error)
  62. // ApproveListing prompt the user for confirmation to list accounts
  63. // the list of accounts to list can be modified by the UI
  64. ApproveListing(request *ListRequest) (ListResponse, error)
  65. // ApproveNewAccount prompt the user for confirmation to create new Account, and reveal to caller
  66. ApproveNewAccount(request *NewAccountRequest) (NewAccountResponse, error)
  67. // ShowError displays error message to user
  68. ShowError(message string)
  69. // ShowInfo displays info message to user
  70. ShowInfo(message string)
  71. // OnApprovedTx notifies the UI about a transaction having been successfully signed.
  72. // This method can be used by a UI to keep track of e.g. how much has been sent to a particular recipient.
  73. OnApprovedTx(tx ethapi.SignTransactionResult)
  74. // OnSignerStartup is invoked when the signer boots, and tells the UI info about external API location and version
  75. // information
  76. OnSignerStartup(info StartupInfo)
  77. }
  78. // SignerAPI defines the actual implementation of ExternalAPI
  79. type SignerAPI struct {
  80. chainID *big.Int
  81. am *accounts.Manager
  82. UI SignerUI
  83. validator *Validator
  84. }
  85. // Metadata about a request
  86. type Metadata struct {
  87. Remote string `json:"remote"`
  88. Local string `json:"local"`
  89. Scheme string `json:"scheme"`
  90. }
  91. // MetadataFromContext extracts Metadata from a given context.Context
  92. func MetadataFromContext(ctx context.Context) Metadata {
  93. m := Metadata{"NA", "NA", "NA"} // batman
  94. if v := ctx.Value("remote"); v != nil {
  95. m.Remote = v.(string)
  96. }
  97. if v := ctx.Value("scheme"); v != nil {
  98. m.Scheme = v.(string)
  99. }
  100. if v := ctx.Value("local"); v != nil {
  101. m.Local = v.(string)
  102. }
  103. return m
  104. }
  105. // String implements Stringer interface
  106. func (m Metadata) String() string {
  107. s, err := json.Marshal(m)
  108. if err == nil {
  109. return string(s)
  110. }
  111. return err.Error()
  112. }
  113. // types for the requests/response types between signer and UI
  114. type (
  115. // SignTxRequest contains info about a Transaction to sign
  116. SignTxRequest struct {
  117. Transaction SendTxArgs `json:"transaction"`
  118. Callinfo []ValidationInfo `json:"call_info"`
  119. Meta Metadata `json:"meta"`
  120. }
  121. // SignTxResponse result from SignTxRequest
  122. SignTxResponse struct {
  123. //The UI may make changes to the TX
  124. Transaction SendTxArgs `json:"transaction"`
  125. Approved bool `json:"approved"`
  126. Password string `json:"password"`
  127. }
  128. // ExportRequest info about query to export accounts
  129. ExportRequest struct {
  130. Address common.Address `json:"address"`
  131. Meta Metadata `json:"meta"`
  132. }
  133. // ExportResponse response to export-request
  134. ExportResponse struct {
  135. Approved bool `json:"approved"`
  136. }
  137. // ImportRequest info about request to import an Account
  138. ImportRequest struct {
  139. Meta Metadata `json:"meta"`
  140. }
  141. ImportResponse struct {
  142. Approved bool `json:"approved"`
  143. OldPassword string `json:"old_password"`
  144. NewPassword string `json:"new_password"`
  145. }
  146. SignDataRequest struct {
  147. Address common.MixedcaseAddress `json:"address"`
  148. Rawdata hexutil.Bytes `json:"raw_data"`
  149. Message string `json:"message"`
  150. Hash hexutil.Bytes `json:"hash"`
  151. Meta Metadata `json:"meta"`
  152. }
  153. SignDataResponse struct {
  154. Approved bool `json:"approved"`
  155. Password string
  156. }
  157. NewAccountRequest struct {
  158. Meta Metadata `json:"meta"`
  159. }
  160. NewAccountResponse struct {
  161. Approved bool `json:"approved"`
  162. Password string `json:"password"`
  163. }
  164. ListRequest struct {
  165. Accounts []Account `json:"accounts"`
  166. Meta Metadata `json:"meta"`
  167. }
  168. ListResponse struct {
  169. Accounts []Account `json:"accounts"`
  170. }
  171. Message struct {
  172. Text string `json:"text"`
  173. }
  174. StartupInfo struct {
  175. Info map[string]interface{} `json:"info"`
  176. }
  177. )
  178. var ErrRequestDenied = errors.New("Request denied")
  179. type errorWrapper struct {
  180. msg string
  181. err error
  182. }
  183. func (ew errorWrapper) String() string {
  184. return fmt.Sprintf("%s\n%s", ew.msg, ew.err)
  185. }
  186. // NewSignerAPI creates a new API that can be used for Account management.
  187. // ksLocation specifies the directory where to store the password protected private
  188. // key that is generated when a new Account is created.
  189. // noUSB disables USB support that is required to support hardware devices such as
  190. // ledger and trezor.
  191. func NewSignerAPI(chainID int64, ksLocation string, noUSB bool, ui SignerUI, abidb *AbiDb, lightKDF bool) *SignerAPI {
  192. var (
  193. backends []accounts.Backend
  194. n, p = keystore.StandardScryptN, keystore.StandardScryptP
  195. )
  196. if lightKDF {
  197. n, p = keystore.LightScryptN, keystore.LightScryptP
  198. }
  199. // support password based accounts
  200. if len(ksLocation) > 0 {
  201. backends = append(backends, keystore.NewKeyStore(ksLocation, n, p))
  202. }
  203. if !noUSB {
  204. // Start a USB hub for Ledger hardware wallets
  205. if ledgerhub, err := usbwallet.NewLedgerHub(); err != nil {
  206. log.Warn(fmt.Sprintf("Failed to start Ledger hub, disabling: %v", err))
  207. } else {
  208. backends = append(backends, ledgerhub)
  209. log.Debug("Ledger support enabled")
  210. }
  211. // Start a USB hub for Trezor hardware wallets
  212. if trezorhub, err := usbwallet.NewTrezorHub(); err != nil {
  213. log.Warn(fmt.Sprintf("Failed to start Trezor hub, disabling: %v", err))
  214. } else {
  215. backends = append(backends, trezorhub)
  216. log.Debug("Trezor support enabled")
  217. }
  218. }
  219. return &SignerAPI{big.NewInt(chainID), accounts.NewManager(backends...), ui, NewValidator(abidb)}
  220. }
  221. // List returns the set of wallet this signer manages. Each wallet can contain
  222. // multiple accounts.
  223. func (api *SignerAPI) List(ctx context.Context) (Accounts, error) {
  224. var accs []Account
  225. for _, wallet := range api.am.Wallets() {
  226. for _, acc := range wallet.Accounts() {
  227. acc := Account{Typ: "Account", URL: wallet.URL(), Address: acc.Address}
  228. accs = append(accs, acc)
  229. }
  230. }
  231. result, err := api.UI.ApproveListing(&ListRequest{Accounts: accs, Meta: MetadataFromContext(ctx)})
  232. if err != nil {
  233. return nil, err
  234. }
  235. if result.Accounts == nil {
  236. return nil, ErrRequestDenied
  237. }
  238. return result.Accounts, nil
  239. }
  240. // New creates a new password protected Account. The private key is protected with
  241. // the given password. Users are responsible to backup the private key that is stored
  242. // in the keystore location thas was specified when this API was created.
  243. func (api *SignerAPI) New(ctx context.Context) (accounts.Account, error) {
  244. be := api.am.Backends(keystore.KeyStoreType)
  245. if len(be) == 0 {
  246. return accounts.Account{}, errors.New("password based accounts not supported")
  247. }
  248. resp, err := api.UI.ApproveNewAccount(&NewAccountRequest{MetadataFromContext(ctx)})
  249. if err != nil {
  250. return accounts.Account{}, err
  251. }
  252. if !resp.Approved {
  253. return accounts.Account{}, ErrRequestDenied
  254. }
  255. return be[0].(*keystore.KeyStore).NewAccount(resp.Password)
  256. }
  257. // logDiff logs the difference between the incoming (original) transaction and the one returned from the signer.
  258. // it also returns 'true' if the transaction was modified, to make it possible to configure the signer not to allow
  259. // UI-modifications to requests
  260. func logDiff(original *SignTxRequest, new *SignTxResponse) bool {
  261. modified := false
  262. if f0, f1 := original.Transaction.From, new.Transaction.From; !reflect.DeepEqual(f0, f1) {
  263. log.Info("Sender-account changed by UI", "was", f0, "is", f1)
  264. modified = true
  265. }
  266. if t0, t1 := original.Transaction.To, new.Transaction.To; !reflect.DeepEqual(t0, t1) {
  267. log.Info("Recipient-account changed by UI", "was", t0, "is", t1)
  268. modified = true
  269. }
  270. if g0, g1 := original.Transaction.Gas, new.Transaction.Gas; g0 != g1 {
  271. modified = true
  272. log.Info("Gas changed by UI", "was", g0, "is", g1)
  273. }
  274. if g0, g1 := big.Int(original.Transaction.GasPrice), big.Int(new.Transaction.GasPrice); g0.Cmp(&g1) != 0 {
  275. modified = true
  276. log.Info("GasPrice changed by UI", "was", g0, "is", g1)
  277. }
  278. if v0, v1 := big.Int(original.Transaction.Value), big.Int(new.Transaction.Value); v0.Cmp(&v1) != 0 {
  279. modified = true
  280. log.Info("Value changed by UI", "was", v0, "is", v1)
  281. }
  282. if d0, d1 := original.Transaction.Data, new.Transaction.Data; d0 != d1 {
  283. d0s := ""
  284. d1s := ""
  285. if d0 != nil {
  286. d0s = common.ToHex(*d0)
  287. }
  288. if d1 != nil {
  289. d1s = common.ToHex(*d1)
  290. }
  291. if d1s != d0s {
  292. modified = true
  293. log.Info("Data changed by UI", "was", d0s, "is", d1s)
  294. }
  295. }
  296. if n0, n1 := original.Transaction.Nonce, new.Transaction.Nonce; n0 != n1 {
  297. modified = true
  298. log.Info("Nonce changed by UI", "was", n0, "is", n1)
  299. }
  300. return modified
  301. }
  302. // SignTransaction signs the given Transaction and returns it both as json and rlp-encoded form
  303. func (api *SignerAPI) SignTransaction(ctx context.Context, args SendTxArgs, methodSelector *string) (*ethapi.SignTransactionResult, error) {
  304. var (
  305. err error
  306. result SignTxResponse
  307. )
  308. msgs, err := api.validator.ValidateTransaction(&args, methodSelector)
  309. if err != nil {
  310. return nil, err
  311. }
  312. req := SignTxRequest{
  313. Transaction: args,
  314. Meta: MetadataFromContext(ctx),
  315. Callinfo: msgs.Messages,
  316. }
  317. // Process approval
  318. result, err = api.UI.ApproveTx(&req)
  319. if err != nil {
  320. return nil, err
  321. }
  322. if !result.Approved {
  323. return nil, ErrRequestDenied
  324. }
  325. // Log changes made by the UI to the signing-request
  326. logDiff(&req, &result)
  327. var (
  328. acc accounts.Account
  329. wallet accounts.Wallet
  330. )
  331. acc = accounts.Account{Address: result.Transaction.From.Address()}
  332. wallet, err = api.am.Find(acc)
  333. if err != nil {
  334. return nil, err
  335. }
  336. // Convert fields into a real transaction
  337. var unsignedTx = result.Transaction.toTransaction()
  338. // The one to sign is the one that was returned from the UI
  339. signedTx, err := wallet.SignTxWithPassphrase(acc, result.Password, unsignedTx, api.chainID)
  340. if err != nil {
  341. api.UI.ShowError(err.Error())
  342. return nil, err
  343. }
  344. rlpdata, err := rlp.EncodeToBytes(signedTx)
  345. response := ethapi.SignTransactionResult{Raw: rlpdata, Tx: signedTx}
  346. // Finally, send the signed tx to the UI
  347. api.UI.OnApprovedTx(response)
  348. // ...and to the external caller
  349. return &response, nil
  350. }
  351. // Sign calculates an Ethereum ECDSA signature for:
  352. // keccack256("\x19Ethereum Signed Message:\n" + len(message) + message))
  353. //
  354. // Note, the produced signature conforms to the secp256k1 curve R, S and V values,
  355. // where the V value will be 27 or 28 for legacy reasons.
  356. //
  357. // The key used to calculate the signature is decrypted with the given password.
  358. //
  359. // https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal_sign
  360. func (api *SignerAPI) Sign(ctx context.Context, addr common.MixedcaseAddress, data hexutil.Bytes) (hexutil.Bytes, error) {
  361. sighash, msg := SignHash(data)
  362. // We make the request prior to looking up if we actually have the account, to prevent
  363. // account-enumeration via the API
  364. req := &SignDataRequest{Address: addr, Rawdata: data, Message: msg, Hash: sighash, Meta: MetadataFromContext(ctx)}
  365. res, err := api.UI.ApproveSignData(req)
  366. if err != nil {
  367. return nil, err
  368. }
  369. if !res.Approved {
  370. return nil, ErrRequestDenied
  371. }
  372. // Look up the wallet containing the requested signer
  373. account := accounts.Account{Address: addr.Address()}
  374. wallet, err := api.am.Find(account)
  375. if err != nil {
  376. return nil, err
  377. }
  378. // Assemble sign the data with the wallet
  379. signature, err := wallet.SignHashWithPassphrase(account, res.Password, sighash)
  380. if err != nil {
  381. api.UI.ShowError(err.Error())
  382. return nil, err
  383. }
  384. signature[64] += 27 // Transform V from 0/1 to 27/28 according to the yellow paper
  385. return signature, nil
  386. }
  387. // EcRecover returns the address for the Account that was used to create the signature.
  388. // Note, this function is compatible with eth_sign and personal_sign. As such it recovers
  389. // the address of:
  390. // hash = keccak256("\x19Ethereum Signed Message:\n"${message length}${message})
  391. // addr = ecrecover(hash, signature)
  392. //
  393. // Note, the signature must conform to the secp256k1 curve R, S and V values, where
  394. // the V value must be be 27 or 28 for legacy reasons.
  395. //
  396. // https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal_ecRecover
  397. func (api *SignerAPI) EcRecover(ctx context.Context, data, sig hexutil.Bytes) (common.Address, error) {
  398. if len(sig) != 65 {
  399. return common.Address{}, fmt.Errorf("signature must be 65 bytes long")
  400. }
  401. if sig[64] != 27 && sig[64] != 28 {
  402. return common.Address{}, fmt.Errorf("invalid Ethereum signature (V is not 27 or 28)")
  403. }
  404. sig[64] -= 27 // Transform yellow paper V from 27/28 to 0/1
  405. hash, _ := SignHash(data)
  406. rpk, err := crypto.Ecrecover(hash, sig)
  407. if err != nil {
  408. return common.Address{}, err
  409. }
  410. pubKey := crypto.ToECDSAPub(rpk)
  411. recoveredAddr := crypto.PubkeyToAddress(*pubKey)
  412. return recoveredAddr, nil
  413. }
  414. // SignHash is a helper function that calculates a hash for the given message that can be
  415. // safely used to calculate a signature from.
  416. //
  417. // The hash is calculated as
  418. // keccak256("\x19Ethereum Signed Message:\n"${message length}${message}).
  419. //
  420. // This gives context to the signed message and prevents signing of transactions.
  421. func SignHash(data []byte) ([]byte, string) {
  422. msg := fmt.Sprintf("\x19Ethereum Signed Message:\n%d%s", len(data), data)
  423. return crypto.Keccak256([]byte(msg)), msg
  424. }
  425. // Export returns encrypted private key associated with the given address in web3 keystore format.
  426. func (api *SignerAPI) Export(ctx context.Context, addr common.Address) (json.RawMessage, error) {
  427. res, err := api.UI.ApproveExport(&ExportRequest{Address: addr, Meta: MetadataFromContext(ctx)})
  428. if err != nil {
  429. return nil, err
  430. }
  431. if !res.Approved {
  432. return nil, ErrRequestDenied
  433. }
  434. // Look up the wallet containing the requested signer
  435. wallet, err := api.am.Find(accounts.Account{Address: addr})
  436. if err != nil {
  437. return nil, err
  438. }
  439. if wallet.URL().Scheme != keystore.KeyStoreScheme {
  440. return nil, fmt.Errorf("Account is not a keystore-account")
  441. }
  442. return ioutil.ReadFile(wallet.URL().Path)
  443. }
  444. // Import tries to import the given keyJSON in the local keystore. The keyJSON data is expected to be
  445. // in web3 keystore format. It will decrypt the keyJSON with the given passphrase and on successful
  446. // decryption it will encrypt the key with the given newPassphrase and store it in the keystore.
  447. func (api *SignerAPI) Import(ctx context.Context, keyJSON json.RawMessage) (Account, error) {
  448. be := api.am.Backends(keystore.KeyStoreType)
  449. if len(be) == 0 {
  450. return Account{}, errors.New("password based accounts not supported")
  451. }
  452. res, err := api.UI.ApproveImport(&ImportRequest{Meta: MetadataFromContext(ctx)})
  453. if err != nil {
  454. return Account{}, err
  455. }
  456. if !res.Approved {
  457. return Account{}, ErrRequestDenied
  458. }
  459. acc, err := be[0].(*keystore.KeyStore).Import(keyJSON, res.OldPassword, res.NewPassword)
  460. if err != nil {
  461. api.UI.ShowError(err.Error())
  462. return Account{}, err
  463. }
  464. return Account{Typ: "Account", URL: acc.URL, Address: acc.Address}, nil
  465. }