refactor: nim_status -> status_go

Also, `status_go.startWallet` proc should be called with a boolean argument.
This commit is contained in:
Michael Bradley, Jr 2021-03-15 14:24:45 -05:00 committed by Iuri Matias
parent c4e786bae3
commit 016dd3081b
6 changed files with 45 additions and 45 deletions

View File

@ -74,4 +74,4 @@ proc checkPendingTransactions*(self: WalletController) =
self.status.wallet.checkPendingTransactions() # TODO: consider doing this in a spawnAndSend self.status.wallet.checkPendingTransactions() # TODO: consider doing this in a spawnAndSend
proc start*(self: WalletController) = proc start*(self: WalletController) =
status_wallet.startWallet() status_wallet.startWallet(false)

View File

@ -12,7 +12,7 @@ import app/provider/core as provider
import status/signals/core as signals import status/signals/core as signals
import status/libstatus/types import status/libstatus/types
import status/libstatus/accounts/constants import status/libstatus/accounts/constants
import nim_status import status_go
import status/status as statuslib import status/status as statuslib
import ./eventemitter import ./eventemitter
@ -192,7 +192,7 @@ proc mainProc() =
signal_handler(signalsQObjPointer, p0, "receiveSignal") signal_handler(signalsQObjPointer, p0, "receiveSignal")
tearDownForeignThreadGc() tearDownForeignThreadGc()
nim_status.setSignalEventCallback(callback) status_go.setSignalEventCallback(callback)
# Qt main event loop is entered here # Qt main event loop is entered here
# The termination of the loop will be performed when exit() or quit() is called # The termination of the loop will be performed when exit() or quit() is called

View File

