aboutsummaryrefslogtreecommitdiffstats
path: root/signer/core/api_test.go
blob: 70aa9aa94ec1318ff45a953e109ce53724dfa8ea (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
// Copyright 2018 The go-ethereum Authors
// This file is part of go-ethereum.
//
// go-ethereum is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// go-ethereum is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
//
package core

import (
    "bytes"
    "context"
    "fmt"
    "io/ioutil"
    "math/big"
    "os"
    "path/filepath"
    "testing"
    "time"

    "github.com/ethereum/go-ethereum/accounts/keystore"
    "github.com/ethereum/go-ethereum/cmd/utils"
    "github.com/ethereum/go-ethereum/common"
    "github.com/ethereum/go-ethereum/common/hexutil"
    "github.com/ethereum/go-ethereum/core/types"
    "github.com/ethereum/go-ethereum/internal/ethapi"
    "github.com/ethereum/go-ethereum/rlp"
)

//Used for testing
type HeadlessUI struct {
    controller chan string
}

func (ui *HeadlessUI) OnSignerStartup(info StartupInfo) {
}

func (ui *HeadlessUI) OnApprovedTx(tx ethapi.SignTransactionResult) {
    fmt.Printf("OnApproved()\n")
}

func (ui *HeadlessUI) ApproveTx(request *SignTxRequest) (SignTxResponse, error) {

    switch <-ui.controller {
    case "Y":
        return SignTxResponse{request.Transaction, true, <-ui.controller}, nil
    case "M": //Modify
        old := big.Int(request.Transaction.Value)
        newVal := big.NewInt(0).Add(&old, big.NewInt(1))
        request.Transaction.Value = hexutil.Big(*newVal)
        return SignTxResponse{request.Transaction, true, <-ui.controller}, nil
    default:
        return SignTxResponse{request.Transaction, false, ""}, nil
    }
}

func (ui *HeadlessUI) ApproveSignData(request *SignDataRequest) (SignDataResponse, error) {
    if "Y" == <-ui.controller {
        return SignDataResponse{true, <-ui.controller}, nil
    }
    return SignDataResponse{false, ""}, nil
}

func (ui *HeadlessUI) ApproveExport(request *ExportRequest) (ExportResponse, error) {
    return ExportResponse{<-ui.controller == "Y"}, nil

}

func (ui *HeadlessUI) ApproveImport(request *ImportRequest) (ImportResponse, error) {
    if "Y" == <-ui.controller {
        return ImportResponse{true, <-ui.controller, <-ui.controller}, nil
    }
    return ImportResponse{false, "", ""}, nil
}

func (ui *HeadlessUI) ApproveListing(request *ListRequest) (ListResponse, error) {
    switch <-ui.controller {
    case "A":
        return ListResponse{request.Accounts}, nil
    case "1":
        l := make([]Account, 1)
        l[0] = request.Accounts[1]
        return ListResponse{l}, nil
    default:
        return ListResponse{nil}, nil
    }
}

func (ui *HeadlessUI) ApproveNewAccount(request *NewAccountRequest) (NewAccountResponse, error) {
    if "Y" == <-ui.controller {
        return NewAccountResponse{true, <-ui.controller}, nil
    }
    return NewAccountResponse{false, ""}, nil
}

func (ui *HeadlessUI) ShowError(message string) {
    //stdout is used by communication
    fmt.Fprintln(os.Stderr, message)
}

func (ui *HeadlessUI) ShowInfo(message string) {
    //stdout is used by communication
    fmt.Fprintln(os.Stderr, message)
}

func tmpDirName(t *testing.T) string {
    d, err := ioutil.TempDir("", "eth-keystore-test")
    if err != nil {
        t.Fatal(err)
    }
    d, err = filepath.EvalSymlinks(d)
    if err != nil {
        t.Fatal(err)
    }
    return d
}

func setup(t *testing.T) (*SignerAPI, chan string) {

    controller := make(chan string, 20)

    db, err := NewAbiDBFromFile("../../cmd/clef/4byte.json")
    if err != nil {
        utils.Fatalf(err.Error())
    }
    var (
        ui  = &HeadlessUI{controller}
        api = NewSignerAPI(
            1,
            tmpDirName(t),
            true,
            ui,
            db,
            true, true)
    )
    return api, controller
}
func createAccount(control chan string, api *SignerAPI, t *testing.T) {

    control <- "Y"
    control <- "a_long_password"
    _, err := api.New(context.Background())
    if err != nil {
        t.Fatal(err)
    }
    // Some time to allow changes to propagate
    time.Sleep(250 * time.Millisecond)
}

func failCreateAccountWithPassword(control chan string, api *SignerAPI, password string, t *testing.T) {

    control <- "Y"
    control <- password
    control <- "Y"
    control <- password
    control <- "Y"
    control <- password

    acc, err := api.New(context.Background())
    if err == nil {
        t.Fatal("Should have returned an error")
    }
    if acc.Address != (common.Address{}) {
        t.Fatal("Empty address should be returned")
    }
}

func failCreateAccount(control chan string, api *SignerAPI, t *testing.T) {
    control <- "N"
    acc, err := api.New(context.Background())
    if err != ErrRequestDenied {
        t.Fatal(err)
    }
    if acc.Address != (common.Address{}) {
        t.Fatal("Empty address should be returned")
    }
}

func list(control chan string, api *SignerAPI, t *testing.T) []common.Address {
    control <- "A"
    list, err := api.List(context.Background())
    if err != nil {
        t.Fatal(err)
    }
    return list
}

func TestNewAcc(t *testing.T) {
    api, control := setup(t)
    verifyNum := func(num int) {
        if list := list(control, api, t); len(list) != num {
            t.Errorf("Expected %d accounts, got %d", num, len(list))
        }
    }
    // Testing create and create-deny
    createAccount(control, api, t)
    createAccount(control, api, t)
    failCreateAccount(control, api, t)
    failCreateAccount(control, api, t)
    createAccount(control, api, t)
    failCreateAccount(control, api, t)
    createAccount(control, api, t)
    failCreateAccount(control, api, t)

    verifyNum(4)

    // Fail to create this, due to bad password
    failCreateAccountWithPassword(control, api, "short", t)
    failCreateAccountWithPassword(control, api, "longerbutbad\rfoo", t)

    verifyNum(4)

    // Testing listing:
    // Listing one Account
    control <- "1"
    list, err := api.List(context.Background())
    if err != nil {
        t.Fatal(err)
    }
    if len(list) != 1 {
        t.Fatalf("List should only show one Account")
    }
    // Listing denied
    control <- "Nope"
    list, err = api.List(context.Background())
    if len(list) != 0 {
        t.Fatalf("List should be empty")
    }
    if err != ErrRequestDenied {
        t.Fatal("Expected deny")
    }
}

func TestSignData(t *testing.T) {
    api, control := setup(t)
    //Create two accounts
    createAccount(control, api, t)
    createAccount(control, api, t)
    control <- "1"
    list, err := api.List(context.Background())
    if err != nil {
        t.Fatal(err)
    }
    a := common.NewMixedcaseAddress(list[0])

    control <- "Y"
    control <- "wrongpassword"
    h, err := api.Sign(context.Background(), a, []byte("EHLO world"))
    if h != nil {
        t.Errorf("Expected nil-data, got %x", h)
    }
    if err != keystore.ErrDecrypt {
        t.Errorf("Expected ErrLocked! %v", err)
    }
    control <- "No way"
    h, err = api.Sign(context.Background(), a, []byte("EHLO world"))
    if h != nil {
        t.Errorf("Expected nil-data, got %x", h)
    }
    if err != ErrRequestDenied {
        t.Errorf("Expected ErrRequestDenied! %v", err)
    }
    control <- "Y"
    control <- "a_long_password"
    h, err = api.Sign(context.Background(), a, []byte("EHLO world"))
    if err != nil {
        t.Fatal(err)
    }
    if h == nil || len(h) != 65 {
        t.Errorf("Expected 65 byte signature (got %d bytes)", len(h))
    }
}
func mkTestTx(from common.MixedcaseAddress) SendTxArgs {
    to := common.NewMixedcaseAddress(common.HexToAddress("0x1337"))
    gas := hexutil.Uint64(21000)
    gasPrice := (hexutil.Big)(*big.NewInt(2000000000))
    value := (hexutil.Big)(*big.NewInt(1e18))
    nonce := (hexutil.Uint64)(0)
    data := hexutil.Bytes(common.Hex2Bytes("01020304050607080a"))
    tx := SendTxArgs{
        From:     from,
        To:       &to,
        Gas:      gas,
        GasPrice: gasPrice,
        Value:    value,
        Data:     &data,
        Nonce:    nonce}
    return tx
}

func TestSignTx(t *testing.T) {
    var (
        list      []common.Address
        res, res2 *ethapi.SignTransactionResult
        err       error
    )

    api, control := setup(t)
    createAccount(control, api, t)
    control <- "A"
    list, err = api.List(context.Background())
    if err != nil {
        t.Fatal(err)
    }
    a := common.NewMixedcaseAddress(list[0])

    methodSig := "test(uint)"
    tx := mkTestTx(a)

    control <- "Y"
    control <- "wrongpassword"
    res, err = api.SignTransaction(context.Background(), tx, &methodSig)
    if res != nil {
        t.Errorf("Expected nil-response, got %v", res)
    }
    if err != keystore.ErrDecrypt {
        t.Errorf("Expected ErrLocked! %v", err)
    }
    control <- "No way"
    res, err = api.SignTransaction(context.Background(), tx, &methodSig)
    if res != nil {
        t.Errorf("Expected nil-response, got %v", res)
    }
    if err != ErrRequestDenied {
        t.Errorf("Expected ErrRequestDenied! %v", err)
    }
    control <- "Y"
    control <- "a_long_password"
    res, err = api.SignTransaction(context.Background(), tx, &methodSig)

    if err != nil {
        t.Fatal(err)
    }
    parsedTx := &types.Transaction{}
    rlp.Decode(bytes.NewReader(res.Raw), parsedTx)

    //The tx should NOT be modified by the UI
    if parsedTx.Value().Cmp(tx.Value.ToInt()) != 0 {
        t.Errorf("Expected value to be unchanged, expected %v got %v", tx.Value, parsedTx.Value())
    }
    control <- "Y"
    control <- "a_long_password"

    res2, err = api.SignTransaction(context.Background(), tx, &methodSig)
    if err != nil {
        t.Fatal(err)
    }
    if !bytes.Equal(res.Raw, res2.Raw) {
        t.Error("Expected tx to be unmodified by UI")
    }

    //The tx is modified by the UI
    control <- "M"
    control <- "a_long_password"

    res2, err = api.SignTransaction(context.Background(), tx, &methodSig)
    if err != nil {
        t.Fatal(err)
    }
    parsedTx2 := &types.Transaction{}
    rlp.Decode(bytes.NewReader(res.Raw), parsedTx2)

    //The tx should be modified by the UI
    if parsedTx2.Value().Cmp(tx.Value.ToInt()) != 0 {
        t.Errorf("Expected value to be unchanged, got %v", parsedTx.Value())
    }
    if bytes.Equal(res.Raw, res2.Raw) {
        t.Error("Expected tx to be modified by UI")
    }

}

/*
func TestAsyncronousResponses(t *testing.T){

    //Set up one account
    api, control := setup(t)
    createAccount(control, api, t)

    // Two transactions, the second one with larger value than the first
    tx1 := mkTestTx()
    newVal := big.NewInt(0).Add((*big.Int) (tx1.Value), big.NewInt(1))
    tx2 := mkTestTx()
    tx2.Value = (*hexutil.Big)(newVal)

    control <- "W" //wait
    control <- "Y" //
    control <- "a_long_password"
    control <- "Y" //
    control <- "a_long_password"

    var err error

    h1, err := api.SignTransaction(context.Background(), common.HexToAddress("1111"), tx1, nil)
    h2, err := api.SignTransaction(context.Background(), common.HexToAddress("2222"), tx2, nil)


    }
*/