api_test.go 9.42 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
// 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"
22
	"errors"
23 24 25 26 27 28 29 30
	"fmt"
	"io/ioutil"
	"math/big"
	"os"
	"path/filepath"
	"testing"
	"time"

31
	"github.com/ethereum/go-ethereum/accounts"
32 33 34 35 36 37 38 39 40 41 42 43 44
	"github.com/ethereum/go-ethereum/accounts/keystore"
	"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
}

45 46 47 48
func (ui *HeadlessUI) OnInputRequired(info UserInputRequest) (UserInputResponse, error) {
	return UserInputResponse{}, errors.New("not implemented")
}

49 50
func (ui *HeadlessUI) OnSignerStartup(info StartupInfo) {
}
51 52
func (ui *HeadlessUI) RegisterUIServer(api *UIServerAPI) {
}
53 54

func (ui *HeadlessUI) OnApprovedTx(tx ethapi.SignTransactionResult) {
55
	fmt.Printf("OnApproved()\n")
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
}

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
	}
}
72

73 74 75 76 77 78 79
func (ui *HeadlessUI) ApproveSignData(request *SignDataRequest) (SignDataResponse, error) {
	if "Y" == <-ui.controller {
		return SignDataResponse{true, <-ui.controller}, nil
	}
	return SignDataResponse{false, ""}, nil
}

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

}

85
func (ui *HeadlessUI) ApproveImport(request *ImportRequest) (ImportResponse, error) {
86 87 88 89 90 91
	if "Y" == <-ui.controller {
		return ImportResponse{true, <-ui.controller, <-ui.controller}, nil
	}
	return ImportResponse{false, "", ""}, nil
}

92
func (ui *HeadlessUI) ApproveListing(request *ListRequest) (ListResponse, error) {
93 94 95 96
	switch <-ui.controller {
	case "A":
		return ListResponse{request.Accounts}, nil
	case "1":
97
		l := make([]accounts.Account, 1)
98 99 100 101 102 103 104
		l[0] = request.Accounts[1]
		return ListResponse{l}, nil
	default:
		return ListResponse{nil}, nil
	}
}

105
func (ui *HeadlessUI) ApproveNewAccount(request *NewAccountRequest) (NewAccountResponse, error) {
106 107 108 109 110
	if "Y" == <-ui.controller {
		return NewAccountResponse{true, <-ui.controller}, nil
	}
	return NewAccountResponse{false, ""}, nil
}
111

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

117 118
func (ui *HeadlessUI) ShowInfo(message string) {
	//stdout is used by communication
119
	fmt.Fprintln(os.Stderr, message)
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
}

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) {

136
	controller := make(chan string, 20)
137 138 139

	db, err := NewAbiDBFromFile("../../cmd/clef/4byte.json")
	if err != nil {
140
		t.Fatal(err.Error())
141 142 143
	}
	var (
		ui  = &HeadlessUI{controller}
144 145
		am  = StartClefAccountManager(tmpDirName(t), true, true)
		api = NewSignerAPI(am, 1337, true, ui, db, true)
146 147 148 149 150 151
	)
	return api, controller
}
func createAccount(control chan string, api *SignerAPI, t *testing.T) {

	control <- "Y"
152
	control <- "a_long_password"
153 154 155 156 157 158 159
	_, err := api.New(context.Background())
	if err != nil {
		t.Fatal(err)
	}
	// Some time to allow changes to propagate
	time.Sleep(250 * time.Millisecond)
}
160 161 162 163 164 165 166 167 168 169

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

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

170
	addr, err := api.New(context.Background())
171 172 173
	if err == nil {
		t.Fatal("Should have returned an error")
	}
174
	if addr != (common.Address{}) {
175 176 177 178
		t.Fatal("Empty address should be returned")
	}
}

179 180
func failCreateAccount(control chan string, api *SignerAPI, t *testing.T) {
	control <- "N"
181
	addr, err := api.New(context.Background())
182 183 184
	if err != ErrRequestDenied {
		t.Fatal(err)
	}
185
	if addr != (common.Address{}) {
186 187 188
		t.Fatal("Empty address should be returned")
	}
}
189 190

func list(control chan string, api *SignerAPI, t *testing.T) []common.Address {
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
	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)
215 216 217 218 219 220 221

	verifyNum(4)

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

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
	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 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 (
265
		list      []common.Address
266 267 268 269 270 271 272 273 274 275 276
		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)
	}
277
	a := common.NewMixedcaseAddress(list[0])
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299

	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"
300
	control <- "a_long_password"
301 302 303 304 305 306 307
	res, err = api.SignTransaction(context.Background(), tx, &methodSig)

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

309 310 311 312 313
	//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"
314
	control <- "a_long_password"
315 316 317 318 319 320 321 322 323 324 325

	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"
326
	control <- "a_long_password"
327 328 329 330 331 332 333

	res2, err = api.SignTransaction(context.Background(), tx, &methodSig)
	if err != nil {
		t.Fatal(err)
	}
	parsedTx2 := &types.Transaction{}
	rlp.Decode(bytes.NewReader(res.Raw), parsedTx2)
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
	//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" //
360
	control <- "a_long_password"
361
	control <- "Y" //
362
	control <- "a_long_password"
363 364 365 366 367 368 369 370 371

	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)


	}
*/