@ -1,6 +1,6 @@
import json, os, nimcrypto, uuids, json_serialization, chronicles, strutils import json, os, nimcrypto, uuids, json_serialization, chronicles, strutils
from nim_status import multiAccountGenerateAndDeriveAddresses, generateAlias, identicon, saveAccountAndLogin, login, openAccounts from status_go import multiAccountGenerateAndDeriveAddresses, generateAlias, identicon, saveAccountAndLogin, login, openAccounts
import core import core
import utils as utils import utils as utils
import types as types import types as types
@ -31,7 +31,7 @@ proc getNodeConfig*(fleetConfig: FleetConfig, installationId: string, networkCon
result["ShhextConfig"]["InstallationID"] = newJString(installationId) result["ShhextConfig"]["InstallationID"] = newJString(installationId)
# TODO: commented since it's not necessary (we do the connections thru C bindings). Enable it thru an option once status-nodes are able to be configured in desktop # TODO: commented since it's not necessary (we do the connections thru C bindings). Enable it thru an option once status-nodes are able to be configured in desktop
# result["ListenAddr"] = if existsEnv("STATUS_PORT"): newJString("0.0.0.0:" & $getEnv("STATUS_PORT")) else: newJString("0.0.0.0:30305") # result["ListenAddr"] = if existsEnv("STATUS_PORT"): newJString("0.0.0.0:" & $getEnv("STATUS_PORT")) else: newJString("0.0.0.0:30305")
proc getNodeConfig*(fleetConfig: FleetConfig, installationId: string, currentNetwork: string = constants.DEFAULT_NETWORK_NAME, fleet: Fleet = Fleet.PROD): JsonNode = proc getNodeConfig*(fleetConfig: FleetConfig, installationId: string, currentNetwork: string = constants.DEFAULT_NETWORK_NAME, fleet: Fleet = Fleet.PROD): JsonNode =
let networkConfig = getNetworkConfig(currentNetwork) let networkConfig = getNetworkConfig(currentNetwork)
result = getNodeConfig(fleetConfig, installationId, networkConfig, fleet) result = getNodeConfig(fleetConfig, installationId, networkConfig, fleet)
@ -50,14 +50,14 @@ proc generateAddresses*(n = 5): seq[GeneratedAccount] =
"bip39Passphrase": "", "bip39Passphrase": "",
"paths": [PATH_WALLET_ROOT, PATH_EIP_1581, PATH_WHISPER, PATH_DEFAULT_WALLET] "paths": [PATH_WALLET_ROOT, PATH_EIP_1581, PATH_WHISPER, PATH_DEFAULT_WALLET]
} }
let generatedAccounts = $nim_status.multiAccountGenerateAndDeriveAddresses($multiAccountConfig) let generatedAccounts = $status_go.multiAccountGenerateAndDeriveAddresses($multiAccountConfig)
result = Json.decode(generatedAccounts, seq[GeneratedAccount]) result = Json.decode(generatedAccounts, seq[GeneratedAccount])
proc generateAlias*(publicKey: string): string = proc generateAlias*(publicKey: string): string =
result = $nim_status.generateAlias(publicKey) result = $status_go.generateAlias(publicKey)
proc generateIdenticon*(publicKey: string): string = proc generateIdenticon*(publicKey: string): string =
result = $nim_status.identicon(publicKey) result = $status_go.identicon(publicKey)
proc ensureDir(dirname: string) = proc ensureDir(dirname: string) =
if not existsDir(dirname): if not existsDir(dirname):
@ -68,7 +68,7 @@ proc initNode*() =
ensureDir(DATADIR) ensureDir(DATADIR)
ensureDir(KEYSTOREDIR) ensureDir(KEYSTOREDIR)
discard $nim_status.initKeystore(KEYSTOREDIR) discard $status_go.initKeystore(KEYSTOREDIR)
proc parseIdentityImage*(images: JsonNode): IdentityImage = proc parseIdentityImage*(images: JsonNode): IdentityImage =
result = IdentityImage() result = IdentityImage()
@ -81,7 +81,7 @@ proc parseIdentityImage*(images: JsonNode): IdentityImage =
result.large = image["uri"].getStr result.large = image["uri"].getStr
proc openAccounts*(): seq[NodeAccount] = proc openAccounts*(): seq[NodeAccount] =
let strNodeAccounts = nim_status.openAccounts(DATADIR).parseJson let strNodeAccounts = status_go.openAccounts(DATADIR).parseJson
# FIXME fix serialization # FIXME fix serialization
result = @[] result = @[]
if (strNodeAccounts.kind != JNull): if (strNodeAccounts.kind != JNull):
@ -95,9 +95,9 @@ proc openAccounts*(): seq[NodeAccount] =
) )
if (account{"images"}.kind != JNull): if (account{"images"}.kind != JNull):
nodeAccount.identityImage = parseIdentityImage(account["images"]) nodeAccount.identityImage = parseIdentityImage(account["images"])
result.add(nodeAccount) result.add(nodeAccount)
proc saveAccountAndLogin*( proc saveAccountAndLogin*(
account: GeneratedAccount, account: GeneratedAccount,
@ -125,7 +125,7 @@ proc saveAccountAndLogin*(
} }
] ]
var savedResult = $nim_status.saveAccountAndLogin(accountData, hashedPassword, settingsJSON, configJSON, $subaccountData) var savedResult = $status_go.saveAccountAndLogin(accountData, hashedPassword, settingsJSON, configJSON, $subaccountData)
let parsedSavedResult = savedResult.parseJson let parsedSavedResult = savedResult.parseJson
let error = parsedSavedResult["error"].getStr let error = parsedSavedResult["error"].getStr
@ -143,7 +143,7 @@ proc storeDerivedAccounts*(account: GeneratedAccount, password: string, paths: s
"paths": paths, "paths": paths,
"password": hashedPassword "password": hashedPassword
} }
let response = $nim_status.multiAccountStoreDerivedAccounts($multiAccount); let response = $status_go.multiAccountStoreDerivedAccounts($multiAccount);
try: try:
result = Json.decode($response, MultiAccounts) result = Json.decode($response, MultiAccounts)
@ -202,12 +202,12 @@ proc setupAccount*(fleetConfig: FleetConfig, account: GeneratedAccount, password
finally: finally:
# TODO this is needed for now for the retrieving of past messages. We'll either move or remove it later # TODO this is needed for now for the retrieving of past messages. We'll either move or remove it later
let peer = "enode://44160e22e8b42bd32a06c1532165fa9e096eebedd7fa6d6e5f8bbef0440bc4a4591fe3651be68193a7ec029021cdb496cfe1d7f9f1dc69eb99226e6f39a7a5d4@35.225.221.245:443" let peer = "enode://44160e22e8b42bd32a06c1532165fa9e096eebedd7fa6d6e5f8bbef0440bc4a4591fe3651be68193a7ec029021cdb496cfe1d7f9f1dc69eb99226e6f39a7a5d4@35.225.221.245:443"
discard nim_status.addPeer(peer) discard status_go.addPeer(peer)
proc login*(nodeAccount: NodeAccount, password: string): NodeAccount = proc login*(nodeAccount: NodeAccount, password: string): NodeAccount =
let hashedPassword = hashPassword(password) let hashedPassword = hashPassword(password)
let account = nodeAccount.toAccount let account = nodeAccount.toAccount
let loginResult = $nim_status.login($toJson(account), hashedPassword) let loginResult = $status_go.login($toJson(account), hashedPassword)
let error = parseJson(loginResult)["error"].getStr let error = parseJson(loginResult)["error"].getStr
if error == "": if error == "":
@ -223,12 +223,12 @@ proc loadAccount*(address: string, password: string): GeneratedAccount =
"address": address, "address": address,
"password": hashedPassword "password": hashedPassword
} }
let loadResult = $nim_status.multiAccountLoadAccount($inputJson) let loadResult = $status_go.multiAccountLoadAccount($inputJson)
result = Json.decode(loadResult, GeneratedAccount) result = Json.decode(loadResult, GeneratedAccount)
proc verifyAccountPassword*(address: string, password: string): bool = proc verifyAccountPassword*(address: string, password: string): bool =
let hashedPassword = hashPassword(password) let hashedPassword = hashPassword(password)
let verifyResult = $nim_status.verifyAccountPassword(KEYSTOREDIR, address, hashedPassword) let verifyResult = $status_go.verifyAccountPassword(KEYSTOREDIR, address, hashedPassword)
let error = parseJson(verifyResult)["error"].getStr let error = parseJson(verifyResult)["error"].getStr
if error == "": if error == "":
@ -241,17 +241,17 @@ proc multiAccountImportMnemonic*(mnemonic: string): GeneratedAccount =
"mnemonicPhrase": mnemonic, "mnemonicPhrase": mnemonic,
"Bip39Passphrase": "" "Bip39Passphrase": ""
} }
# nim_status.multiAccountImportMnemonic never results in an error given ANY input # status_go.multiAccountImportMnemonic never results in an error given ANY input
let importResult = $nim_status.multiAccountImportMnemonic($mnemonicJson) let importResult = $status_go.multiAccountImportMnemonic($mnemonicJson)
result = Json.decode(importResult, GeneratedAccount) result = Json.decode(importResult, GeneratedAccount)
proc MultiAccountImportPrivateKey*(privateKey: string): GeneratedAccount = proc MultiAccountImportPrivateKey*(privateKey: string): GeneratedAccount =
let privateKeyJson = %* { let privateKeyJson = %* {
"privateKey": privateKey "privateKey": privateKey
} }
# nim_status.MultiAccountImportPrivateKey never results in an error given ANY input # status_go.MultiAccountImportPrivateKey never results in an error given ANY input
try: try:
let importResult = $nim_status.multiAccountImportPrivateKey($privateKeyJson) let importResult = $status_go.multiAccountImportPrivateKey($privateKeyJson)
result = Json.decode(importResult, GeneratedAccount) result = Json.decode(importResult, GeneratedAccount)
except Exception as e: except Exception as e:
error "Error getting account from private key", msg=e.msg error "Error getting account from private key", msg=e.msg
@ -265,7 +265,7 @@ proc storeDerivedWallet*(account: GeneratedAccount, password: string, walletInde
"paths": [derivationPath], "paths": [derivationPath],
"password": hashedPassword "password": hashedPassword
} }
let response = parseJson($nim_status.multiAccountStoreDerivedAccounts($multiAccount)); let response = parseJson($status_go.multiAccountStoreDerivedAccounts($multiAccount));
let error = response{"error"}.getStr let error = response{"error"}.getStr
if error == "": if error == "":
debug "Wallet stored succesfully" debug "Wallet stored succesfully"
@ -274,7 +274,7 @@ proc storeDerivedWallet*(account: GeneratedAccount, password: string, walletInde
proc storePrivateKeyAccount*(account: GeneratedAccount, password: string) = proc storePrivateKeyAccount*(account: GeneratedAccount, password: string) =
let hashedPassword = hashPassword(password) let hashedPassword = hashPassword(password)
let response = parseJson($nim_status.multiAccountStoreAccount($(%*{"accountID": account.id, "password": hashedPassword}))); let response = parseJson($status_go.multiAccountStoreAccount($(%*{"accountID": account.id, "password": hashedPassword})));
let error = response{"error"}.getStr let error = response{"error"}.getStr
if error == "": if error == "":
debug "Wallet stored succesfully" debug "Wallet stored succesfully"
@ -349,9 +349,9 @@ proc deriveWallet*(accountId: string, walletIndex: int): DerivedAccount =
"accountID": accountId, "accountID": accountId,
"paths": [path] "paths": [path]
} }
let deriveResult = parseJson($nim_status.multiAccountDeriveAddresses($deriveJson)) let deriveResult = parseJson($status_go.multiAccountDeriveAddresses($deriveJson))
result = DerivedAccount( result = DerivedAccount(
address: deriveResult[path]["address"].getStr, address: deriveResult[path]["address"].getStr,
publicKey: deriveResult[path]["publicKey"].getStr) publicKey: deriveResult[path]["publicKey"].getStr)
proc deriveAccounts*(accountId: string): MultiAccounts = proc deriveAccounts*(accountId: string): MultiAccounts =
@ -359,11 +359,11 @@ proc deriveAccounts*(accountId: string): MultiAccounts =
"accountID": accountId, "accountID": accountId,
"paths": [PATH_WALLET_ROOT, PATH_EIP_1581, PATH_WHISPER, PATH_DEFAULT_WALLET] "paths": [PATH_WALLET_ROOT, PATH_EIP_1581, PATH_WHISPER, PATH_DEFAULT_WALLET]
} }
let deriveResult = $nim_status.multiAccountDeriveAddresses($deriveJson) let deriveResult = $status_go.multiAccountDeriveAddresses($deriveJson)
result = Json.decode(deriveResult, MultiAccounts) result = Json.decode(deriveResult, MultiAccounts)
proc logout*(): StatusGoError = proc logout*(): StatusGoError =
result = Json.decode($nim_status.logout(), StatusGoError) result = Json.decode($status_go.logout(), StatusGoError)
proc storeIdentityImage*(keyUID: string, imagePath: string, aX, aY, bX, bY: int): IdentityImage = proc storeIdentityImage*(keyUID: string, imagePath: string, aX, aY, bX, bY: int): IdentityImage =
let response = callPrivateRPC("multiaccounts_storeIdentityImage", %* [keyUID, imagePath, aX, aY, bX, bY]).parseJson let response = callPrivateRPC("multiaccounts_storeIdentityImage", %* [keyUID, imagePath, aX, aY, bX, bY]).parseJson

