api_test.go 9.4 KB

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