api_test.go 10 KB

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