View File

@ -1,14 +1,14 @@
import json, nimcrypto, chronicles import json, nimcrypto, chronicles
import nim_status, utils import status_go, utils
logScope: logScope:
topics = "rpc" topics = "rpc"
proc callRPC*(inputJSON: string): string = proc callRPC*(inputJSON: string): string =
return $nim_status.callRPC(inputJSON) return $status_go.callRPC(inputJSON)
proc callPrivateRPCRaw*(inputJSON: string): string = proc callPrivateRPCRaw*(inputJSON: string): string =
return $nim_status.callPrivateRPC(inputJSON) return $status_go.callPrivateRPC(inputJSON)
proc callPrivateRPC*(methodName: string, payload = %* []): string = proc callPrivateRPC*(methodName: string, payload = %* []): string =
try: try:
@ -18,7 +18,7 @@ proc callPrivateRPC*(methodName: string, payload = %* []): string =
"params": %payload "params": %payload
} }
debug "callPrivateRPC", rpc_method=methodName debug "callPrivateRPC", rpc_method=methodName
let response = nim_status.callPrivateRPC($inputJSON) let response = status_go.callPrivateRPC($inputJSON)
result = $response result = $response
if parseJSON(result).hasKey("error"): if parseJSON(result).hasKey("error"):
error "rpc response error", result = result error "rpc response error", result = result
@ -27,7 +27,7 @@ proc callPrivateRPC*(methodName: string, payload = %* []): string =
proc sendTransaction*(inputJSON: string, password: string): string = proc sendTransaction*(inputJSON: string, password: string): string =
var hashed_password = "0x" & $keccak_256.digest(password) var hashed_password = "0x" & $keccak_256.digest(password)
return $nim_status.sendTransaction(inputJSON, hashed_password) return $status_go.sendTransaction(inputJSON, hashed_password)
proc startMessenger*() = proc startMessenger*() =
discard callPrivateRPC("startMessenger".prefix) discard callPrivateRPC("startMessenger".prefix)
@ -51,7 +51,7 @@ proc getTransfersByAddress*(address: string, toBlock: string, limit: string): st
result = callPrivateRPC("wallet_getTransfersByAddress", %* [address, toBlock, limit]) result = callPrivateRPC("wallet_getTransfersByAddress", %* [address, toBlock, limit])
proc signMessage*(rpcParams: string): string = proc signMessage*(rpcParams: string): string =
return $nim_status.signMessage(rpcParams) return $status_go.signMessage(rpcParams)
proc signTypedData*(data: string, address: string, password: string): string = proc signTypedData*(data: string, address: string, password: string): string =
return $nim_status.signTypedData(data, address, password) return $status_go.signTypedData(data, address, password)

