api_test.go 8.7 KB

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