status-go/services/accounts/accounts.go

342 lines
8.3 KiB
Go
Raw Normal View History

package accounts
import (
"context"
"errors"
"fmt"
"strings"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/event"
2020-01-02 09:10:19 +00:00
status-im/status-react#9203 Faster tx fetching with less request *** How it worked before this PR on multiaccount creation: - On multiacc creation we scanned chain for eth and erc20 transfers. For each address of a new empty multiaccount this scan required 1. two `eth_getBalance` requests to find out that there is no any balance change between zero and the last block, for eth transfers 2. and `chain-size/100000` (currently ~100) `eth_getLogs` requests, for erc20 transfers - For some reason we scanned an address of the chat account as well, and also accounts were not deduplicated. So even for an empty multiacc we scanned chain twice for each chat and main wallet addresses, in result app had to execute about 400 requests. - As mentioned above, `eth_getBalance` requests were used to check if there were any eth transfers, and that caused empty history in case if user already used all available eth (so that both zero and latest blocks show 0 eth for an address). There might have been transactions but we wouldn't fetch/show them. - There was no upper limit for the number of rpc requests during the scan, so it could require indefinite number of requests; the scanning algorithm was written so that we persisted the whole history of transactions or tried to scan form the beginning again in case of failure, giving up only after 10 minutes of failures. In result addresses with sufficient number of transactions would never be fully scanned and during these 10 minutes app could use gigabytes of internet data. - Failures were caused by `eth_getBlockByNumber`/`eth_getBlockByHash` requests. These requests return significantly bigger responses than `eth_getBalance`/`eth_transactionsCount` and it is likely that execution of thousands of them in parallel caused failures for accounts with hundreds of transactions. Even for an account with 12k we could successfully determine blocks with transaction in a few minutes using `eth_getBalance` requests, but `eth_getBlock...` couldn't be processed for this acc. - There was no caching for for `eth_getBalance` requests, and this caused in average 3-4 times more such requests than is needed. *** How it works now on multiaccount creation: - On multiacc creation we scan chain for last ~30 eth transactions and then check erc20 in the range where these eth transactions were found. For an empty address in multiacc this means: 1. two `eth_getBalance` transactions to determine that there was no balance change between zero and the last block; two `eth_transactionsCount` requests to determine there are no outgoing transactions for this address; total 4 requests for eth transfers 2. 20 `eth_getLogs` for erc20 transfers. This number can be lowered, but that's not a big deal - Deduplication of addresses is added and also we don't scan chat account, so a new multiacc requires ~25 (we also request latest block number and probably execute a few other calls) request to determine that multiacc is empty (comparing to ~400 before) - In case if address contains transactions we: 1. determine the range which contains 20-25 outgoing eth/erc20 transactions. This usually requires up to 10 `eth_transactionCount` requests 2. then we scan chain for eth transfers using `eth_getBalance` and `eth_transactionCount` (for double checking zero balances) 3. we make sure that we do not scan db for more than 30 blocks with transfers. That's important for accounts with mostly incoming transactions, because the range found on the first step might contain any number of incoming transfers, but only 20-25 outgoing transactions 4. when we found ~30 blocks in a given range, we update initial range `from` block using the oldest found block 5. and now we scan db for erc20transfers using `eth_getLogs` `oldest-found-eth-block`-`latest-block`, we make not more than 20 calls 6. when all blocks which contain incoming/outgoing transfers for a given address are found, we save these blocks to db and mark that transfers from these blocks are still to be fetched 7. Then we select latest ~30 (the number can be adjusted) blocks from these which were found and fetch transfers, this requires 3-4 requests per transfer. 8. we persist scanned range so that we know were to start next time 9. we dispatch an event which tells client that transactions are found 10. client fetches latest 20 transfers - when user presses "fetch more" button we check if app's db contains next 20 transfers, if not we scan chain again and return transfers after small fixes
2019-12-18 11:01:46 +00:00
"github.com/ethereum/go-ethereum/log"
"github.com/status-im/status-go/account"
2019-12-11 13:59:37 +00:00
"github.com/status-im/status-go/eth-node/types"
"github.com/status-im/status-go/multiaccounts/accounts"
Sync Settings (#2478) * Sync Settings * Added valueHandlers and Database singleton Some issues remain, need a way to comparing incoming sql.DB to check if the connection is to a different file or not. Maybe make singleton instance per filename * Added functionality to check the sqlite filename * Refactor of Database.SaveSyncSettings to be used as a handler * Implemented inteface for setting sync protobuf factories * Refactored and completed adhoc send setting sync * Tidying up * Immutability refactor * Refactor settings into dedicated package * Breakout structs * Tidy up * Refactor of bulk settings sync * Bug fixes * Addressing feedback * Fix code dropped during rebase * Fix for db closed * Fix for node config related crashes * Provisional fix for type assertion - issue 2 * Adding robust type assertion checks * Partial fix for null literal db storage and json encoding * Fix for passively handling nil sql.DB, and checking if elem has len and if len is 0 * Added test for preferred name behaviour * Adding saved sync settings to MessengerResponse * Completed granular initial sync and clock from network on save * add Settings to isEmpty * Refactor of protobufs, partially done * Added syncSetting receiver handling, some bug fixes * Fix for sticker packs * Implement inactive flag on sync protobuf factory * Refactor of types and structs * Added SettingField.CanSync functionality * Addressing rebase artifact * Refactor of Setting SELECT queries * Refactor of string return queries * VERSION bump and migration index bump * Deactiveate Sync Settings * Deactiveated preferred_name and send_status_updates Co-authored-by: Andrea Maria Piana <andrea.maria.piana@gmail.com>
2022-03-23 18:47:00 +00:00
"github.com/status-im/status-go/multiaccounts/settings"
"github.com/status-im/status-go/params"
)
2022-04-11 16:35:18 +00:00
const pathWalletRoot = "m/44'/60'/0'/0"
const pathDefaultWallet = pathWalletRoot + "/0"
func NewAccountsAPI(manager *account.GethManager, config *params.NodeConfig, db *accounts.Database, feed *event.Feed) *API {
return &API{manager, config, db, feed}
}
// API is class with methods available over RPC.
type API struct {
manager *account.GethManager
config *params.NodeConfig
db *accounts.Database
feed *event.Feed
}
type DerivedAddress struct {
Address common.Address `json:"address"`
Path string `json:"path"`
HasActivity bool `json:"hasActivity"`
AlreadyCreated bool `json:"alreadyCreated"`
}
func (api *API) SaveAccounts(ctx context.Context, accounts []accounts.Account) error {
status-im/status-react#9203 Faster tx fetching with less request *** How it worked before this PR on multiaccount creation: - On multiacc creation we scanned chain for eth and erc20 transfers. For each address of a new empty multiaccount this scan required 1. two `eth_getBalance` requests to find out that there is no any balance change between zero and the last block, for eth transfers 2. and `chain-size/100000` (currently ~100) `eth_getLogs` requests, for erc20 transfers - For some reason we scanned an address of the chat account as well, and also accounts were not deduplicated. So even for an empty multiacc we scanned chain twice for each chat and main wallet addresses, in result app had to execute about 400 requests. - As mentioned above, `eth_getBalance` requests were used to check if there were any eth transfers, and that caused empty history in case if user already used all available eth (so that both zero and latest blocks show 0 eth for an address). There might have been transactions but we wouldn't fetch/show them. - There was no upper limit for the number of rpc requests during the scan, so it could require indefinite number of requests; the scanning algorithm was written so that we persisted the whole history of transactions or tried to scan form the beginning again in case of failure, giving up only after 10 minutes of failures. In result addresses with sufficient number of transactions would never be fully scanned and during these 10 minutes app could use gigabytes of internet data. - Failures were caused by `eth_getBlockByNumber`/`eth_getBlockByHash` requests. These requests return significantly bigger responses than `eth_getBalance`/`eth_transactionsCount` and it is likely that execution of thousands of them in parallel caused failures for accounts with hundreds of transactions. Even for an account with 12k we could successfully determine blocks with transaction in a few minutes using `eth_getBalance` requests, but `eth_getBlock...` couldn't be processed for this acc. - There was no caching for for `eth_getBalance` requests, and this caused in average 3-4 times more such requests than is needed. *** How it works now on multiaccount creation: - On multiacc creation we scan chain for last ~30 eth transactions and then check erc20 in the range where these eth transactions were found. For an empty address in multiacc this means: 1. two `eth_getBalance` transactions to determine that there was no balance change between zero and the last block; two `eth_transactionsCount` requests to determine there are no outgoing transactions for this address; total 4 requests for eth transfers 2. 20 `eth_getLogs` for erc20 transfers. This number can be lowered, but that's not a big deal - Deduplication of addresses is added and also we don't scan chat account, so a new multiacc requires ~25 (we also request latest block number and probably execute a few other calls) request to determine that multiacc is empty (comparing to ~400 before) - In case if address contains transactions we: 1. determine the range which contains 20-25 outgoing eth/erc20 transactions. This usually requires up to 10 `eth_transactionCount` requests 2. then we scan chain for eth transfers using `eth_getBalance` and `eth_transactionCount` (for double checking zero balances) 3. we make sure that we do not scan db for more than 30 blocks with transfers. That's important for accounts with mostly incoming transactions, because the range found on the first step might contain any number of incoming transfers, but only 20-25 outgoing transactions 4. when we found ~30 blocks in a given range, we update initial range `from` block using the oldest found block 5. and now we scan db for erc20transfers using `eth_getLogs` `oldest-found-eth-block`-`latest-block`, we make not more than 20 calls 6. when all blocks which contain incoming/outgoing transfers for a given address are found, we save these blocks to db and mark that transfers from these blocks are still to be fetched 7. Then we select latest ~30 (the number can be adjusted) blocks from these which were found and fetch transfers, this requires 3-4 requests per transfer. 8. we persist scanned range so that we know were to start next time 9. we dispatch an event which tells client that transactions are found 10. client fetches latest 20 transfers - when user presses "fetch more" button we check if app's db contains next 20 transfers, if not we scan chain again and return transfers after small fixes
2019-12-18 11:01:46 +00:00
log.Info("[AccountsAPI::SaveAccounts]")
err := api.db.SaveAccounts(accounts)
if err != nil {
return err
}
api.feed.Send(accounts)
return nil
}
func (api *API) GetAccounts(ctx context.Context) ([]accounts.Account, error) {
return api.db.GetAccounts()
}
2019-12-11 13:59:37 +00:00
func (api *API) DeleteAccount(ctx context.Context, address types.Address) error {
return api.db.DeleteAccount(address)
}
func (api *API) AddAccountWatch(ctx context.Context, address string, name string, color string, emoji string) error {
account := accounts.Account{
Address: types.Address(common.HexToAddress(address)),
Type: "watch",
Name: name,
Emoji: emoji,
Color: color,
}
return api.SaveAccounts(ctx, []accounts.Account{account})
}
func (api *API) AddAccountWithMnemonic(
ctx context.Context,
mnemonic string,
password string,
name string,
color string,
emoji string,
) error {
return api.addAccountWithMnemonic(ctx, mnemonic, password, name, color, emoji, pathWalletRoot)
}
func (api *API) AddAccountWithMnemonicAndPath(
ctx context.Context,
mnemonic string,
password string,
name string,
color string,
emoji string,
path string,
) error {
return api.addAccountWithMnemonic(ctx, mnemonic, password, name, color, emoji, path)
}
func (api *API) AddAccountWithPrivateKey(
ctx context.Context,
privateKey string,
password string,
name string,
color string,
emoji string,
) error {
err := api.verifyPassword(password)
if err != nil {
return err
}
info, err := api.manager.AccountsGenerator().ImportPrivateKey(privateKey)
if err != nil {
return err
}
addressExists, err := api.db.AddressExists(types.Address(common.HexToAddress(info.Address)))
if err != nil {
return err
}
if addressExists {
return errors.New("account already exists")
}
_, err = api.manager.AccountsGenerator().StoreAccount(info.ID, password)
if err != nil {
return err
}
account := accounts.Account{
Address: types.Address(common.HexToAddress(info.Address)),
PublicKey: types.HexBytes(info.PublicKey),
Type: "key",
Name: name,
Emoji: emoji,
Color: color,
Path: pathDefaultWallet,
}
return api.SaveAccounts(ctx, []accounts.Account{account})
}
func (api *API) GenerateAccount(
ctx context.Context,
password string,
name string,
color string,
emoji string,
) error {
address, err := api.db.GetWalletRoodAddress()
if err != nil {
return err
}
latestDerivedPath, err := api.db.GetLatestDerivedPath()
if err != nil {
return err
}
newDerivedPath := latestDerivedPath + 1
path := fmt.Sprint(pathWalletRoot, "/", newDerivedPath)
err = api.generateAccount(ctx, password, name, color, emoji, path, address.Hex())
if err != nil {
return err
}
err = api.db.SaveSettingField(settings.LatestDerivedPath, newDerivedPath)
if err != nil {
return err
}
return err
}
func (api *API) GenerateAccountWithDerivedPath(
ctx context.Context,
password string,
name string,
color string,
emoji string,
path string,
derivedFrom string,
) error {
return api.generateAccount(ctx, password, name, color, emoji, path, derivedFrom)
}
func (api *API) GetDerivedAddressesForPath(password string, derivedFrom string, path string, pageSize int, pageNumber int) ([]*DerivedAddress, error) {
info, err := api.manager.AccountsGenerator().LoadAccount(derivedFrom, password)
if err != nil {
return nil, err
}
return api.getDerivedAddresses(info.ID, path, pageSize, pageNumber)
}
func (api *API) GetDerivedAddressesForMenominicWithPath(mnemonic string, path string, pageSize int, pageNumber int) ([]*DerivedAddress, error) {
mnemonicNoExtraSpaces := strings.Join(strings.Fields(mnemonic), " ")
info, err := api.manager.AccountsGenerator().ImportMnemonic(mnemonicNoExtraSpaces, "")
if err != nil {
return nil, err
}
return api.getDerivedAddresses(info.ID, path, pageSize, pageNumber)
}
func (api *API) verifyPassword(password string) error {
address, err := api.db.GetChatAddress()
if err != nil {
return err
}
_, err = api.manager.VerifyAccountPassword(api.config.KeyStoreDir, address.Hex(), password)
return err
}
func (api *API) getDerivedAddresses(id string, path string, pageSize int, pageNumber int) ([]*DerivedAddress, error) {
addedAccounts, err := api.db.GetAccounts()
if err != nil {
return nil, err
}
derivedAddresses := make([]*DerivedAddress, 0)
if pageNumber <= 0 || pageSize <= 0 {
return nil, fmt.Errorf("pageSize and pageNumber should be greater than 0")
}
var startIndex = ((pageNumber - 1) * pageSize)
var endIndex = (pageNumber * pageSize)
for i := startIndex; i < endIndex; i++ {
derivedPath := fmt.Sprint(path, "/", i)
info, err := api.manager.AccountsGenerator().DeriveAddresses(id, []string{derivedPath})
if err != nil {
return nil, err
}
alreadyExists := false
for _, account := range addedAccounts {
if types.Address(common.HexToAddress(info[derivedPath].Address)) == account.Address {
alreadyExists = true
break
}
}
address := &DerivedAddress{
Address: common.HexToAddress(info[derivedPath].Address),
Path: derivedPath,
HasActivity: false,
AlreadyCreated: alreadyExists,
}
derivedAddresses = append(derivedAddresses, address)
}
return derivedAddresses, nil
}
func (api *API) addAccountWithMnemonic(
ctx context.Context,
mnemonic string,
password string,
name string,
color string,
emoji string,
path string,
) error {
mnemonicNoExtraSpaces := strings.Join(strings.Fields(mnemonic), " ")
err := api.verifyPassword(password)
if err != nil {
return err
}
generatedAccountInfo, err := api.manager.AccountsGenerator().ImportMnemonic(mnemonicNoExtraSpaces, "")
if err != nil {
return err
}
_, err = api.manager.AccountsGenerator().StoreAccount(generatedAccountInfo.ID, password)
if err != nil {
return err
}
accountinfos, err := api.manager.AccountsGenerator().StoreDerivedAccounts(generatedAccountInfo.ID, password, []string{path})
if err != nil {
return err
}
account := accounts.Account{
Address: types.Address(common.HexToAddress(accountinfos[path].Address)),
PublicKey: types.HexBytes(accountinfos[path].PublicKey),
Type: "seed",
Name: name,
Emoji: emoji,
Color: color,
Path: path,
DerivedFrom: generatedAccountInfo.Address,
}
return api.SaveAccounts(ctx, []accounts.Account{account})
}
func (api *API) generateAccount(
ctx context.Context,
password string,
name string,
color string,
emoji string,
path string,
address string,
) error {
err := api.verifyPassword(password)
if err != nil {
return err
}
info, err := api.manager.AccountsGenerator().LoadAccount(address, password)
if err != nil {
return err
}
infos, err := api.manager.AccountsGenerator().DeriveAddresses(info.ID, []string{path})
if err != nil {
return err
}
_, err = api.manager.AccountsGenerator().StoreDerivedAccounts(info.ID, password, []string{path})
if err != nil {
return err
}
acc := accounts.Account{
Address: types.Address(common.HexToAddress(infos[path].Address)),
PublicKey: types.HexBytes(infos[path].PublicKey),
Type: "generated",
Name: name,
Emoji: emoji,
Color: color,
Path: path,
DerivedFrom: address,
}
return api.SaveAccounts(ctx, []accounts.Account{acc})
}