api.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  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. // NewSignerAPI creates a new API that can be used for Account management.
  180. // ksLocation specifies the directory where to store the password protected private
  181. // key that is generated when a new Account is created.
  182. // noUSB disables USB support that is required to support hardware devices such as
  183. // ledger and trezor.
  184. func NewSignerAPI(chainID int64, ksLocation string, noUSB bool, ui SignerUI, abidb *AbiDb, lightKDF bool) *SignerAPI {
  185. var (
  186. backends []accounts.Backend
  187. n, p = keystore.StandardScryptN, keystore.StandardScryptP
  188. )
  189. if lightKDF {
  190. n, p = keystore.LightScryptN, keystore.LightScryptP
  191. }
  192. // support password based accounts
  193. if len(ksLocation) > 0 {
  194. backends = append(backends, keystore.NewKeyStore(ksLocation, n, p))
  195. }
  196. if !noUSB {
  197. // Start a USB hub for Ledger hardware wallets
  198. if ledgerhub, err := usbwallet.NewLedgerHub(); err != nil {
  199. log.Warn(fmt.Sprintf("Failed to start Ledger hub, disabling: %v", err))
  200. } else {
  201. backends = append(backends, ledgerhub)
  202. log.Debug("Ledger support enabled")
  203. }
  204. // Start a USB hub for Trezor hardware wallets
  205. if trezorhub, err := usbwallet.NewTrezorHub(); err != nil {
  206. log.Warn(fmt.Sprintf("Failed to start Trezor hub, disabling: %v", err))
  207. } else {
  208. backends = append(backends, trezorhub)
  209. log.Debug("Trezor support enabled")
  210. }
  211. }
  212. return &SignerAPI{big.NewInt(chainID), accounts.NewManager(backends...), ui, NewValidator(abidb)}
  213. }
  214. // List returns the set of wallet this signer manages. Each wallet can contain
  215. // multiple accounts.
  216. func (api *SignerAPI) List(ctx context.Context) (Accounts, error) {
  217. var accs []Account
  218. for _, wallet := range api.am.Wallets() {
  219. for _, acc := range wallet.Accounts() {
  220. acc := Account{Typ: "Account", URL: wallet.URL(), Address: acc.Address}
  221. accs = append(accs, acc)
  222. }
  223. }
  224. result, err := api.UI.ApproveListing(&ListRequest{Accounts: accs, Meta: MetadataFromContext(ctx)})
  225. if err != nil {
  226. return nil, err
  227. }
  228. if result.Accounts == nil {
  229. return nil, ErrRequestDenied
  230. }
  231. return result.Accounts, nil
  232. }
  233. // New creates a new password protected Account. The private key is protected with
  234. // the given password. Users are responsible to backup the private key that is stored
  235. // in the keystore location thas was specified when this API was created.
  236. func (api *SignerAPI) New(ctx context.Context) (accounts.Account, error) {
  237. be := api.am.Backends(keystore.KeyStoreType)
  238. if len(be) == 0 {
  239. return accounts.Account{}, errors.New("password based accounts not supported")
  240. }
  241. resp, err := api.UI.ApproveNewAccount(&NewAccountRequest{MetadataFromContext(ctx)})
  242. if err != nil {
  243. return accounts.Account{}, err
  244. }
  245. if !resp.Approved {
  246. return accounts.Account{}, ErrRequestDenied
  247. }
  248. return be[0].(*keystore.KeyStore).NewAccount(resp.Password)
  249. }
  250. // logDiff logs the difference between the incoming (original) transaction and the one returned from the signer.
  251. // it also returns 'true' if the transaction was modified, to make it possible to configure the signer not to allow
  252. // UI-modifications to requests
  253. func logDiff(original *SignTxRequest, new *SignTxResponse) bool {
  254. modified := false
  255. if f0, f1 := original.Transaction.From, new.Transaction.From; !reflect.DeepEqual(f0, f1) {
  256. log.Info("Sender-account changed by UI", "was", f0, "is", f1)
  257. modified = true
  258. }
  259. if t0, t1 := original.Transaction.To, new.Transaction.To; !reflect.DeepEqual(t0, t1) {
  260. log.Info("Recipient-account changed by UI", "was", t0, "is", t1)
  261. modified = true
  262. }
  263. if g0, g1 := original.Transaction.Gas, new.Transaction.Gas; g0 != g1 {
  264. modified = true
  265. log.Info("Gas changed by UI", "was", g0, "is", g1)
  266. }
  267. if g0, g1 := big.Int(original.Transaction.GasPrice), big.Int(new.Transaction.GasPrice); g0.Cmp(&g1) != 0 {
  268. modified = true
  269. log.Info("GasPrice changed by UI", "was", g0, "is", g1)
  270. }
  271. if v0, v1 := big.Int(original.Transaction.Value), big.Int(new.Transaction.Value); v0.Cmp(&v1) != 0 {
  272. modified = true
  273. log.Info("Value changed by UI", "was", v0, "is", v1)
  274. }
  275. if d0, d1 := original.Transaction.Data, new.Transaction.Data; d0 != d1 {
  276. d0s := ""
  277. d1s := ""
  278. if d0 != nil {
  279. d0s = common.ToHex(*d0)
  280. }
  281. if d1 != nil {
  282. d1s = common.ToHex(*d1)
  283. }
  284. if d1s != d0s {
  285. modified = true
  286. log.Info("Data changed by UI", "was", d0s, "is", d1s)
  287. }
  288. }
  289. if n0, n1 := original.Transaction.Nonce, new.Transaction.Nonce; n0 != n1 {
  290. modified = true
  291. log.Info("Nonce changed by UI", "was", n0, "is", n1)
  292. }
  293. return modified
  294. }
  295. // SignTransaction signs the given Transaction and returns it both as json and rlp-encoded form
  296. func (api *SignerAPI) SignTransaction(ctx context.Context, args SendTxArgs, methodSelector *string) (*ethapi.SignTransactionResult, error) {
  297. var (
  298. err error
  299. result SignTxResponse
  300. )
  301. msgs, err := api.validator.ValidateTransaction(&args, methodSelector)
  302. if err != nil {
  303. return nil, err
  304. }
  305. req := SignTxRequest{
  306. Transaction: args,
  307. Meta: MetadataFromContext(ctx),
  308. Callinfo: msgs.Messages,
  309. }
  310. // Process approval
  311. result, err = api.UI.ApproveTx(&req)
  312. if err != nil {
  313. return nil, err
  314. }
  315. if !result.Approved {
  316. return nil, ErrRequestDenied
  317. }
  318. // Log changes made by the UI to the signing-request
  319. logDiff(&req, &result)
  320. var (
  321. acc accounts.Account
  322. wallet accounts.Wallet
  323. )
  324. acc = accounts.Account{Address: result.Transaction.From.Address()}
  325. wallet, err = api.am.Find(acc)
  326. if err != nil {
  327. return nil, err
  328. }
  329. // Convert fields into a real transaction
  330. var unsignedTx = result.Transaction.toTransaction()
  331. // The one to sign is the one that was returned from the UI
  332. signedTx, err := wallet.SignTxWithPassphrase(acc, result.Password, unsignedTx, api.chainID)
  333. if err != nil {
  334. api.UI.ShowError(err.Error())
  335. return nil, err
  336. }
  337. rlpdata, err := rlp.EncodeToBytes(signedTx)
  338. response := ethapi.SignTransactionResult{Raw: rlpdata, Tx: signedTx}
  339. // Finally, send the signed tx to the UI
  340. api.UI.OnApprovedTx(response)
  341. // ...and to the external caller
  342. return &response, nil
  343. }
  344. // Sign calculates an Ethereum ECDSA signature for:
  345. // keccack256("\x19Ethereum Signed Message:\n" + len(message) + message))
  346. //
  347. // Note, the produced signature conforms to the secp256k1 curve R, S and V values,
  348. // where the V value will be 27 or 28 for legacy reasons.
  349. //
  350. // The key used to calculate the signature is decrypted with the given password.
  351. //
  352. // https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal_sign
  353. func (api *SignerAPI) Sign(ctx context.Context, addr common.MixedcaseAddress, data hexutil.Bytes) (hexutil.Bytes, error) {
  354. sighash, msg := SignHash(data)
  355. // We make the request prior to looking up if we actually have the account, to prevent
  356. // account-enumeration via the API
  357. req := &SignDataRequest{Address: addr, Rawdata: data, Message: msg, Hash: sighash, Meta: MetadataFromContext(ctx)}
  358. res, err := api.UI.ApproveSignData(req)
  359. if err != nil {
  360. return nil, err
  361. }
  362. if !res.Approved {
  363. return nil, ErrRequestDenied
  364. }
  365. // Look up the wallet containing the requested signer
  366. account := accounts.Account{Address: addr.Address()}
  367. wallet, err := api.am.Find(account)
  368. if err != nil {
  369. return nil, err
  370. }
  371. // Assemble sign the data with the wallet
  372. signature, err := wallet.SignHashWithPassphrase(account, res.Password, sighash)
  373. if err != nil {
  374. api.UI.ShowError(err.Error())
  375. return nil, err
  376. }
  377. signature[64] += 27 // Transform V from 0/1 to 27/28 according to the yellow paper
  378. return signature, nil
  379. }
  380. // EcRecover returns the address for the Account that was used to create the signature.
  381. // Note, this function is compatible with eth_sign and personal_sign. As such it recovers
  382. // the address of:
  383. // hash = keccak256("\x19Ethereum Signed Message:\n"${message length}${message})
  384. // addr = ecrecover(hash, signature)
  385. //
  386. // Note, the signature must conform to the secp256k1 curve R, S and V values, where
  387. // the V value must be 27 or 28 for legacy reasons.
  388. //
  389. // https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal_ecRecover
  390. func (api *SignerAPI) EcRecover(ctx context.Context, data, sig hexutil.Bytes) (common.Address, error) {
  391. if len(sig) != 65 {
  392. return common.Address{}, fmt.Errorf("signature must be 65 bytes long")
  393. }
  394. if sig[64] != 27 && sig[64] != 28 {
  395. return common.Address{}, fmt.Errorf("invalid Ethereum signature (V is not 27 or 28)")
  396. }
  397. sig[64] -= 27 // Transform yellow paper V from 27/28 to 0/1
  398. hash, _ := SignHash(data)
  399. rpk, err := crypto.SigToPub(hash, sig)
  400. if err != nil {
  401. return common.Address{}, err
  402. }
  403. return crypto.PubkeyToAddress(*rpk), nil
  404. }
  405. // SignHash is a helper function that calculates a hash for the given message that can be
  406. // safely used to calculate a signature from.
  407. //
  408. // The hash is calculated as
  409. // keccak256("\x19Ethereum Signed Message:\n"${message length}${message}).
  410. //
  411. // This gives context to the signed message and prevents signing of transactions.
  412. func SignHash(data []byte) ([]byte, string) {
  413. msg := fmt.Sprintf("\x19Ethereum Signed Message:\n%d%s", len(data), data)
  414. return crypto.Keccak256([]byte(msg)), msg
  415. }
  416. // Export returns encrypted private key associated with the given address in web3 keystore format.
  417. func (api *SignerAPI) Export(ctx context.Context, addr common.Address) (json.RawMessage, error) {
  418. res, err := api.UI.ApproveExport(&ExportRequest{Address: addr, Meta: MetadataFromContext(ctx)})
  419. if err != nil {
  420. return nil, err
  421. }
  422. if !res.Approved {
  423. return nil, ErrRequestDenied
  424. }
  425. // Look up the wallet containing the requested signer
  426. wallet, err := api.am.Find(accounts.Account{Address: addr})
  427. if err != nil {
  428. return nil, err
  429. }
  430. if wallet.URL().Scheme != keystore.KeyStoreScheme {
  431. return nil, fmt.Errorf("Account is not a keystore-account")
  432. }
  433. return ioutil.ReadFile(wallet.URL().Path)
  434. }
  435. // Import tries to import the given keyJSON in the local keystore. The keyJSON data is expected to be
  436. // in web3 keystore format. It will decrypt the keyJSON with the given passphrase and on successful
  437. // decryption it will encrypt the key with the given newPassphrase and store it in the keystore.
  438. func (api *SignerAPI) Import(ctx context.Context, keyJSON json.RawMessage) (Account, error) {
  439. be := api.am.Backends(keystore.KeyStoreType)
  440. if len(be) == 0 {
  441. return Account{}, errors.New("password based accounts not supported")
  442. }
  443. res, err := api.UI.ApproveImport(&ImportRequest{Meta: MetadataFromContext(ctx)})
  444. if err != nil {
  445. return Account{}, err
  446. }
  447. if !res.Approved {
  448. return Account{}, ErrRequestDenied
  449. }
  450. acc, err := be[0].(*keystore.KeyStore).Import(keyJSON, res.OldPassword, res.NewPassword)
  451. if err != nil {
  452. api.UI.ShowError(err.Error())
  453. return Account{}, err
  454. }
  455. return Account{Typ: "Account", URL: acc.URL, Address: acc.Address}, nil
  456. }