accounts.go 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. // Copyright 2017 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser 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. // The go-ethereum library 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 Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. // Package accounts implements high level Ethereum account management.
  17. package accounts
  18. import (
  19. "fmt"
  20. "math/big"
  21. "github.com/ethereum/go-ethereum"
  22. "github.com/ethereum/go-ethereum/common"
  23. "github.com/ethereum/go-ethereum/core/types"
  24. "github.com/ethereum/go-ethereum/event"
  25. "golang.org/x/crypto/sha3"
  26. )
  27. // Account represents an Ethereum account located at a specific location defined
  28. // by the optional URL field.
  29. type Account struct {
  30. Address common.Address `json:"address"` // Ethereum account address derived from the key
  31. URL URL `json:"url"` // Optional resource locator within a backend
  32. }
  33. const (
  34. MimetypeDataWithValidator = "data/validator"
  35. MimetypeTypedData = "data/typed"
  36. MimetypeClique = "application/x-clique-header"
  37. MimetypeTextPlain = "text/plain"
  38. )
  39. // Wallet represents a software or hardware wallet that might contain one or more
  40. // accounts (derived from the same seed).
  41. type Wallet interface {
  42. // URL retrieves the canonical path under which this wallet is reachable. It is
  43. // user by upper layers to define a sorting order over all wallets from multiple
  44. // backends.
  45. URL() URL
  46. // Status returns a textual status to aid the user in the current state of the
  47. // wallet. It also returns an error indicating any failure the wallet might have
  48. // encountered.
  49. Status() (string, error)
  50. // Open initializes access to a wallet instance. It is not meant to unlock or
  51. // decrypt account keys, rather simply to establish a connection to hardware
  52. // wallets and/or to access derivation seeds.
  53. //
  54. // The passphrase parameter may or may not be used by the implementation of a
  55. // particular wallet instance. The reason there is no passwordless open method
  56. // is to strive towards a uniform wallet handling, oblivious to the different
  57. // backend providers.
  58. //
  59. // Please note, if you open a wallet, you must close it to release any allocated
  60. // resources (especially important when working with hardware wallets).
  61. Open(passphrase string) error
  62. // Close releases any resources held by an open wallet instance.
  63. Close() error
  64. // Accounts retrieves the list of signing accounts the wallet is currently aware
  65. // of. For hierarchical deterministic wallets, the list will not be exhaustive,
  66. // rather only contain the accounts explicitly pinned during account derivation.
  67. Accounts() []Account
  68. // Contains returns whether an account is part of this particular wallet or not.
  69. Contains(account Account) bool
  70. // Derive attempts to explicitly derive a hierarchical deterministic account at
  71. // the specified derivation path. If requested, the derived account will be added
  72. // to the wallet's tracked account list.
  73. Derive(path DerivationPath, pin bool) (Account, error)
  74. // SelfDerive sets a base account derivation path from which the wallet attempts
  75. // to discover non zero accounts and automatically add them to list of tracked
  76. // accounts.
  77. //
  78. // Note, self derivation will increment the last component of the specified path
  79. // opposed to decending into a child path to allow discovering accounts starting
  80. // from non zero components.
  81. //
  82. // Some hardware wallets switched derivation paths through their evolution, so
  83. // this method supports providing multiple bases to discover old user accounts
  84. // too. Only the last base will be used to derive the next empty account.
  85. //
  86. // You can disable automatic account discovery by calling SelfDerive with a nil
  87. // chain state reader.
  88. SelfDerive(bases []DerivationPath, chain ethereum.ChainStateReader)
  89. // SignData requests the wallet to sign the hash of the given data
  90. // It looks up the account specified either solely via its address contained within,
  91. // or optionally with the aid of any location metadata from the embedded URL field.
  92. //
  93. // If the wallet requires additional authentication to sign the request (e.g.
  94. // a password to decrypt the account, or a PIN code o verify the transaction),
  95. // an AuthNeededError instance will be returned, containing infos for the user
  96. // about which fields or actions are needed. The user may retry by providing
  97. // the needed details via SignDataWithPassphrase, or by other means (e.g. unlock
  98. // the account in a keystore).
  99. SignData(account Account, mimeType string, data []byte) ([]byte, error)
  100. // SignDataWithPassphrase is identical to SignData, but also takes a password
  101. // NOTE: there's a chance that an erroneous call might mistake the two strings, and
  102. // supply password in the mimetype field, or vice versa. Thus, an implementation
  103. // should never echo the mimetype or return the mimetype in the error-response
  104. SignDataWithPassphrase(account Account, passphrase, mimeType string, data []byte) ([]byte, error)
  105. // SignText requests the wallet to sign the hash of a given piece of data, prefixed
  106. // by the Ethereum prefix scheme
  107. // It looks up the account specified either solely via its address contained within,
  108. // or optionally with the aid of any location metadata from the embedded URL field.
  109. //
  110. // If the wallet requires additional authentication to sign the request (e.g.
  111. // a password to decrypt the account, or a PIN code o verify the transaction),
  112. // an AuthNeededError instance will be returned, containing infos for the user
  113. // about which fields or actions are needed. The user may retry by providing
  114. // the needed details via SignTextWithPassphrase, or by other means (e.g. unlock
  115. // the account in a keystore).
  116. //
  117. // This method should return the signature in 'canonical' format, with v 0 or 1
  118. SignText(account Account, text []byte) ([]byte, error)
  119. // SignTextWithPassphrase is identical to Signtext, but also takes a password
  120. SignTextWithPassphrase(account Account, passphrase string, hash []byte) ([]byte, error)
  121. // SignTx requests the wallet to sign the given transaction.
  122. //
  123. // It looks up the account specified either solely via its address contained within,
  124. // or optionally with the aid of any location metadata from the embedded URL field.
  125. //
  126. // If the wallet requires additional authentication to sign the request (e.g.
  127. // a password to decrypt the account, or a PIN code to verify the transaction),
  128. // an AuthNeededError instance will be returned, containing infos for the user
  129. // about which fields or actions are needed. The user may retry by providing
  130. // the needed details via SignTxWithPassphrase, or by other means (e.g. unlock
  131. // the account in a keystore).
  132. SignTx(account Account, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error)
  133. // SignTxWithPassphrase is identical to SignTx, but also takes a password
  134. SignTxWithPassphrase(account Account, passphrase string, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error)
  135. }
  136. // Backend is a "wallet provider" that may contain a batch of accounts they can
  137. // sign transactions with and upon request, do so.
  138. type Backend interface {
  139. // Wallets retrieves the list of wallets the backend is currently aware of.
  140. //
  141. // The returned wallets are not opened by default. For software HD wallets this
  142. // means that no base seeds are decrypted, and for hardware wallets that no actual
  143. // connection is established.
  144. //
  145. // The resulting wallet list will be sorted alphabetically based on its internal
  146. // URL assigned by the backend. Since wallets (especially hardware) may come and
  147. // go, the same wallet might appear at a different positions in the list during
  148. // subsequent retrievals.
  149. Wallets() []Wallet
  150. // Subscribe creates an async subscription to receive notifications when the
  151. // backend detects the arrival or departure of a wallet.
  152. Subscribe(sink chan<- WalletEvent) event.Subscription
  153. }
  154. // TextHash is a helper function that calculates a hash for the given message that can be
  155. // safely used to calculate a signature from.
  156. //
  157. // The hash is calulcated as
  158. // keccak256("\x19Ethereum Signed Message:\n"${message length}${message}).
  159. //
  160. // This gives context to the signed message and prevents signing of transactions.
  161. func TextHash(data []byte) []byte {
  162. hash, _ := TextAndHash(data)
  163. return hash
  164. }
  165. // TextAndHash is a helper function that calculates a hash for the given message that can be
  166. // safely used to calculate a signature from.
  167. //
  168. // The hash is calulcated as
  169. // keccak256("\x19Ethereum Signed Message:\n"${message length}${message}).
  170. //
  171. // This gives context to the signed message and prevents signing of transactions.
  172. func TextAndHash(data []byte) ([]byte, string) {
  173. msg := fmt.Sprintf("\x19Ethereum Signed Message:\n%d%s", len(data), string(data))
  174. hasher := sha3.NewLegacyKeccak256()
  175. hasher.Write([]byte(msg))
  176. return hasher.Sum(nil), msg
  177. }
  178. // WalletEventType represents the different event types that can be fired by
  179. // the wallet subscription subsystem.
  180. type WalletEventType int
  181. const (
  182. // WalletArrived is fired when a new wallet is detected either via USB or via
  183. // a filesystem event in the keystore.
  184. WalletArrived WalletEventType = iota
  185. // WalletOpened is fired when a wallet is successfully opened with the purpose
  186. // of starting any background processes such as automatic key derivation.
  187. WalletOpened
  188. // WalletDropped
  189. WalletDropped
  190. )
  191. // WalletEvent is an event fired by an account backend when a wallet arrival or
  192. // departure is detected.
  193. type WalletEvent struct {
  194. Wallet Wallet // Wallet instance arrived or departed
  195. Kind WalletEventType // Event type that happened in the system
  196. }