api_test.go 10 KB

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