api_test.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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. //
  17. package core_test
  18. import (
  19. "bytes"
  20. "context"
  21. "fmt"
  22. "io/ioutil"
  23. "math/big"
  24. "os"
  25. "path/filepath"
  26. "testing"
  27. "time"
  28. "github.com/ethereum/go-ethereum/accounts"
  29. "github.com/ethereum/go-ethereum/accounts/keystore"
  30. "github.com/ethereum/go-ethereum/common"
  31. "github.com/ethereum/go-ethereum/common/hexutil"
  32. "github.com/ethereum/go-ethereum/core/types"
  33. "github.com/ethereum/go-ethereum/internal/ethapi"
  34. "github.com/ethereum/go-ethereum/rlp"
  35. "github.com/ethereum/go-ethereum/signer/core"
  36. "github.com/ethereum/go-ethereum/signer/fourbyte"
  37. "github.com/ethereum/go-ethereum/signer/storage"
  38. )
  39. //Used for testing
  40. type headlessUi struct {
  41. approveCh chan string // to send approve/deny
  42. inputCh chan string // to send password
  43. }
  44. func (ui *headlessUi) OnInputRequired(info core.UserInputRequest) (core.UserInputResponse, error) {
  45. input := <-ui.inputCh
  46. return core.UserInputResponse{Text: input}, nil
  47. }
  48. func (ui *headlessUi) OnSignerStartup(info core.StartupInfo) {}
  49. func (ui *headlessUi) RegisterUIServer(api *core.UIServerAPI) {}
  50. func (ui *headlessUi) OnApprovedTx(tx ethapi.SignTransactionResult) {}
  51. func (ui *headlessUi) ApproveTx(request *core.SignTxRequest) (core.SignTxResponse, error) {
  52. switch <-ui.approveCh {
  53. case "Y":
  54. return core.SignTxResponse{request.Transaction, true}, nil
  55. case "M": // modify
  56. // The headless UI always modifies the transaction
  57. old := big.Int(request.Transaction.Value)
  58. newVal := big.NewInt(0).Add(&old, big.NewInt(1))
  59. request.Transaction.Value = hexutil.Big(*newVal)
  60. return core.SignTxResponse{request.Transaction, true}, nil
  61. default:
  62. return core.SignTxResponse{request.Transaction, false}, nil
  63. }
  64. }
  65. func (ui *headlessUi) ApproveSignData(request *core.SignDataRequest) (core.SignDataResponse, error) {
  66. approved := "Y" == <-ui.approveCh
  67. return core.SignDataResponse{approved}, nil
  68. }
  69. func (ui *headlessUi) ApproveListing(request *core.ListRequest) (core.ListResponse, error) {
  70. approval := <-ui.approveCh
  71. //fmt.Printf("approval %s\n", approval)
  72. switch approval {
  73. case "A":
  74. return core.ListResponse{request.Accounts}, nil
  75. case "1":
  76. l := make([]accounts.Account, 1)
  77. l[0] = request.Accounts[1]
  78. return core.ListResponse{l}, nil
  79. default:
  80. return core.ListResponse{nil}, nil
  81. }
  82. }
  83. func (ui *headlessUi) ApproveNewAccount(request *core.NewAccountRequest) (core.NewAccountResponse, error) {
  84. if "Y" == <-ui.approveCh {
  85. return core.NewAccountResponse{true}, nil
  86. }
  87. return core.NewAccountResponse{false}, nil
  88. }
  89. func (ui *headlessUi) ShowError(message string) {
  90. //stdout is used by communication
  91. fmt.Fprintln(os.Stderr, message)
  92. }
  93. func (ui *headlessUi) ShowInfo(message string) {
  94. //stdout is used by communication
  95. fmt.Fprintln(os.Stderr, message)
  96. }
  97. func tmpDirName(t *testing.T) string {
  98. d, err := ioutil.TempDir("", "eth-keystore-test")
  99. if err != nil {
  100. t.Fatal(err)
  101. }
  102. d, err = filepath.EvalSymlinks(d)
  103. if err != nil {
  104. t.Fatal(err)
  105. }
  106. return d
  107. }
  108. func setup(t *testing.T) (*core.SignerAPI, *headlessUi) {
  109. db, err := fourbyte.New()
  110. if err != nil {
  111. t.Fatal(err.Error())
  112. }
  113. ui := &headlessUi{make(chan string, 20), make(chan string, 20)}
  114. am := core.StartClefAccountManager(tmpDirName(t), true, true, "")
  115. api := core.NewSignerAPI(am, 1337, true, ui, db, true, &storage.NoStorage{})
  116. return api, ui
  117. }
  118. func createAccount(ui *headlessUi, api *core.SignerAPI, t *testing.T) {
  119. ui.approveCh <- "Y"
  120. ui.inputCh <- "a_long_password"
  121. _, err := api.New(context.Background())
  122. if err != nil {
  123. t.Fatal(err)
  124. }
  125. // Some time to allow changes to propagate
  126. time.Sleep(250 * time.Millisecond)
  127. }
  128. func failCreateAccountWithPassword(ui *headlessUi, api *core.SignerAPI, password string, t *testing.T) {
  129. ui.approveCh <- "Y"
  130. // We will be asked three times to provide a suitable password
  131. ui.inputCh <- password
  132. ui.inputCh <- password
  133. ui.inputCh <- password
  134. addr, err := api.New(context.Background())
  135. if err == nil {
  136. t.Fatal("Should have returned an error")
  137. }
  138. if addr != (common.Address{}) {
  139. t.Fatal("Empty address should be returned")
  140. }
  141. }
  142. func failCreateAccount(ui *headlessUi, api *core.SignerAPI, t *testing.T) {
  143. ui.approveCh <- "N"
  144. addr, err := api.New(context.Background())
  145. if err != core.ErrRequestDenied {
  146. t.Fatal(err)
  147. }
  148. if addr != (common.Address{}) {
  149. t.Fatal("Empty address should be returned")
  150. }
  151. }
  152. func list(ui *headlessUi, api *core.SignerAPI, t *testing.T) ([]common.Address, error) {
  153. ui.approveCh <- "A"
  154. return api.List(context.Background())
  155. }
  156. func TestNewAcc(t *testing.T) {
  157. api, control := setup(t)
  158. verifyNum := func(num int) {
  159. list, err := list(control, api, t)
  160. if err != nil {
  161. t.Errorf("Unexpected error %v", err)
  162. }
  163. if len(list) != num {
  164. t.Errorf("Expected %d accounts, got %d", num, len(list))
  165. }
  166. }
  167. // Testing create and create-deny
  168. createAccount(control, api, t)
  169. createAccount(control, api, t)
  170. failCreateAccount(control, api, t)
  171. failCreateAccount(control, api, t)
  172. createAccount(control, api, t)
  173. failCreateAccount(control, api, t)
  174. createAccount(control, api, t)
  175. failCreateAccount(control, api, t)
  176. verifyNum(4)
  177. // Fail to create this, due to bad password
  178. failCreateAccountWithPassword(control, api, "short", t)
  179. failCreateAccountWithPassword(control, api, "longerbutbad\rfoo", t)
  180. verifyNum(4)
  181. // Testing listing:
  182. // Listing one Account
  183. control.approveCh <- "1"
  184. list, err := api.List(context.Background())
  185. if err != nil {
  186. t.Fatal(err)
  187. }
  188. if len(list) != 1 {
  189. t.Fatalf("List should only show one Account")
  190. }
  191. // Listing denied
  192. control.approveCh <- "Nope"
  193. list, err = api.List(context.Background())
  194. if len(list) != 0 {
  195. t.Fatalf("List should be empty")
  196. }
  197. if err != core.ErrRequestDenied {
  198. t.Fatal("Expected deny")
  199. }
  200. }
  201. func mkTestTx(from common.MixedcaseAddress) core.SendTxArgs {
  202. to := common.NewMixedcaseAddress(common.HexToAddress("0x1337"))
  203. gas := hexutil.Uint64(21000)
  204. gasPrice := (hexutil.Big)(*big.NewInt(2000000000))
  205. value := (hexutil.Big)(*big.NewInt(1e18))
  206. nonce := (hexutil.Uint64)(0)
  207. data := hexutil.Bytes(common.Hex2Bytes("01020304050607080a"))
  208. tx := core.SendTxArgs{
  209. From: from,
  210. To: &to,
  211. Gas: gas,
  212. GasPrice: gasPrice,
  213. Value: value,
  214. Data: &data,
  215. Nonce: nonce}
  216. return tx
  217. }
  218. func TestSignTx(t *testing.T) {
  219. var (
  220. list []common.Address
  221. res, res2 *ethapi.SignTransactionResult
  222. err error
  223. )
  224. api, control := setup(t)
  225. createAccount(control, api, t)
  226. control.approveCh <- "A"
  227. list, err = api.List(context.Background())
  228. if err != nil {
  229. t.Fatal(err)
  230. }
  231. a := common.NewMixedcaseAddress(list[0])
  232. methodSig := "test(uint)"
  233. tx := mkTestTx(a)
  234. control.approveCh <- "Y"
  235. control.inputCh <- "wrongpassword"
  236. res, err = api.SignTransaction(context.Background(), tx, &methodSig)
  237. if res != nil {
  238. t.Errorf("Expected nil-response, got %v", res)
  239. }
  240. if err != keystore.ErrDecrypt {
  241. t.Errorf("Expected ErrLocked! %v", err)
  242. }
  243. control.approveCh <- "No way"
  244. res, err = api.SignTransaction(context.Background(), tx, &methodSig)
  245. if res != nil {
  246. t.Errorf("Expected nil-response, got %v", res)
  247. }
  248. if err != core.ErrRequestDenied {
  249. t.Errorf("Expected ErrRequestDenied! %v", err)
  250. }
  251. // Sign with correct password
  252. control.approveCh <- "Y"
  253. control.inputCh <- "a_long_password"
  254. res, err = api.SignTransaction(context.Background(), tx, &methodSig)
  255. if err != nil {
  256. t.Fatal(err)
  257. }
  258. parsedTx := &types.Transaction{}
  259. rlp.Decode(bytes.NewReader(res.Raw), parsedTx)
  260. //The tx should NOT be modified by the UI
  261. if parsedTx.Value().Cmp(tx.Value.ToInt()) != 0 {
  262. t.Errorf("Expected value to be unchanged, expected %v got %v", tx.Value, parsedTx.Value())
  263. }
  264. control.approveCh <- "Y"
  265. control.inputCh <- "a_long_password"
  266. res2, err = api.SignTransaction(context.Background(), tx, &methodSig)
  267. if err != nil {
  268. t.Fatal(err)
  269. }
  270. if !bytes.Equal(res.Raw, res2.Raw) {
  271. t.Error("Expected tx to be unmodified by UI")
  272. }
  273. //The tx is modified by the UI
  274. control.approveCh <- "M"
  275. control.inputCh <- "a_long_password"
  276. res2, err = api.SignTransaction(context.Background(), tx, &methodSig)
  277. if err != nil {
  278. t.Fatal(err)
  279. }
  280. parsedTx2 := &types.Transaction{}
  281. rlp.Decode(bytes.NewReader(res.Raw), parsedTx2)
  282. //The tx should be modified by the UI
  283. if parsedTx2.Value().Cmp(tx.Value.ToInt()) != 0 {
  284. t.Errorf("Expected value to be unchanged, got %v", parsedTx.Value())
  285. }
  286. if bytes.Equal(res.Raw, res2.Raw) {
  287. t.Error("Expected tx to be modified by UI")
  288. }
  289. }