Chore: improve mocking for community tests (#3637)

* chore: different wallet addresses for different users in community tests

* chore: fix naming for account.Manager interface
This commit is contained in:
Mikhail Rogachev 2023-06-21 16:13:31 +04:00 committed by GitHub
parent 8ef3c52f4d
commit 2fb87b5f0d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 109 additions and 86 deletions

View File

@ -62,15 +62,15 @@ type RecoverParams struct {
Signature string `json:"signature"` Signature string `json:"signature"`
} }
// Interface represents account manager interface // Manager represents account manager interface
type Interface interface { type Manager interface {
GetVerifiedWalletAccount(db *accounts.Database, address, password string) (*SelectedExtKey, error) GetVerifiedWalletAccount(db *accounts.Database, address, password string) (*SelectedExtKey, error)
Sign(rpcParams SignParams, verifiedAccount *SelectedExtKey) (result types.HexBytes, err error) Sign(rpcParams SignParams, verifiedAccount *SelectedExtKey) (result types.HexBytes, err error)
Recover(rpcParams RecoverParams) (addr types.Address, err error) CanRecover(rpcParams RecoverParams, revealedAddress types.Address) (bool, error)
} }
// Manager represents account manager implementation // DefaultManager represents default account manager implementation
type Manager struct { type DefaultManager struct {
mu sync.RWMutex mu sync.RWMutex
rpcClient *rpc.Client rpcClient *rpc.Client
rpcTimeout time.Duration rpcTimeout time.Duration
@ -86,18 +86,18 @@ type Manager struct {
} }
// GetKeystore is only used in tests // GetKeystore is only used in tests
func (m *Manager) GetKeystore() types.KeyStore { func (m *DefaultManager) GetKeystore() types.KeyStore {
m.mu.RLock() m.mu.RLock()
defer m.mu.RUnlock() defer m.mu.RUnlock()
return m.keystore return m.keystore
} }
// AccountsGenerator returns accountsGenerator. // AccountsGenerator returns accountsGenerator.
func (m *Manager) AccountsGenerator() *generator.Generator { func (m *DefaultManager) AccountsGenerator() *generator.Generator {
return m.accountsGenerator return m.accountsGenerator
} }
func (m *Manager) GetRandomMnemonic() (string, error) { func (m *DefaultManager) GetRandomMnemonic() (string, error) {
// generate mnemonic phrase // generate mnemonic phrase
mn := extkeys.NewMnemonic() mn := extkeys.NewMnemonic()
mnemonic, err := mn.MnemonicPhrase(extkeys.EntropyStrength128, extkeys.EnglishLanguage) mnemonic, err := mn.MnemonicPhrase(extkeys.EntropyStrength128, extkeys.EnglishLanguage)
@ -111,7 +111,7 @@ func (m *Manager) GetRandomMnemonic() (string, error) {
// BIP44-compatible keys are generated: CKD#1 is stored as account key, CKD#2 stored as sub-account root // 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 // Public key of CKD#1 is returned, with CKD#2 securely encoded into account key file (to be used for
// sub-account derivations) // sub-account derivations)
func (m *Manager) CreateAccount(password string) (generator.GeneratedAccountInfo, Info, string, error) { func (m *DefaultManager) CreateAccount(password string) (generator.GeneratedAccountInfo, Info, string, error) {
var mkInfo generator.GeneratedAccountInfo var mkInfo generator.GeneratedAccountInfo
info := Info{} info := Info{}
@ -149,7 +149,7 @@ func (m *Manager) CreateAccount(password string) (generator.GeneratedAccountInfo
// RecoverAccount re-creates master key using given details. // RecoverAccount re-creates master key using given details.
// Once master key is re-generated, it is inserted into keystore (if not already there). // Once master key is re-generated, it is inserted into keystore (if not already there).
func (m *Manager) RecoverAccount(password, mnemonic string) (Info, error) { func (m *DefaultManager) RecoverAccount(password, mnemonic string) (Info, error) {
info := Info{} info := Info{}
// re-create extended key (see BIP32) // re-create extended key (see BIP32)
mn := extkeys.NewMnemonic() mn := extkeys.NewMnemonic()
@ -172,7 +172,7 @@ func (m *Manager) RecoverAccount(password, mnemonic string) (Info, error) {
// VerifyAccountPassword tries to decrypt a given account key file, with a provided password. // VerifyAccountPassword tries to decrypt a given account key file, with a provided password.
// If no error is returned, then account is considered verified. // If no error is returned, then account is considered verified.
func (m *Manager) VerifyAccountPassword(keyStoreDir, address, password string) (*types.Key, error) { func (m *DefaultManager) VerifyAccountPassword(keyStoreDir, address, password string) (*types.Key, error) {
var err error var err error
var foundKeyFile []byte var foundKeyFile []byte
@ -229,7 +229,7 @@ func (m *Manager) VerifyAccountPassword(keyStoreDir, address, password string) (
// SelectAccount selects current account, by verifying that address has corresponding account which can be decrypted // SelectAccount selects current account, by verifying that address has corresponding account which can be decrypted
// using provided password. Once verification is done, all previous identities are removed). // using provided password. Once verification is done, all previous identities are removed).
func (m *Manager) SelectAccount(loginParams LoginParams) error { func (m *DefaultManager) SelectAccount(loginParams LoginParams) error {
m.mu.Lock() m.mu.Lock()
defer m.mu.Unlock() defer m.mu.Unlock()
@ -245,14 +245,14 @@ func (m *Manager) SelectAccount(loginParams LoginParams) error {
return nil return nil
} }
func (m *Manager) SetAccountAddresses(main types.Address, secondary ...types.Address) { func (m *DefaultManager) SetAccountAddresses(main types.Address, secondary ...types.Address) {
m.watchAddresses = []types.Address{main} m.watchAddresses = []types.Address{main}
m.watchAddresses = append(m.watchAddresses, secondary...) m.watchAddresses = append(m.watchAddresses, secondary...)
m.mainAccountAddress = main m.mainAccountAddress = main
} }
// SetChatAccount initializes selectedChatAccount with privKey // SetChatAccount initializes selectedChatAccount with privKey
func (m *Manager) SetChatAccount(privKey *ecdsa.PrivateKey) error { func (m *DefaultManager) SetChatAccount(privKey *ecdsa.PrivateKey) error {
m.mu.Lock() m.mu.Lock()
defer m.mu.Unlock() defer m.mu.Unlock()
@ -276,7 +276,7 @@ func (m *Manager) SetChatAccount(privKey *ecdsa.PrivateKey) error {
} }
// MainAccountAddress returns main account address set during login // MainAccountAddress returns main account address set during login
func (m *Manager) MainAccountAddress() (types.Address, error) { func (m *DefaultManager) MainAccountAddress() (types.Address, error) {
m.mu.RLock() m.mu.RLock()
defer m.mu.RUnlock() defer m.mu.RUnlock()
@ -288,7 +288,7 @@ func (m *Manager) MainAccountAddress() (types.Address, error) {
} }
// WatchAddresses returns currently selected watch addresses. // WatchAddresses returns currently selected watch addresses.
func (m *Manager) WatchAddresses() []types.Address { func (m *DefaultManager) WatchAddresses() []types.Address {
m.mu.RLock() m.mu.RLock()
defer m.mu.RUnlock() defer m.mu.RUnlock()
@ -296,7 +296,7 @@ func (m *Manager) WatchAddresses() []types.Address {
} }
// SelectedChatAccount returns currently selected chat account // SelectedChatAccount returns currently selected chat account
func (m *Manager) SelectedChatAccount() (*SelectedExtKey, error) { func (m *DefaultManager) SelectedChatAccount() (*SelectedExtKey, error) {
m.mu.RLock() m.mu.RLock()
defer m.mu.RUnlock() defer m.mu.RUnlock()
@ -307,7 +307,7 @@ func (m *Manager) SelectedChatAccount() (*SelectedExtKey, error) {
} }
// Logout clears selected accounts. // Logout clears selected accounts.
func (m *Manager) Logout() { func (m *DefaultManager) Logout() {
m.mu.Lock() m.mu.Lock()
defer m.mu.Unlock() defer m.mu.Unlock()
@ -318,7 +318,7 @@ func (m *Manager) Logout() {
} }
// ImportAccount imports the account specified with privateKey. // ImportAccount imports the account specified with privateKey.
func (m *Manager) ImportAccount(privateKey *ecdsa.PrivateKey, password string) (types.Address, error) { func (m *DefaultManager) ImportAccount(privateKey *ecdsa.PrivateKey, password string) (types.Address, error) {
if m.keystore == nil { if m.keystore == nil {
return types.Address{}, ErrAccountKeyStoreMissing return types.Address{}, ErrAccountKeyStoreMissing
} }
@ -332,7 +332,7 @@ func (m *Manager) ImportAccount(privateKey *ecdsa.PrivateKey, password string) (
// of the Key struct. // of the Key struct.
// ImportExtendedKey is used in older version of Status where PrivateKey is set to be the BIP44 key at index 0, // ImportExtendedKey is used in older version of Status where PrivateKey is set to be the BIP44 key at index 0,
// and ExtendedKey is the extended key of the BIP44 key at index 1. // and ExtendedKey is the extended key of the BIP44 key at index 1.
func (m *Manager) ImportSingleExtendedKey(extKey *extkeys.ExtendedKey, password string) (address, pubKey string, err error) { func (m *DefaultManager) ImportSingleExtendedKey(extKey *extkeys.ExtendedKey, password string) (address, pubKey string, err error) {
if m.keystore == nil { if m.keystore == nil {
return "", "", ErrAccountKeyStoreMissing return "", "", ErrAccountKeyStoreMissing
} }
@ -358,7 +358,7 @@ func (m *Manager) ImportSingleExtendedKey(extKey *extkeys.ExtendedKey, password
// importExtendedKey processes incoming extended key, extracts required info and creates corresponding account key. // importExtendedKey processes incoming extended key, extracts required info and creates corresponding account key.
// Once account key is formed, that key is put (if not already) into keystore i.e. key is *encoded* into key file. // Once account key is formed, that key is put (if not already) into keystore i.e. key is *encoded* into key file.
func (m *Manager) importExtendedKey(keyPurpose extkeys.KeyPurpose, extKey *extkeys.ExtendedKey, password string) (address, pubKey string, err error) { func (m *DefaultManager) importExtendedKey(keyPurpose extkeys.KeyPurpose, extKey *extkeys.ExtendedKey, password string) (address, pubKey string, err error) {
if m.keystore == nil { if m.keystore == nil {
return "", "", ErrAccountKeyStoreMissing return "", "", ErrAccountKeyStoreMissing
} }
@ -382,7 +382,7 @@ func (m *Manager) importExtendedKey(keyPurpose extkeys.KeyPurpose, extKey *extke
// Accounts returns list of addresses for selected account, including // Accounts returns list of addresses for selected account, including
// subaccounts. // subaccounts.
func (m *Manager) Accounts() ([]types.Address, error) { func (m *DefaultManager) Accounts() ([]types.Address, error) {
m.mu.RLock() m.mu.RLock()
defer m.mu.RUnlock() defer m.mu.RUnlock()
addresses := make([]types.Address, 0) addresses := make([]types.Address, 0)
@ -394,7 +394,7 @@ func (m *Manager) Accounts() ([]types.Address, error) {
} }
// StartOnboarding starts the onboarding process generating accountsCount accounts and returns a slice of OnboardingAccount. // StartOnboarding starts the onboarding process generating accountsCount accounts and returns a slice of OnboardingAccount.
func (m *Manager) StartOnboarding(accountsCount, mnemonicPhraseLength int) ([]*OnboardingAccount, error) { func (m *DefaultManager) StartOnboarding(accountsCount, mnemonicPhraseLength int) ([]*OnboardingAccount, error) {
m.mu.Lock() m.mu.Lock()
defer m.mu.Unlock() defer m.mu.Unlock()
@ -409,7 +409,7 @@ func (m *Manager) StartOnboarding(accountsCount, mnemonicPhraseLength int) ([]*O
} }
// RemoveOnboarding reset the current onboarding struct setting it to nil and deleting the accounts from memory. // RemoveOnboarding reset the current onboarding struct setting it to nil and deleting the accounts from memory.
func (m *Manager) RemoveOnboarding() { func (m *DefaultManager) RemoveOnboarding() {
m.mu.Lock() m.mu.Lock()
defer m.mu.Unlock() defer m.mu.Unlock()
@ -417,7 +417,7 @@ func (m *Manager) RemoveOnboarding() {
} }
// ImportOnboardingAccount imports the account specified by id and encrypts it with password. // ImportOnboardingAccount imports the account specified by id and encrypts it with password.
func (m *Manager) ImportOnboardingAccount(id string, password string) (Info, string, error) { func (m *DefaultManager) ImportOnboardingAccount(id string, password string) (Info, string, error) {
var info Info var info Info
m.mu.Lock() m.mu.Lock()
@ -445,7 +445,7 @@ func (m *Manager) ImportOnboardingAccount(id string, password string) (Info, str
// AddressToDecryptedAccount tries to load decrypted key for a given account. // AddressToDecryptedAccount tries to load decrypted key for a given account.
// The running node, has a keystore directory which is loaded on start. Key file // The running node, has a keystore directory which is loaded on start. Key file
// for a given address is expected to be in that directory prior to node start. // for a given address is expected to be in that directory prior to node start.
func (m *Manager) AddressToDecryptedAccount(address, password string) (types.Account, *types.Key, error) { func (m *DefaultManager) AddressToDecryptedAccount(address, password string) (types.Account, *types.Key, error) {
if m.keystore == nil { if m.keystore == nil {
return types.Account{}, nil, ErrAccountKeyStoreMissing return types.Account{}, nil, ErrAccountKeyStoreMissing
} }
@ -463,7 +463,7 @@ func (m *Manager) AddressToDecryptedAccount(address, password string) (types.Acc
return account, key, err return account, key, err
} }
func (m *Manager) unlockExtendedKey(address, password string) (*SelectedExtKey, error) { func (m *DefaultManager) unlockExtendedKey(address, password string) (*SelectedExtKey, error) {
account, accountKey, err := m.AddressToDecryptedAccount(address, password) account, accountKey, err := m.AddressToDecryptedAccount(address, password)
if err != nil { if err != nil {
return nil, err return nil, err
@ -477,7 +477,7 @@ func (m *Manager) unlockExtendedKey(address, password string) (*SelectedExtKey,
return selectedExtendedKey, nil return selectedExtendedKey, nil
} }
func (m *Manager) MigrateKeyStoreDir(oldDir, newDir string, addresses []string) error { func (m *DefaultManager) MigrateKeyStoreDir(oldDir, newDir string, addresses []string) error {
paths := []string{} paths := []string{}
addressesMap := map[string]struct{}{} addressesMap := map[string]struct{}{}
@ -532,7 +532,7 @@ func (m *Manager) MigrateKeyStoreDir(oldDir, newDir string, addresses []string)
return nil return nil
} }
func (m *Manager) ReEncryptKey(rawKey []byte, pass string, newPass string) (reEncryptedKey []byte, e error) { func (m *DefaultManager) ReEncryptKey(rawKey []byte, pass string, newPass string) (reEncryptedKey []byte, e error) {
cryptoJSON, e := keystore.RawKeyToCryptoJSON(rawKey) cryptoJSON, e := keystore.RawKeyToCryptoJSON(rawKey)
if e != nil { if e != nil {
return reEncryptedKey, fmt.Errorf("convert to crypto json error: %v", e) return reEncryptedKey, fmt.Errorf("convert to crypto json error: %v", e)
@ -560,7 +560,7 @@ func (m *Manager) ReEncryptKey(rawKey []byte, pass string, newPass string) (reEn
return gethkeystore.EncryptKey(&gethKey, newPass, n, p) return gethkeystore.EncryptKey(&gethKey, newPass, n, p)
} }
func (m *Manager) ReEncryptKeyStoreDir(keyDirPath, oldPass, newPass string) error { func (m *DefaultManager) ReEncryptKeyStoreDir(keyDirPath, oldPass, newPass string) error {
rencryptFileAtPath := func(tempKeyDirPath, path string, fileInfo os.FileInfo) error { rencryptFileAtPath := func(tempKeyDirPath, path string, fileInfo os.FileInfo) error {
if fileInfo.IsDir() { if fileInfo.IsDir() {
return nil return nil
@ -647,11 +647,11 @@ func (m *Manager) ReEncryptKeyStoreDir(keyDirPath, oldPass, newPass string) erro
return nil return nil
} }
func (m *Manager) DeleteAccount(address types.Address) error { func (m *DefaultManager) DeleteAccount(address types.Address) error {
return m.keystore.Delete(types.Account{Address: address}) return m.keystore.Delete(types.Account{Address: address})
} }
func (m *Manager) GetVerifiedWalletAccount(db *accounts.Database, address, password string) (*SelectedExtKey, error) { func (m *DefaultManager) GetVerifiedWalletAccount(db *accounts.Database, address, password string) (*SelectedExtKey, error) {
exists, err := db.AddressExists(types.HexToAddress(address)) exists, err := db.AddressExists(types.HexToAddress(address))
if err != nil { if err != nil {
return nil, err return nil, err
@ -679,7 +679,7 @@ func (m *Manager) GetVerifiedWalletAccount(db *accounts.Database, address, passw
}, nil }, nil
} }
func (m *Manager) generatePartialAccountKey(db *accounts.Database, address string, password string) (*types.Key, error) { func (m *DefaultManager) generatePartialAccountKey(db *accounts.Database, address string, password string) (*types.Key, error) {
dbPath, err := db.GetPath(types.HexToAddress(address)) dbPath, err := db.GetPath(types.HexToAddress(address))
path := "m/" + dbPath[strings.LastIndex(dbPath, "/")+1:] path := "m/" + dbPath[strings.LastIndex(dbPath, "/")+1:]
if err != nil { if err != nil {
@ -709,7 +709,7 @@ func (m *Manager) generatePartialAccountKey(db *accounts.Database, address strin
return key, nil return key, nil
} }
func (m *Manager) Recover(rpcParams RecoverParams) (addr types.Address, err error) { func (m *DefaultManager) Recover(rpcParams RecoverParams) (addr types.Address, err error) {
ctx, cancel := context.WithTimeout(context.Background(), m.rpcTimeout) ctx, cancel := context.WithTimeout(context.Background(), m.rpcTimeout)
defer cancel() defer cancel()
var gethAddr gethcommon.Address var gethAddr gethcommon.Address
@ -724,7 +724,15 @@ func (m *Manager) Recover(rpcParams RecoverParams) (addr types.Address, err erro
return return
} }
func (m *Manager) Sign(rpcParams SignParams, verifiedAccount *SelectedExtKey) (result types.HexBytes, err error) { func (m *DefaultManager) CanRecover(rpcParams RecoverParams, revealedAddress types.Address) (bool, error) {
recovered, err := m.Recover(rpcParams)
if err != nil {
return false, err
}
return recovered == revealedAddress, nil
}
func (m *DefaultManager) Sign(rpcParams SignParams, verifiedAccount *SelectedExtKey) (result types.HexBytes, err error) {
if !strings.EqualFold(rpcParams.Address, verifiedAccount.Address.Hex()) { if !strings.EqualFold(rpcParams.Address, verifiedAccount.Address.Hex()) {
err = ErrInvalidPersonalSignAccount err = ErrInvalidPersonalSignAccount
return return

View File

@ -11,7 +11,7 @@ import (
// GethManager represents account manager interface. // GethManager represents account manager interface.
type GethManager struct { type GethManager struct {
*Manager *DefaultManager
gethAccManager *accounts.Manager gethAccManager *accounts.Manager
} }
@ -19,13 +19,13 @@ type GethManager struct {
// NewGethManager returns new node account manager. // NewGethManager returns new node account manager.
func NewGethManager() *GethManager { func NewGethManager() *GethManager {
m := &GethManager{} m := &GethManager{}
m.Manager = &Manager{accountsGenerator: generator.New(m)} m.DefaultManager = &DefaultManager{accountsGenerator: generator.New(m)}
return m return m
} }
func (m *GethManager) SetRPCClient(rpcClient *rpc.Client, rpcTimeout time.Duration) { func (m *GethManager) SetRPCClient(rpcClient *rpc.Client, rpcTimeout time.Duration) {
m.Manager.rpcClient = rpcClient m.DefaultManager.rpcClient = rpcClient
m.Manager.rpcTimeout = rpcTimeout m.DefaultManager.rpcTimeout = rpcTimeout
} }
// InitKeystore sets key manager and key store. // InitKeystore sets key manager and key store.

View File

@ -69,7 +69,7 @@ type Manager struct {
subscriptions []chan *Subscription subscriptions []chan *Subscription
ensVerifier *ens.Verifier ensVerifier *ens.Verifier
identity *ecdsa.PrivateKey identity *ecdsa.PrivateKey
accountsManager account.Interface accountsManager account.Manager
tokenManager TokenManager tokenManager TokenManager
logger *zap.Logger logger *zap.Logger
stdoutLogger *zap.Logger stdoutLogger *zap.Logger
@ -122,7 +122,7 @@ func (t *HistoryArchiveDownloadTask) Cancel() {
} }
type managerOptions struct { type managerOptions struct {
accountsManager account.Interface accountsManager account.Manager
tokenManager TokenManager tokenManager TokenManager
walletConfig *params.WalletConfig walletConfig *params.WalletConfig
openseaClientBuilder openseaClientBuilder openseaClientBuilder openseaClientBuilder
@ -168,7 +168,7 @@ func (m *DefaultTokenManager) GetBalancesByChain(ctx context.Context, accounts,
type ManagerOption func(*managerOptions) type ManagerOption func(*managerOptions)
func WithAccountManager(accountsManager account.Interface) ManagerOption { func WithAccountManager(accountsManager account.Manager) ManagerOption {
return func(opts *managerOptions) { return func(opts *managerOptions) {
opts.accountsManager = accountsManager opts.accountsManager = accountsManager
} }
@ -1786,11 +1786,11 @@ func (m *Manager) HandleCommunityRequestToJoin(signer *ecdsa.PublicKey, request
Signature: types.EncodeHex(revealedAccount.Signature), Signature: types.EncodeHex(revealedAccount.Signature),
} }
recovered, err := m.accountsManager.Recover(recoverParams) matching, err := m.accountsManager.CanRecover(recoverParams, types.HexToAddress(revealedAccount.Address))
if err != nil { if err != nil {
return nil, err return nil, err
} }
if recovered.Hex() != revealedAccount.Address { if !matching {
// if ownership of only one wallet address cannot be verified, // if ownership of only one wallet address cannot be verified,
// we mark the request as cancelled and stop // we mark the request as cancelled and stop
err = m.markRequestToJoinAsCanceled(signer, community) err = m.markRequestToJoinAsCanceled(signer, community)

View File

@ -43,11 +43,13 @@ import (
"github.com/status-im/status-go/waku" "github.com/status-im/status-go/waku"
) )
const AdminPassword = "123456" const adminPassword = "123456"
const AlicePassword = "qwerty" const alicePassword = "qwerty"
const BobPassword = "bob123" const bobPassword = "bob123"
var walletAddress = "0x0100000000000000000000000000000000000000" const adminAddress = "0x0100000000000000000000000000000000000000"
const aliceAddress = "0x0200000000000000000000000000000000000000"
const bobAddress = "0x0300000000000000000000000000000000000000"
type AccountManagerMock struct { type AccountManagerMock struct {
AccountsMap map[string]string AccountsMap map[string]string
@ -76,8 +78,8 @@ func (m *AccountManagerMock) GetVerifiedWalletAccount(db *accounts.Database, add
return nil, errors.New("address doesn't exist") return nil, errors.New("address doesn't exist")
} }
func (m *AccountManagerMock) Recover(rpcParams account.RecoverParams) (addr types.Address, err error) { func (m *AccountManagerMock) CanRecover(rpcParams account.RecoverParams, revealedAddress types.Address) (bool, error) {
return types.HexToAddress(walletAddress), nil return true, nil
} }
func (m *AccountManagerMock) Sign(rpcParams account.SignParams, verifiedAccount *account.SelectedExtKey) (result types.HexBytes, err error) { func (m *AccountManagerMock) Sign(rpcParams account.SignParams, verifiedAccount *account.SelectedExtKey) (result types.HexBytes, err error) {
@ -108,9 +110,9 @@ func (s *MessengerCommunitiesSuite) SetupTest() {
s.shh = gethbridge.NewGethWakuWrapper(shh) s.shh = gethbridge.NewGethWakuWrapper(shh)
s.Require().NoError(shh.Start()) s.Require().NoError(shh.Start())
s.admin = s.newMessenger(AdminPassword) s.admin = s.newMessengerWithWallet(adminPassword, adminAddress)
s.bob = s.newMessenger(BobPassword) s.bob = s.newMessengerWithWallet(bobPassword, bobAddress)
s.alice = s.newMessenger(AlicePassword) s.alice = s.newMessengerWithWallet(alicePassword, aliceAddress)
_, err := s.admin.Start() _, err := s.admin.Start()
s.Require().NoError(err) s.Require().NoError(err)
_, err = s.bob.Start() _, err = s.bob.Start()
@ -126,11 +128,7 @@ func (s *MessengerCommunitiesSuite) TearDownTest() {
_ = s.logger.Sync() _ = s.logger.Sync()
} }
func (s *MessengerCommunitiesSuite) newMessengerWithOptions(shh types.Waku, privateKey *ecdsa.PrivateKey, password string, options []Option) *Messenger { func (s *MessengerCommunitiesSuite) newMessengerWithOptions(shh types.Waku, privateKey *ecdsa.PrivateKey, accountsManager account.Manager, options []Option) *Messenger {
accountsManager := &AccountManagerMock{}
accountsManager.AccountsMap = make(map[string]string)
accountsManager.AccountsMap[walletAddress] = types.EncodeHex(crypto.Keccak256([]byte(password)))
m, err := NewMessenger( m, err := NewMessenger(
"Test", "Test",
privateKey, privateKey,
@ -175,21 +173,10 @@ func (s *MessengerCommunitiesSuite) newMessengerWithOptions(shh types.Waku, priv
_ = m.settings.CreateSettings(setting, config) _ = m.settings.CreateSettings(setting, config)
// add wallet account with keypair
kp := accounts.GetProfileKeypairForTest(false, true, false)
kp.Accounts[0].Address = types.HexToAddress(walletAddress)
err = m.settings.SaveOrUpdateKeypair(kp)
s.Require().NoError(err)
walletAccounts, err := m.settings.GetAccounts()
s.Require().NoError(err)
s.Require().Len(walletAccounts, 1)
s.Require().Equal(walletAccounts[0].Type, accounts.AccountTypeGenerated)
return m return m
} }
func (s *MessengerCommunitiesSuite) newMessengerWithKey(shh types.Waku, privateKey *ecdsa.PrivateKey, password string) *Messenger { func (s *MessengerCommunitiesSuite) newMessengerWithKey(shh types.Waku, privateKey *ecdsa.PrivateKey, accountsManager account.Manager) *Messenger {
tmpfile, err := ioutil.TempFile("", "accounts-tests-") tmpfile, err := ioutil.TempFile("", "accounts-tests-")
s.Require().NoError(err) s.Require().NoError(err)
madb, err := multiaccounts.InitializeDB(tmpfile.Name()) madb, err := multiaccounts.InitializeDB(tmpfile.Name())
@ -207,14 +194,34 @@ func (s *MessengerCommunitiesSuite) newMessengerWithKey(shh types.Waku, privateK
WithDatasync(), WithDatasync(),
WithTokenManager(tm), WithTokenManager(tm),
} }
return s.newMessengerWithOptions(shh, privateKey, password, options) return s.newMessengerWithOptions(shh, privateKey, accountsManager, options)
} }
func (s *MessengerCommunitiesSuite) newMessenger(password string) *Messenger { func (s *MessengerCommunitiesSuite) newMessenger(accountsManager account.Manager) *Messenger {
privateKey, err := crypto.GenerateKey() privateKey, err := crypto.GenerateKey()
s.Require().NoError(err) s.Require().NoError(err)
return s.newMessengerWithKey(s.shh, privateKey, password) return s.newMessengerWithKey(s.shh, privateKey, accountsManager)
}
func (s *MessengerCommunitiesSuite) newMessengerWithWallet(password string, walletAddress string) *Messenger {
accountsManager := &AccountManagerMock{}
accountsManager.AccountsMap = make(map[string]string)
accountsManager.AccountsMap[walletAddress] = types.EncodeHex(crypto.Keccak256([]byte(password)))
messenger := s.newMessenger(accountsManager)
// add wallet account with keypair
kp := accounts.GetProfileKeypairForTest(false, true, false)
kp.Accounts[0].Address = types.HexToAddress(walletAddress)
err := messenger.settings.SaveOrUpdateKeypair(kp)
s.Require().NoError(err)
walletAccounts, err := messenger.settings.GetAccounts()
s.Require().NoError(err)
s.Require().Len(walletAccounts, 1)
s.Require().Equal(walletAccounts[0].Type, accounts.AccountTypeGenerated)
return messenger
} }
func (s *MessengerCommunitiesSuite) requestToJoinCommunity(user *Messenger, communityID types.HexBytes, password string) (*MessengerResponse, error) { func (s *MessengerCommunitiesSuite) requestToJoinCommunity(user *Messenger, communityID types.HexBytes, password string) (*MessengerResponse, error) {
@ -255,7 +262,7 @@ func (s *MessengerCommunitiesSuite) TestCreateCommunity_WithoutDefaultChannel()
} }
func (s *MessengerCommunitiesSuite) TestRetrieveCommunity() { func (s *MessengerCommunitiesSuite) TestRetrieveCommunity() {
alice := s.newMessenger(AlicePassword) alice := s.newMessengerWithWallet(alicePassword, aliceAddress)
description := &requests.CreateCommunity{ description := &requests.CreateCommunity{
Membership: protobuf.CommunityPermissions_NO_MEMBERSHIP, Membership: protobuf.CommunityPermissions_NO_MEMBERSHIP,
@ -632,8 +639,8 @@ func (s *MessengerCommunitiesSuite) TestCommunityContactCodeAdvertisement() {
s.advertiseCommunityTo(community, s.bob) s.advertiseCommunityTo(community, s.bob)
s.advertiseCommunityTo(community, s.alice) s.advertiseCommunityTo(community, s.alice)
s.joinCommunity(community, s.bob, BobPassword) s.joinCommunity(community, s.bob, bobPassword)
s.joinCommunity(community, s.alice, AlicePassword) s.joinCommunity(community, s.alice, alicePassword)
// Trigger ContactCodeAdvertisement // Trigger ContactCodeAdvertisement
err = s.bob.SetDisplayName("bobby") err = s.bob.SetDisplayName("bobby")
@ -2422,8 +2429,8 @@ func (s *MessengerCommunitiesSuite) TestLeaveAndRejoinCommunity() {
s.advertiseCommunityTo(community, s.alice) s.advertiseCommunityTo(community, s.alice)
s.advertiseCommunityTo(community, s.bob) s.advertiseCommunityTo(community, s.bob)
s.joinCommunity(community, s.alice, AlicePassword) s.joinCommunity(community, s.alice, alicePassword)
s.joinCommunity(community, s.bob, BobPassword) s.joinCommunity(community, s.bob, bobPassword)
joinedCommunities, err := s.admin.communitiesManager.Joined() joinedCommunities, err := s.admin.communitiesManager.Joined()
s.Require().NoError(err) s.Require().NoError(err)
@ -2486,7 +2493,7 @@ func (s *MessengerCommunitiesSuite) TestLeaveAndRejoinCommunity() {
s.Require().Equal(3, numberInactiveChats) s.Require().Equal(3, numberInactiveChats)
// alice can rejoin // alice can rejoin
s.joinCommunity(community, s.alice, AlicePassword) s.joinCommunity(community, s.alice, alicePassword)
joinedCommunities, err = s.admin.communitiesManager.Joined() joinedCommunities, err = s.admin.communitiesManager.Joined()
s.Require().NoError(err) s.Require().NoError(err)
@ -3533,7 +3540,7 @@ func (s *MessengerCommunitiesSuite) TestCommunityBanUserRequesToJoin() {
s.Require().NoError(err) s.Require().NoError(err)
s.Require().Len(response.Communities(), 1) s.Require().Len(response.Communities(), 1)
passwdHash := types.EncodeHex(crypto.Keccak256([]byte(AlicePassword))) passwdHash := types.EncodeHex(crypto.Keccak256([]byte(alicePassword)))
request := &requests.RequestToJoinCommunity{CommunityID: community.ID(), Password: passwdHash} request := &requests.RequestToJoinCommunity{CommunityID: community.ID(), Password: passwdHash}
// We try to join the org // We try to join the org
_, rtj, err := s.alice.communitiesManager.RequestToJoin(&s.alice.identity.PublicKey, request) _, rtj, err := s.alice.communitiesManager.RequestToJoin(&s.alice.identity.PublicKey, request)
@ -3692,8 +3699,8 @@ func (s *MessengerCommunitiesSuite) TestJoinedCommunityMembersSharedAddress() {
s.advertiseCommunityTo(community, s.alice) s.advertiseCommunityTo(community, s.alice)
s.advertiseCommunityTo(community, s.bob) s.advertiseCommunityTo(community, s.bob)
s.joinCommunity(community, s.alice, AlicePassword) s.joinCommunity(community, s.alice, alicePassword)
s.joinCommunity(community, s.bob, BobPassword) s.joinCommunity(community, s.bob, bobPassword)
community, err := s.admin.GetCommunityByID(community.ID()) community, err := s.admin.GetCommunityByID(community.ID())
s.Require().NoError(err) s.Require().NoError(err)
@ -3703,7 +3710,15 @@ func (s *MessengerCommunitiesSuite) TestJoinedCommunityMembersSharedAddress() {
for pubKey, member := range community.Members() { for pubKey, member := range community.Members() {
if pubKey != common.PubkeyToHex(&s.admin.identity.PublicKey) { if pubKey != common.PubkeyToHex(&s.admin.identity.PublicKey) {
s.Require().Len(member.RevealedAccounts, 1) s.Require().Len(member.RevealedAccounts, 1)
s.Require().Equal(member.RevealedAccounts[0].Address, walletAddress)
switch pubKey {
case common.PubkeyToHex(&s.alice.identity.PublicKey):
s.Require().Equal(member.RevealedAccounts[0].Address, aliceAddress)
case common.PubkeyToHex(&s.bob.identity.PublicKey):
s.Require().Equal(member.RevealedAccounts[0].Address, bobAddress)
default:
s.Require().Fail("pubKey does not match expected keys")
}
} }
} }
} }

View File

@ -111,7 +111,7 @@ type Messenger struct {
pushNotificationClient *pushnotificationclient.Client pushNotificationClient *pushnotificationclient.Client
pushNotificationServer *pushnotificationserver.Server pushNotificationServer *pushnotificationserver.Server
communitiesManager *communities.Manager communitiesManager *communities.Manager
accountsManager account.Interface accountsManager account.Manager
mentionsManager *MentionManager mentionsManager *MentionManager
logger *zap.Logger logger *zap.Logger
@ -255,7 +255,7 @@ func NewMessenger(
node types.Node, node types.Node,
installationID string, installationID string,
peerStore *mailservers.PeerStore, peerStore *mailservers.PeerStore,
accountsManager account.Interface, accountsManager account.Manager,
opts ...Option, opts ...Option,
) (*Messenger, error) { ) (*Messenger, error) {
var messenger *Messenger var messenger *Messenger

View File

@ -665,7 +665,7 @@ func (m *Messenger) RequestToJoinCommunity(request *requests.RequestToJoinCommun
if len(walletAccounts) > 0 { if len(walletAccounts) > 0 {
_, err := m.accountsManager.GetVerifiedWalletAccount(m.settings, walletAccounts[0].Address.Hex(), request.Password) _, err := m.accountsManager.GetVerifiedWalletAccount(m.settings, walletAccounts[0].Address.Hex(), request.Password)
if err != nil { if err != nil {
return nil, errors.New("wrong password") return nil, err
} }
} }
} }