diff --git a/api/api.go b/api/api.go deleted file mode 100644 index 89e2aafbe..000000000 --- a/api/api.go +++ /dev/null @@ -1,229 +0,0 @@ -package api - -import ( - "context" - - "github.com/NaySoftware/go-fcm" - "github.com/ethereum/go-ethereum/accounts/keystore" - gethcommon "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/log" - "github.com/status-im/status-go/account" - "github.com/status-im/status-go/jail" - "github.com/status-im/status-go/node" - "github.com/status-im/status-go/params" - "github.com/status-im/status-go/sign" - "github.com/status-im/status-go/transactions" -) - -// StatusAPI provides API to access Status related functionality. -type StatusAPI struct { - b *StatusBackend - log log.Logger -} - -// NewStatusAPI creates a new StatusAPI instance -func NewStatusAPI() *StatusAPI { - return NewStatusAPIWithBackend(NewStatusBackend()) -} - -// NewStatusAPIWithBackend creates a new StatusAPI instance using -// the passed backend. -func NewStatusAPIWithBackend(b *StatusBackend) *StatusAPI { - return &StatusAPI{ - b: b, - log: log.New("package", "status-go/api.StatusAPI"), - } -} - -// StatusNode returns reference to StatusNode. -func (api *StatusAPI) StatusNode() *node.StatusNode { - return api.b.StatusNode() -} - -// AccountManager returns reference to account manager -func (api *StatusAPI) AccountManager() *account.Manager { - return api.b.AccountManager() -} - -// JailManager returns reference to jail -func (api *StatusAPI) JailManager() jail.Manager { - return api.b.JailManager() -} - -// Transactor returns reference to a status transactor -func (api *StatusAPI) Transactor() *transactions.Transactor { - return api.b.Transactor() -} - -// PendingSignRequests returns reference to a list of current sign requests -func (api *StatusAPI) PendingSignRequests() *sign.PendingRequests { - return api.b.PendingSignRequests() -} - -// StartNode start Status node, fails if node is already started -func (api *StatusAPI) StartNode(config *params.NodeConfig) error { - return api.b.StartNode(config) -} - -// StartNodeAsync start Status node, fails if node is already started -// Returns immediately w/o waiting for node to start (see node.ready) -func (api *StatusAPI) StartNodeAsync(config *params.NodeConfig) <-chan error { - return runAsync(func() error { return api.StartNode(config) }) -} - -// StopNode stop Status node. Stopped node cannot be resumed. -func (api *StatusAPI) StopNode() error { - return api.b.StopNode() -} - -// StopNodeAsync stop Status node. Stopped node cannot be resumed. -// Returns immediately, w/o waiting for node to stop (see node.stopped) -func (api *StatusAPI) StopNodeAsync() <-chan error { - return runAsync(api.StopNode) -} - -// RestartNode restart running Status node, fails if node is not running -func (api *StatusAPI) RestartNode() error { - return api.b.RestartNode() -} - -// RestartNodeAsync restart running Status node, in async manner -func (api *StatusAPI) RestartNodeAsync() <-chan error { - return runAsync(api.RestartNode) -} - -// ResetChainData remove chain data from data directory. -// Node is stopped, and new node is started, with clean data directory. -func (api *StatusAPI) ResetChainData() error { - return api.b.ResetChainData() -} - -// ResetChainDataAsync remove chain data from data directory, in async manner -func (api *StatusAPI) ResetChainDataAsync() <-chan error { - return runAsync(api.ResetChainData) -} - -// CallRPC executes public RPC requests on node's in-proc RPC server. -func (api *StatusAPI) CallRPC(inputJSON string) string { - return api.b.CallRPC(inputJSON) -} - -// CallPrivateRPC executes public and private RPC requests on node's in-proc RPC server. -func (api *StatusAPI) CallPrivateRPC(inputJSON string) string { - return api.b.CallPrivateRPC(inputJSON) -} - -// CreateAccount creates an internal geth account -// BIP44-compatible keys are generated: CKD#1 is stored as account key, CKD#2 stored as sub-account root -// Public key of CKD#1 is returned, with CKD#2 securely encoded into account key file (to be used for -// sub-account derivations) -func (api *StatusAPI) CreateAccount(password string) (address, pubKey, mnemonic string, err error) { - return api.b.AccountManager().CreateAccount(password) -} - -// CreateChildAccount creates sub-account for an account identified by parent address. -// CKD#2 is used as root for master accounts (when parentAddress is ""). -// Otherwise (when parentAddress != ""), child is derived directly from parent. -func (api *StatusAPI) CreateChildAccount(parentAddress, password string) (address, pubKey string, err error) { - return api.b.AccountManager().CreateChildAccount(parentAddress, password) -} - -// RecoverAccount re-creates master key using given details. -// Once master key is re-generated, it is inserted into keystore (if not already there). -func (api *StatusAPI) RecoverAccount(password, mnemonic string) (address, pubKey string, err error) { - return api.b.AccountManager().RecoverAccount(password, mnemonic) -} - -// VerifyAccountPassword tries to decrypt a given account key file, with a provided password. -// If no error is returned, then account is considered verified. -func (api *StatusAPI) VerifyAccountPassword(keyStoreDir, address, password string) (*keystore.Key, error) { - return api.b.AccountManager().VerifyAccountPassword(keyStoreDir, address, password) -} - -// SelectAccount selects current account, by verifying that address has corresponding account which can be decrypted -// using provided password. Once verification is done, decrypted key is injected into Whisper (as a single identity, -// all previous identities are removed). -func (api *StatusAPI) SelectAccount(address, password string) error { - return api.b.SelectAccount(address, password) -} - -// Logout clears whisper identities -func (api *StatusAPI) Logout() error { - return api.b.Logout() -} - -// SendTransaction creates a new transaction and waits until it's complete. -func (api *StatusAPI) SendTransaction(ctx context.Context, args transactions.SendTxArgs) (gethcommon.Hash, error) { - return api.b.SendTransaction(ctx, args) -} - -// ApproveSignRequest instructs backend to complete sending of a given transaction -func (api *StatusAPI) ApproveSignRequest(id, password string) sign.Result { - return api.b.ApproveSignRequest(id, password) -} - -// ApproveSignRequestWithArgs instructs backend to complete sending of a given transaction -// gas and gasPrice will be overrided with the given values before signing the -// transaction. -func (api *StatusAPI) ApproveSignRequestWithArgs(id, password string, gas, gasPrice int64) sign.Result { - return api.b.ApproveSignRequestWithArgs(id, password, gas, gasPrice) -} - -// ApproveSignRequests instructs backend to complete sending of multiple transactions -func (api *StatusAPI) ApproveSignRequests(ids []string, password string) map[string]sign.Result { - return api.b.ApproveSignRequests(ids, password) -} - -// DiscardSignRequest discards a given transaction from transaction queue -func (api *StatusAPI) DiscardSignRequest(id string) error { - return api.b.DiscardSignRequest(id) -} - -// DiscardSignRequests discards given multiple transactions from transaction queue -func (api *StatusAPI) DiscardSignRequests(ids []string) map[string]error { - return api.b.DiscardSignRequests(ids) -} - -// JailParse creates a new jail cell context, with the given chatID as identifier. -// New context executes provided JavaScript code, right after the initialization. -// DEPRECATED in favour of CreateAndInitCell. -func (api *StatusAPI) JailParse(chatID string, js string) string { - return api.b.jailManager.Parse(chatID, js) -} - -// CreateAndInitCell creates a new jail cell context, with the given chatID as identifier. -// New context executes provided JavaScript code, right after the initialization. -func (api *StatusAPI) CreateAndInitCell(chatID, js string) string { - return api.b.jailManager.CreateAndInitCell(chatID, js) -} - -// JailCall executes given JavaScript function w/i a jail cell context identified by the chatID. -func (api *StatusAPI) JailCall(chatID, this, args string) string { - return api.b.jailManager.Call(chatID, this, args) -} - -// JailExecute allows to run arbitrary JS code within a jail cell. -func (api *StatusAPI) JailExecute(chatID, code string) string { - return api.b.jailManager.Execute(chatID, code) -} - -// SetJailBaseJS allows to setup initial JavaScript to be loaded on each jail.CreateAndInitCell(). -func (api *StatusAPI) SetJailBaseJS(js string) { - api.b.jailManager.SetBaseJS(js) -} - -// NotifyUsers send notifications to users. -func (api *StatusAPI) NotifyUsers(message string, payload fcm.NotificationPayload, tokens ...string) error { - return api.b.NotifyUsers(message, payload, tokens...) -} - -// ConnectionChange handles network state changes logic. -func (api *StatusAPI) ConnectionChange(typ string, expensive bool) { - api.b.ConnectionChange(typ, expensive) -} - -// AppStateChange handles app state changes (background/foreground). -// state values: see https://facebook.github.io/react-native/docs/appstate.html -func (api *StatusAPI) AppStateChange(state string) { - api.b.AppStateChange(state) -} diff --git a/api/utils.go b/api/utils.go index c61fb137d..5e129d23c 100644 --- a/api/utils.go +++ b/api/utils.go @@ -1,6 +1,6 @@ package api -func runAsync(f func() error) <-chan error { +func RunAsync(f func() error) <-chan error { resp := make(chan error, 1) go func() { err := f() diff --git a/cmd/statusd/debug/commands.go b/cmd/statusd/debug/commands.go index 3bf124791..e457e6c77 100644 --- a/cmd/statusd/debug/commands.go +++ b/cmd/statusd/debug/commands.go @@ -106,14 +106,14 @@ func exprsToArgs(exprs []ast.Expr) []interface{} { // is not possible due to non-low-level arguments. Here this wrapper // helps. type commandSet struct { - statusAPI *api.StatusAPI + statusBackend *api.StatusBackend } // newCommandSet creates the command set for the passed Status API // instance. -func newCommandSet(statusAPI *api.StatusAPI) *commandSet { +func newCommandSet(statusBackend *api.StatusBackend) *commandSet { return &commandSet{ - statusAPI: statusAPI, + statusBackend: statusBackend, } } @@ -124,52 +124,52 @@ func (cs *commandSet) StartNode(config string) error { if err != nil { return err } - return cs.statusAPI.StartNode(nodeConfig) + return cs.statusBackend.StartNode(nodeConfig) } // StopNode starts the stopped node. func (cs *commandSet) StopNode() error { - return cs.statusAPI.StopNode() + return cs.statusBackend.StopNode() } // ResetChainData removes chain data from data directory. func (cs *commandSet) ResetChainData() error { - return cs.statusAPI.ResetChainData() + return cs.statusBackend.ResetChainData() } // CallRPC calls status node via RPC. func (cs *commandSet) CallRPC(inputJSON string) string { - return cs.statusAPI.CallRPC(inputJSON) + return cs.statusBackend.CallRPC(inputJSON) } // CreateAccount creates an internal geth account. func (cs *commandSet) CreateAccount(password string) (string, string, string, error) { - return cs.statusAPI.CreateAccount(password) + return cs.statusBackend.AccountManager().CreateAccount(password) } // CreateChildAccount creates a sub-account. func (cs *commandSet) CreateChildAccount(parentAddress, password string) (string, string, error) { - return cs.statusAPI.CreateChildAccount(parentAddress, password) + return cs.statusBackend.AccountManager().CreateChildAccount(parentAddress, password) } // RecoverAccount re-creates the master key using the given details. func (cs *commandSet) RecoverAccount(password, mnemonic string) (string, string, error) { - return cs.statusAPI.RecoverAccount(password, mnemonic) + return cs.statusBackend.AccountManager().RecoverAccount(password, mnemonic) } // SelectAccount selects the addressed account. func (cs *commandSet) SelectAccount(address, password string) error { - return cs.statusAPI.SelectAccount(address, password) + return cs.statusBackend.SelectAccount(address, password) } // Logout clears the Whisper identities. func (cs *commandSet) Logout() error { - return cs.statusAPI.Logout() + return cs.statusBackend.Logout() } // ApproveSignRequest instructs API to complete sending of a given transaction. func (cs *commandSet) ApproveSignRequest(id, password string) (string, error) { - result := cs.statusAPI.ApproveSignRequest(id, password) + result := cs.statusBackend.ApproveSignRequest(id, password) if result.Error != nil { return "", result.Error } @@ -180,7 +180,7 @@ func (cs *commandSet) ApproveSignRequest(id, password string) (string, error) { // gas and gasPrice will be overrided with the given values before signing the // transaction. func (cs *commandSet) ApproveSignRequestWithArgs(id, password string, gas, gasPrice int64) (string, error) { - result := cs.statusAPI.ApproveSignRequestWithArgs(id, password, gas, gasPrice) + result := cs.statusBackend.ApproveSignRequestWithArgs(id, password, gas, gasPrice) if result.Error != nil { return "", result.Error } diff --git a/cmd/statusd/debug/debug.go b/cmd/statusd/debug/debug.go index dabeb5ccf..0e1bdea94 100644 --- a/cmd/statusd/debug/debug.go +++ b/cmd/statusd/debug/debug.go @@ -27,13 +27,13 @@ type Server struct { // New creates a debug server using the passed Status API. // It also starts the server. -func New(statusAPI *api.StatusAPI, port string) (*Server, error) { +func New(statusBackend *api.StatusBackend, port string) (*Server, error) { listener, err := net.Listen("tcp", fmt.Sprintf(":%s", port)) // nolint if err != nil { return nil, err } s := Server{ - commandSetValue: reflect.ValueOf(newCommandSet(statusAPI)), + commandSetValue: reflect.ValueOf(newCommandSet(statusBackend)), listener: listener, log: log.New("package", "status-go/cmd/statusd/debug.Server"), } diff --git a/cmd/statusd/debug/debug_test.go b/cmd/statusd/debug/debug_test.go index 34704b290..575a16ea1 100644 --- a/cmd/statusd/debug/debug_test.go +++ b/cmd/statusd/debug/debug_test.go @@ -161,8 +161,8 @@ func startDebugging(assert *testifyAssert.Assertions) { defer mu.Unlock() if d == nil { var err error - api := api.NewStatusAPI() - d, err = debug.New(api, debug.CLIPort) + backend := api.NewStatusBackend() + d, err = debug.New(backend, debug.CLIPort) assert.NoError(err) } } diff --git a/cmd/statusd/main.go b/cmd/statusd/main.go index 2da233451..f3c34c445 100644 --- a/cmd/statusd/main.go +++ b/cmd/statusd/main.go @@ -174,8 +174,7 @@ func main() { // startDebug starts the debugging API server. func startDebug(backend *api.StatusBackend) error { - statusAPI := api.NewStatusAPIWithBackend(backend) - _, err := debug.New(statusAPI, *cliPort) + _, err := debug.New(backend, *cliPort) return err } diff --git a/lib/library.go b/lib/library.go index f71990002..5c02584f3 100644 --- a/lib/library.go +++ b/lib/library.go @@ -8,6 +8,7 @@ import ( "github.com/NaySoftware/go-fcm" "github.com/ethereum/go-ethereum/log" + "github.com/status-im/status-go/api" "github.com/status-im/status-go/logutils" "github.com/status-im/status-go/params" "github.com/status-im/status-go/profiling" @@ -46,7 +47,7 @@ func StartNode(configJSON *C.char) *C.char { return makeJSONResponse(err) } - statusAPI.StartNodeAsync(config) + api.RunAsync(func() error { return statusBackend.StartNode(config) }) return makeJSONResponse(nil) } @@ -54,7 +55,7 @@ func StartNode(configJSON *C.char) *C.char { //StopNode - stop status node //export StopNode func StopNode() *C.char { - statusAPI.StopNodeAsync() + api.RunAsync(statusBackend.StopNode) return makeJSONResponse(nil) } @@ -104,21 +105,21 @@ func ValidateNodeConfig(configJSON *C.char) *C.char { //ResetChainData remove chain data from data directory //export ResetChainData func ResetChainData() *C.char { - statusAPI.ResetChainDataAsync() + api.RunAsync(statusBackend.ResetChainData) return makeJSONResponse(nil) } //CallRPC calls public APIs via RPC //export CallRPC func CallRPC(inputJSON *C.char) *C.char { - outputJSON := statusAPI.CallRPC(C.GoString(inputJSON)) + outputJSON := statusBackend.CallRPC(C.GoString(inputJSON)) return C.CString(outputJSON) } //CallPrivateRPC calls both public and private APIs via RPC //export CallPrivateRPC func CallPrivateRPC(inputJSON *C.char) *C.char { - outputJSON := statusAPI.CallPrivateRPC(C.GoString(inputJSON)) + outputJSON := statusBackend.CallPrivateRPC(C.GoString(inputJSON)) return C.CString(outputJSON) } @@ -126,7 +127,7 @@ func CallPrivateRPC(inputJSON *C.char) *C.char { // just modified to handle the function arg passing //export CreateAccount func CreateAccount(password *C.char) *C.char { - address, pubKey, mnemonic, err := statusAPI.CreateAccount(C.GoString(password)) + address, pubKey, mnemonic, err := statusBackend.AccountManager().CreateAccount(C.GoString(password)) errString := "" if err != nil { @@ -147,7 +148,7 @@ func CreateAccount(password *C.char) *C.char { //CreateChildAccount creates sub-account //export CreateChildAccount func CreateChildAccount(parentAddress, password *C.char) *C.char { - address, pubKey, err := statusAPI.CreateChildAccount(C.GoString(parentAddress), C.GoString(password)) + address, pubKey, err := statusBackend.AccountManager().CreateChildAccount(C.GoString(parentAddress), C.GoString(password)) errString := "" if err != nil { @@ -167,7 +168,7 @@ func CreateChildAccount(parentAddress, password *C.char) *C.char { //RecoverAccount re-creates master key using given details //export RecoverAccount func RecoverAccount(password, mnemonic *C.char) *C.char { - address, pubKey, err := statusAPI.RecoverAccount(C.GoString(password), C.GoString(mnemonic)) + address, pubKey, err := statusBackend.AccountManager().RecoverAccount(C.GoString(password), C.GoString(mnemonic)) errString := "" if err != nil { @@ -188,7 +189,7 @@ func RecoverAccount(password, mnemonic *C.char) *C.char { //VerifyAccountPassword verifies account password //export VerifyAccountPassword func VerifyAccountPassword(keyStoreDir, address, password *C.char) *C.char { - _, err := statusAPI.VerifyAccountPassword(C.GoString(keyStoreDir), C.GoString(address), C.GoString(password)) + _, err := statusBackend.AccountManager().VerifyAccountPassword(C.GoString(keyStoreDir), C.GoString(address), C.GoString(password)) return makeJSONResponse(err) } @@ -196,14 +197,14 @@ func VerifyAccountPassword(keyStoreDir, address, password *C.char) *C.char { // if verified, purges all the previous identities from Whisper, and injects verified key as shh identity //export Login func Login(address, password *C.char) *C.char { - err := statusAPI.SelectAccount(C.GoString(address), C.GoString(password)) + err := statusBackend.SelectAccount(C.GoString(address), C.GoString(password)) return makeJSONResponse(err) } //Logout is equivalent to clearing whisper identities //export Logout func Logout() *C.char { - err := statusAPI.Logout() + err := statusBackend.Logout() return makeJSONResponse(err) } @@ -212,7 +213,7 @@ func Logout() *C.char { // transaction. //export ApproveSignRequestWithArgs func ApproveSignRequestWithArgs(id, password *C.char, gas, gasPrice C.longlong) *C.char { - result := statusAPI.ApproveSignRequestWithArgs(C.GoString(id), C.GoString(password), int64(gas), int64(gasPrice)) + result := statusBackend.ApproveSignRequestWithArgs(C.GoString(id), C.GoString(password), int64(gas), int64(gasPrice)) return prepareApproveSignRequestResponse(result, id) } @@ -220,7 +221,7 @@ func ApproveSignRequestWithArgs(id, password *C.char, gas, gasPrice C.longlong) //ApproveSignRequest instructs backend to complete sending of a given transaction. //export ApproveSignRequest func ApproveSignRequest(id, password *C.char) *C.char { - result := statusAPI.ApproveSignRequest(C.GoString(id), C.GoString(password)) + result := statusBackend.ApproveSignRequest(C.GoString(id), C.GoString(password)) return prepareApproveSignRequestResponse(result, id) } @@ -265,7 +266,7 @@ func ApproveSignRequests(ids, password *C.char) *C.char { txIDs[i] = id } - results := statusAPI.ApproveSignRequests(txIDs, C.GoString(password)) + results := statusBackend.ApproveSignRequests(txIDs, C.GoString(password)) for txID, result := range results { txResult := SignRequestResult{ ID: txID, @@ -290,7 +291,7 @@ func ApproveSignRequests(ids, password *C.char) *C.char { //DiscardSignRequest discards a given transaction from transaction queue //export DiscardSignRequest func DiscardSignRequest(id *C.char) *C.char { - err := statusAPI.DiscardSignRequest(C.GoString(id)) + err := statusBackend.DiscardSignRequest(C.GoString(id)) errString := "" if err != nil { @@ -328,7 +329,7 @@ func DiscardSignRequests(ids *C.char) *C.char { txIDs[i] = id } - results := statusAPI.DiscardSignRequests(txIDs) + results := statusBackend.DiscardSignRequests(txIDs) for txID, err := range results { out.Results[txID] = DiscardSignRequestResult{ ID: txID, @@ -349,35 +350,35 @@ func DiscardSignRequests(ids *C.char) *C.char { //InitJail setup initial JavaScript //export InitJail func InitJail(js *C.char) { - statusAPI.SetJailBaseJS(C.GoString(js)) + statusBackend.JailManager().SetBaseJS(C.GoString(js)) } //Parse creates a new jail cell context and executes provided JavaScript code. //DEPRECATED in favour of CreateAndInitCell. //export Parse func Parse(chatID *C.char, js *C.char) *C.char { - res := statusAPI.CreateAndInitCell(C.GoString(chatID), C.GoString(js)) + res := statusBackend.JailManager().CreateAndInitCell(C.GoString(chatID), C.GoString(js)) return C.CString(res) } //CreateAndInitCell creates a new jail cell context and executes provided JavaScript code. //export CreateAndInitCell func CreateAndInitCell(chatID *C.char, js *C.char) *C.char { - res := statusAPI.CreateAndInitCell(C.GoString(chatID), C.GoString(js)) + res := statusBackend.JailManager().CreateAndInitCell(C.GoString(chatID), C.GoString(js)) return C.CString(res) } //ExecuteJS allows to run arbitrary JS code within a cell. //export ExecuteJS func ExecuteJS(chatID *C.char, code *C.char) *C.char { - res := statusAPI.JailExecute(C.GoString(chatID), C.GoString(code)) + res := statusBackend.JailManager().Execute(C.GoString(chatID), C.GoString(code)) return C.CString(res) } //Call executes given JavaScript function //export Call func Call(chatID *C.char, path *C.char, params *C.char) *C.char { - res := statusAPI.JailCall(C.GoString(chatID), C.GoString(path), C.GoString(params)) + res := statusBackend.JailManager().Call(C.GoString(chatID), C.GoString(path), C.GoString(params)) return C.CString(res) } @@ -455,7 +456,7 @@ func NotifyUsers(message, payloadJSON, tokensArray *C.char) (outCBytes *C.char) return } - err = statusAPI.NotifyUsers(C.GoString(message), payload, tokens...) + err = statusBackend.NotifyUsers(C.GoString(message), payload, tokens...) if err != nil { errString = err.Error() return @@ -467,7 +468,7 @@ func NotifyUsers(message, payloadJSON, tokensArray *C.char) (outCBytes *C.char) // AddPeer adds an enode as a peer. //export AddPeer func AddPeer(enode *C.char) *C.char { - err := statusAPI.StatusNode().AddPeer(C.GoString(enode)) + err := statusBackend.StatusNode().AddPeer(C.GoString(enode)) return makeJSONResponse(err) } @@ -475,11 +476,11 @@ func AddPeer(enode *C.char) *C.char { // by ReactNative (see https://facebook.github.io/react-native/docs/netinfo.html) //export ConnectionChange func ConnectionChange(typ *C.char, expensive C.int) { - statusAPI.ConnectionChange(C.GoString(typ), expensive == 1) + statusBackend.ConnectionChange(C.GoString(typ), expensive == 1) } // AppStateChange handles app state changes (background/foreground). //export AppStateChange func AppStateChange(state *C.char) { - statusAPI.AppStateChange(C.GoString(state)) + statusBackend.AppStateChange(C.GoString(state)) } diff --git a/lib/library_test_utils.go b/lib/library_test_utils.go index 7d631360d..9a8efbe86 100644 --- a/lib/library_test_utils.go +++ b/lib/library_test_utils.go @@ -267,7 +267,7 @@ func testResetChainData(t *testing.T) bool { return false } - EnsureNodeSync(statusAPI.StatusNode().EnsureSync) + EnsureNodeSync(statusBackend.StatusNode().EnsureSync) testCompleteTransaction(t) return true @@ -275,17 +275,17 @@ func testResetChainData(t *testing.T) bool { func testStopResumeNode(t *testing.T) bool { //nolint: gocyclo // to make sure that we start with empty account (which might have gotten populated during previous tests) - if err := statusAPI.Logout(); err != nil { + if err := statusBackend.Logout(); err != nil { t.Fatal(err) } - whisperService, err := statusAPI.StatusNode().WhisperService() + whisperService, err := statusBackend.StatusNode().WhisperService() if err != nil { t.Errorf("whisper service not running: %v", err) } // create an account - address1, pubKey1, _, err := statusAPI.CreateAccount(TestConfig.Account1.Password) + address1, pubKey1, _, err := statusBackend.AccountManager().CreateAccount(TestConfig.Account1.Password) if err != nil { t.Errorf("could not create account: %v", err) return false @@ -366,7 +366,7 @@ func testStopResumeNode(t *testing.T) bool { //nolint: gocyclo time.Sleep(10 * time.Second) // allow to start (instead of using blocking version of start, of filter event) // now, verify that we still have account logged in - whisperService, err = statusAPI.StatusNode().WhisperService() + whisperService, err = statusBackend.StatusNode().WhisperService() if err != nil { t.Errorf("whisper service not running: %v", err) } @@ -417,11 +417,11 @@ func testCallPrivateRPCWithPrivateAPI(t *testing.T) bool { func testCreateChildAccount(t *testing.T) bool { //nolint: gocyclo // to make sure that we start with empty account (which might get populated during previous tests) - if err := statusAPI.Logout(); err != nil { + if err := statusBackend.Logout(); err != nil { t.Fatal(err) } - keyStore, err := statusAPI.StatusNode().AccountKeyStore() + keyStore, err := statusBackend.StatusNode().AccountKeyStore() if err != nil { t.Error(err) return false @@ -475,7 +475,7 @@ func testCreateChildAccount(t *testing.T) bool { //nolint: gocyclo return false } - err = statusAPI.SelectAccount(address, TestConfig.Account1.Password) + err = statusBackend.SelectAccount(address, TestConfig.Account1.Password) if err != nil { t.Errorf("Test failed: could not select account: %v", err) return false @@ -552,10 +552,10 @@ func testCreateChildAccount(t *testing.T) bool { //nolint: gocyclo } func testRecoverAccount(t *testing.T) bool { //nolint: gocyclo - keyStore, _ := statusAPI.StatusNode().AccountKeyStore() + keyStore, _ := statusBackend.StatusNode().AccountKeyStore() // create an account - address, pubKey, mnemonic, err := statusAPI.CreateAccount(TestConfig.Account1.Password) + address, pubKey, mnemonic, err := statusBackend.AccountManager().CreateAccount(TestConfig.Account1.Password) if err != nil { t.Errorf("could not create account: %v", err) return false @@ -643,7 +643,7 @@ func testRecoverAccount(t *testing.T) bool { //nolint: gocyclo } // time to login with recovered data - whisperService, err := statusAPI.StatusNode().WhisperService() + whisperService, err := statusBackend.StatusNode().WhisperService() if err != nil { t.Errorf("whisper service not running: %v", err) } @@ -652,7 +652,7 @@ func testRecoverAccount(t *testing.T) bool { //nolint: gocyclo if whisperService.HasKeyPair(pubKeyCheck) { t.Error("identity already present in whisper") } - err = statusAPI.SelectAccount(addressCheck, TestConfig.Account1.Password) + err = statusBackend.SelectAccount(addressCheck, TestConfig.Account1.Password) if err != nil { t.Errorf("Test failed: could not select account: %v", err) return false @@ -666,20 +666,20 @@ func testRecoverAccount(t *testing.T) bool { //nolint: gocyclo func testAccountSelect(t *testing.T) bool { //nolint: gocyclo // test to see if the account was injected in whisper - whisperService, err := statusAPI.StatusNode().WhisperService() + whisperService, err := statusBackend.StatusNode().WhisperService() if err != nil { t.Errorf("whisper service not running: %v", err) } // create an account - address1, pubKey1, _, err := statusAPI.CreateAccount(TestConfig.Account1.Password) + address1, pubKey1, _, err := statusBackend.AccountManager().CreateAccount(TestConfig.Account1.Password) if err != nil { t.Errorf("could not create account: %v", err) return false } t.Logf("Account created: {address: %s, key: %s}", address1, pubKey1) - address2, pubKey2, _, err := statusAPI.CreateAccount(TestConfig.Account1.Password) + address2, pubKey2, _, err := statusBackend.AccountManager().CreateAccount(TestConfig.Account1.Password) if err != nil { t.Error("Test failed: could not create account") return false @@ -749,14 +749,14 @@ func testAccountSelect(t *testing.T) bool { //nolint: gocyclo } func testAccountLogout(t *testing.T) bool { - whisperService, err := statusAPI.StatusNode().WhisperService() + whisperService, err := statusBackend.StatusNode().WhisperService() if err != nil { t.Errorf("whisper service not running: %v", err) return false } // create an account - address, pubKey, _, err := statusAPI.CreateAccount(TestConfig.Account1.Password) + address, pubKey, _, err := statusBackend.AccountManager().CreateAccount(TestConfig.Account1.Password) if err != nil { t.Errorf("could not create account: %v", err) return false @@ -769,7 +769,7 @@ func testAccountLogout(t *testing.T) bool { } // select/login - err = statusAPI.SelectAccount(address, TestConfig.Account1.Password) + err = statusBackend.SelectAccount(address, TestConfig.Account1.Password) if err != nil { t.Errorf("Test failed: could not select account: %v", err) return false @@ -802,12 +802,12 @@ func testAccountLogout(t *testing.T) bool { } func testCompleteTransaction(t *testing.T) bool { - signRequests := statusAPI.PendingSignRequests() + signRequests := statusBackend.PendingSignRequests() - EnsureNodeSync(statusAPI.StatusNode().EnsureSync) + EnsureNodeSync(statusBackend.StatusNode().EnsureSync) // log into account from which transactions will be sent - if err := statusAPI.SelectAccount(TestConfig.Account1.Address, TestConfig.Account1.Password); err != nil { + if err := statusBackend.SelectAccount(TestConfig.Account1.Address, TestConfig.Account1.Password); err != nil { t.Errorf("cannot select account: %v. Error %q", TestConfig.Account1.Address, err) return false } @@ -849,7 +849,7 @@ func testCompleteTransaction(t *testing.T) bool { }) // this call blocks, up until Complete Transaction is called - txCheckHash, err := statusAPI.SendTransaction(context.TODO(), transactions.SendTxArgs{ + txCheckHash, err := statusBackend.SendTransaction(context.TODO(), transactions.SendTxArgs{ From: account.FromAddress(TestConfig.Account1.Address), To: account.ToAddress(TestConfig.Account2.Address), Value: (*hexutil.Big)(big.NewInt(1000000000000)), @@ -881,10 +881,10 @@ func testCompleteTransaction(t *testing.T) bool { } func testCompleteMultipleQueuedTransactions(t *testing.T) bool { //nolint: gocyclo - signRequests := statusAPI.PendingSignRequests() + signRequests := statusBackend.PendingSignRequests() // log into account from which transactions will be sent - if err := statusAPI.SelectAccount(TestConfig.Account1.Address, TestConfig.Account1.Password); err != nil { + if err := statusBackend.SelectAccount(TestConfig.Account1.Address, TestConfig.Account1.Password); err != nil { t.Errorf("cannot select account: %v", TestConfig.Account1.Address) return false } @@ -913,7 +913,7 @@ func testCompleteMultipleQueuedTransactions(t *testing.T) bool { //nolint: gocyc // this call blocks, and should return when DiscardQueuedTransaction() for a given tx id is called sendTx := func() { - txHashCheck, err := statusAPI.SendTransaction(context.TODO(), transactions.SendTxArgs{ + txHashCheck, err := statusBackend.SendTransaction(context.TODO(), transactions.SendTxArgs{ From: account.FromAddress(TestConfig.Account1.Address), To: account.ToAddress(TestConfig.Account2.Address), Value: (*hexutil.Big)(big.NewInt(1000000000000)), @@ -1013,10 +1013,10 @@ func testCompleteMultipleQueuedTransactions(t *testing.T) bool { //nolint: gocyc } func testDiscardTransaction(t *testing.T) bool { //nolint: gocyclo - signRequests := statusAPI.PendingSignRequests() + signRequests := statusBackend.PendingSignRequests() // log into account from which transactions will be sent - if err := statusAPI.SelectAccount(TestConfig.Account1.Address, TestConfig.Account1.Password); err != nil { + if err := statusBackend.SelectAccount(TestConfig.Account1.Address, TestConfig.Account1.Password); err != nil { t.Errorf("cannot select account: %v", TestConfig.Account1.Address) return false } @@ -1058,7 +1058,7 @@ func testDiscardTransaction(t *testing.T) bool { //nolint: gocyclo } // try completing discarded transaction - err := statusAPI.ApproveSignRequest(string(txID), TestConfig.Account1.Password).Error + err := statusBackend.ApproveSignRequest(string(txID), TestConfig.Account1.Password).Error if err != sign.ErrSignReqNotFound { t.Error("expects tx not found, but call to CompleteTransaction succeeded") return @@ -1094,7 +1094,7 @@ func testDiscardTransaction(t *testing.T) bool { //nolint: gocyclo }) // this call blocks, and should return when DiscardQueuedTransaction() is called - txHashCheck, err := statusAPI.SendTransaction(context.TODO(), transactions.SendTxArgs{ + txHashCheck, err := statusBackend.SendTransaction(context.TODO(), transactions.SendTxArgs{ From: account.FromAddress(TestConfig.Account1.Address), To: account.ToAddress(TestConfig.Account2.Address), Value: (*hexutil.Big)(big.NewInt(1000000000000)), @@ -1126,10 +1126,10 @@ func testDiscardTransaction(t *testing.T) bool { //nolint: gocyclo } func testDiscardMultipleQueuedTransactions(t *testing.T) bool { //nolint: gocyclo - signRequests := statusAPI.PendingSignRequests() + signRequests := statusBackend.PendingSignRequests() // log into account from which transactions will be sent - if err := statusAPI.SelectAccount(TestConfig.Account1.Address, TestConfig.Account1.Password); err != nil { + if err := statusBackend.SelectAccount(TestConfig.Account1.Address, TestConfig.Account1.Password); err != nil { t.Errorf("cannot select account: %v", TestConfig.Account1.Address) return false } @@ -1185,7 +1185,7 @@ func testDiscardMultipleQueuedTransactions(t *testing.T) bool { //nolint: gocycl // this call blocks, and should return when DiscardQueuedTransaction() for a given tx id is called sendTx := func() { - txHashCheck, err := statusAPI.SendTransaction(context.TODO(), transactions.SendTxArgs{ + txHashCheck, err := statusBackend.SendTransaction(context.TODO(), transactions.SendTxArgs{ From: account.FromAddress(TestConfig.Account1.Address), To: account.ToAddress(TestConfig.Account2.Address), Value: (*hexutil.Big)(big.NewInt(1000000000000)), @@ -1472,7 +1472,7 @@ func startTestNode(t *testing.T) <-chan struct{} { // sync if syncRequired { t.Logf("Sync is required") - EnsureNodeSync(statusAPI.StatusNode().EnsureSync) + EnsureNodeSync(statusBackend.StatusNode().EnsureSync) } else { time.Sleep(5 * time.Second) } diff --git a/lib/main.go b/lib/main.go index e3c8ba739..6064e5210 100644 --- a/lib/main.go +++ b/lib/main.go @@ -2,7 +2,7 @@ package main import "github.com/status-im/status-go/api" -var statusAPI = api.NewStatusAPI() +var statusBackend = api.NewStatusBackend() // Technically this package supposed to be a lib for // cross-compilation and usage with Android/iOS, but diff --git a/t/e2e/api/api_test.go b/t/e2e/api/api_test.go index b2505870e..7def1225b 100644 --- a/t/e2e/api/api_test.go +++ b/t/e2e/api/api_test.go @@ -9,7 +9,6 @@ import ( "testing" "time" - "github.com/ethereum/go-ethereum/log" "github.com/status-im/status-go/api" "github.com/status-im/status-go/node" "github.com/status-im/status-go/params" @@ -30,18 +29,18 @@ func TestAPI(t *testing.T) { type APITestSuite struct { suite.Suite - api *api.StatusAPI + backend *api.StatusBackend } func (s *APITestSuite) ensureNodeStopped() { - if err := s.api.StopNode(); err != node.ErrNoRunningNode && err != nil { + if err := s.backend.StopNode(); err != node.ErrNoRunningNode && err != nil { s.NoError(err, "unexpected error") } } func (s *APITestSuite) SetupTest() { - s.api = api.NewStatusAPI() - s.NotNil(s.api) + s.backend = api.NewStatusBackend() + s.NotNil(s.backend) } func (s *APITestSuite) TestCHTUpdate() { @@ -76,29 +75,25 @@ func (s *APITestSuite) TestRaceConditions() { var funcsToTest = []func(*params.NodeConfig){ func(config *params.NodeConfig) { - log.Info("StartNodeAsync()") - s.api.StartNodeAsync(config) - s.T().Logf("StartNodeAsync() for network: %d", config.NetworkID) + s.T().Logf("async call to StartNode() for network: %d", config.NetworkID) + api.RunAsync(func() error { return s.backend.StartNode(config) }) progress <- struct{}{} }, func(config *params.NodeConfig) { - log.Info("StopNodeAsync()") - s.api.StopNodeAsync() - s.T().Logf("StopNodeAsync()") + s.T().Logf("async call to StopNode() for network: %d", config.NetworkID) + api.RunAsync(s.backend.StopNode) progress <- struct{}{} }, func(config *params.NodeConfig) { - log.Info("RestartNodeAsync()") - s.api.RestartNodeAsync() - s.T().Logf("RestartNodeAsync()") + s.T().Logf("async call to RestartNode() for network: %d", config.NetworkID) + api.RunAsync(s.backend.RestartNode) progress <- struct{}{} }, // TODO(adam): quarantined until it uses a different datadir // as otherwise it wipes out cached blockchain data. // func(config *params.NodeConfig) { - // log.Info("ResetChainDataAsync()") - // _, err := s.api.ResetChainDataAsync() - // s.T().Logf("ResetChainDataAsync(), error: %v", err) + // s.T().Logf("async call to ResetChainData() for network: %d", config.NetworkID) + // _, err := s.api.ResetChainData() // progress <- struct{}{} // }, } @@ -141,29 +136,29 @@ func (s *APITestSuite) TestCellsRemovedAfterSwitchAccount() { config, err := MakeTestNodeConfig(GetNetworkID()) require.NoError(err) - err = s.api.StartNode(config) + err = s.backend.StartNode(config) require.NoError(err) - defer s.api.StopNode() //nolint: errcheck + defer s.backend.StopNode() //nolint: errcheck - address1, _, _, err := s.api.AccountManager().CreateAccount(TestConfig.Account1.Password) + address1, _, _, err := s.backend.AccountManager().CreateAccount(TestConfig.Account1.Password) require.NoError(err) - address2, _, _, err := s.api.AccountManager().CreateAccount(TestConfig.Account2.Password) + address2, _, _, err := s.backend.AccountManager().CreateAccount(TestConfig.Account2.Password) require.NoError(err) - err = s.api.SelectAccount(address1, TestConfig.Account1.Password) + err = s.backend.SelectAccount(address1, TestConfig.Account1.Password) require.NoError(err) for i := 0; i < itersCount; i++ { - _, e := s.api.JailManager().CreateCell(getChatID(i)) + _, e := s.backend.JailManager().CreateCell(getChatID(i)) require.NoError(e) } - err = s.api.SelectAccount(address2, TestConfig.Account2.Password) + err = s.backend.SelectAccount(address2, TestConfig.Account2.Password) require.NoError(err) for i := 0; i < itersCount; i++ { - _, e := s.api.JailManager().Cell(getChatID(i)) + _, e := s.backend.JailManager().Cell(getChatID(i)) require.Error(e) } } @@ -178,22 +173,22 @@ func (s *APITestSuite) TestLogoutRemovesCells() { config, err := MakeTestNodeConfig(GetNetworkID()) require.NoError(err) - err = s.api.StartNode(config) + err = s.backend.StartNode(config) require.NoError(err) - defer s.api.StopNode() //nolint: errcheck + defer s.backend.StopNode() //nolint: errcheck - address1, _, _, err := s.api.AccountManager().CreateAccount(TestConfig.Account1.Password) + address1, _, _, err := s.backend.AccountManager().CreateAccount(TestConfig.Account1.Password) require.NoError(err) - err = s.api.SelectAccount(address1, TestConfig.Account1.Password) + err = s.backend.SelectAccount(address1, TestConfig.Account1.Password) require.NoError(err) - s.api.JailManager().CreateAndInitCell(testChatID) + s.backend.JailManager().CreateAndInitCell(testChatID) - err = s.api.Logout() + err = s.backend.Logout() require.NoError(err) - _, err = s.api.JailManager().Cell(testChatID) + _, err = s.backend.JailManager().Cell(testChatID) require.Error(err, "Expected that cells was removed") } @@ -216,14 +211,14 @@ func (s *APITestSuite) TestEventsNodeStartStop() { nodeConfig, err := MakeTestNodeConfig(GetNetworkID()) s.NoError(err) - s.NoError(s.api.StartNode(nodeConfig)) - s.NoError(s.api.StopNode()) + s.NoError(s.backend.StartNode(nodeConfig)) + s.NoError(s.backend.StopNode()) s.verifyEnvelopes(envelopes, signal.EventNodeStarted, signal.EventNodeReady, signal.EventNodeStopped) - s.NoError(s.api.StartNode(nodeConfig)) + s.NoError(s.backend.StartNode(nodeConfig)) s.verifyEnvelopes(envelopes, signal.EventNodeStarted, signal.EventNodeReady) - s.NoError(s.api.RestartNode()) + s.NoError(s.backend.RestartNode()) s.verifyEnvelopes(envelopes, signal.EventNodeStopped, signal.EventNodeStarted, signal.EventNodeReady) - s.NoError(s.api.StopNode()) + s.NoError(s.backend.StopNode()) s.verifyEnvelopes(envelopes, signal.EventNodeStopped) } @@ -266,7 +261,7 @@ func (s *APITestSuite) TestNodeStartCrash() { s.NoError(err) // now try starting using node manager, it should fail (error is irrelevant as it is implementation detail) - s.Error(<-s.api.StartNodeAsync(nodeConfig)) + s.Error(<-api.RunAsync(func() error { return s.backend.StartNode(nodeConfig) })) select { case <-time.After(500 * time.Millisecond): @@ -277,7 +272,7 @@ func (s *APITestSuite) TestNodeStartCrash() { // stop outside node, and re-try s.NoError(outsideNode.Stop()) signalReceived = make(chan struct{}) - s.NoError(<-s.api.StartNodeAsync(nodeConfig)) + s.NoError(<-api.RunAsync(func() error { return s.backend.StartNode(nodeConfig) })) select { case <-time.After(500 * time.Millisecond): @@ -286,5 +281,5 @@ func (s *APITestSuite) TestNodeStartCrash() { } // cleanup - s.NoError(s.api.StopNode()) + s.NoError(s.backend.StopNode()) }