View File

@ -1,7 +1,7 @@
import json, json, options, json_serialization, stint, chronicles import json, json, options, json_serialization, stint, chronicles
import core, types, utils, strutils, strformat import core, types, utils, strutils, strformat
import utils import utils
from nim_status import validateMnemonic, startWallet from status_go import validateMnemonic, startWallet
import ../wallet/account import ../wallet/account
import web3/ethtypes import web3/ethtypes
import ./types import ./types
@ -37,7 +37,7 @@ proc getTransfersByAddress*(address: string, blockNumber: string = "latest"): se
try: try:
let response = getBlockByNumber(blockNumber) let response = getBlockByNumber(blockNumber)
let latestBlock = parseJson(response)["result"] let latestBlock = parseJson(response)["result"]
let transactionsResponse = getTransfersByAddress(address, latestBlock["number"].getStr, "0x14") let transactionsResponse = getTransfersByAddress(address, latestBlock["number"].getStr, "0x14")
let transactions = parseJson(transactionsResponse)["result"] let transactions = parseJson(transactionsResponse)["result"]
var accountTransactions: seq[types.Transaction] = @[] var accountTransactions: seq[types.Transaction] = @[]
@ -73,7 +73,7 @@ proc getBalance*(address: string): string =
let response = parseJson(callPrivateRPC("eth_getBalance", payload)) let response = parseJson(callPrivateRPC("eth_getBalance", payload))
if response.hasKey("error"): if response.hasKey("error"):
raise newException(RpcException, "Error getting balance: " & $response["error"]) raise newException(RpcException, "Error getting balance: " & $response["error"])
else: else:
result = response["result"].str result = response["result"].str
proc hex2Eth*(input: string): string = proc hex2Eth*(input: string): string =
@ -81,10 +81,10 @@ proc hex2Eth*(input: string): string =
result = utils.wei2Eth(value) result = utils.wei2Eth(value)
proc validateMnemonic*(mnemonic: string): string = proc validateMnemonic*(mnemonic: string): string =
result = $nim_status.validateMnemonic(mnemonic) result = $status_go.validateMnemonic(mnemonic)
proc startWallet*() = proc startWallet*(watchNewBlocks: bool) =
discard nim_status.startWallet() # TODO: true to watch trx discard status_go.startWallet(watchNewBlocks) # TODO: true to watch trx
proc hex2Token*(input: string, decimals: int): string = proc hex2Token*(input: string, decimals: int): string =
var value = fromHex(Stuint[256], input) var value = fromHex(Stuint[256], input)
@ -92,10 +92,10 @@ proc hex2Token*(input: string, decimals: int): string =
var i = value.div(p) var i = value.div(p)
var r = value.mod(p) var r = value.mod(p)
var leading_zeros = "0".repeat(decimals - ($r).len) var leading_zeros = "0".repeat(decimals - ($r).len)
var d = fmt"{leading_zeros}{$r}" var d = fmt"{leading_zeros}{$r}"
result = $i result = $i
if(r > 0): result = fmt"{result}.{d}" if(r > 0): result = fmt"{result}.{d}"
proc trackPendingTransaction*(transactionHash: string, fromAddress: string, toAddress: string, trxType: PendingTransactionType, data: string) = proc trackPendingTransaction*(transactionHash: string, fromAddress: string, toAddress: string, trxType: PendingTransactionType, data: string) =
let blockNumber = parseInt($fromHex(Stuint[256], getBlockByNumber("latest").parseJson()["result"]["number"].getStr)) let blockNumber = parseInt($fromHex(Stuint[256], getBlockByNumber("latest").parseJson()["result"]["number"].getStr))
let payload = %* [{"transactionHash": transactionHash, "blockNumber": blockNumber, "from_address": fromAddress, "to_address": toAddress, "type": $trxType, "data": data}] let payload = %* [{"transactionHash": transactionHash, "blockNumber": blockNumber, "from_address": fromAddress, "to_address": toAddress, "type": $trxType, "data": data}]
@ -108,7 +108,7 @@ proc getPendingTransactions*(): string =
except Exception as e: except Exception as e:
error "Error getting pending transactions (possible dev Infura key)", msg = e.msg error "Error getting pending transactions (possible dev Infura key)", msg = e.msg
result = "" result = ""
proc getPendingOutboundTransactionsByAddress*(address: string): string = proc getPendingOutboundTransactionsByAddress*(address: string): string =
let payload = %* [address] let payload = %* [address]

@ -1 +1 @@
Subproject commit bbdbe2a7ebb75bf228ddc553126caa96ec202f18 Subproject commit f1ec58561d7b48f6c8b664f3806fd8a113164fba