api_test.go 9.0 KB

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