From 759f49802c914709b3432370e43274359fa2b251 Mon Sep 17 00:00:00 2001 From: stdevHsequeda Date: Fri, 20 Dec 2019 12:16:37 -0500 Subject: [PATCH 1/6] [generic] refs 290 Created generic.go file in core package. Added Iterator interface in generic.go file in core package. Created genericIterator.go file in util package. Added GenericIterator type implemented Iterator interface in genericIterator.go file in util package. Implemented CurrentData, HasNext and Next methods of GenericIterator type in util package. Created NewGenericIterator function in util package. --- src/core/generic.go | 7 ++++ src/util/genericIterator.go | 66 +++++++++++++++++++++++++++++++++++++ 2 files changed, 73 insertions(+) create mode 100644 src/core/generic.go create mode 100644 src/util/genericIterator.go diff --git a/src/core/generic.go b/src/core/generic.go new file mode 100644 index 00000000..56577d4d --- /dev/null +++ b/src/core/generic.go @@ -0,0 +1,7 @@ +package core + +type Iterator interface { + CurrentData(interface{}) error + HasNext() bool + Next() bool +} diff --git a/src/util/genericIterator.go b/src/util/genericIterator.go new file mode 100644 index 00000000..2eafdfa4 --- /dev/null +++ b/src/util/genericIterator.go @@ -0,0 +1,66 @@ +package util + +import ( + "errors" + "fmt" + "github.com/fibercrypto/fibercryptowallet/src/core" + "reflect" +) + +type GenericIterator struct { + data []interface{} + index int +} + +func NewGenericIterator(value interface{}) core.Iterator { + var iteratorData []interface{} + reflectValue := reflect.ValueOf(value) + if reflectValue.Kind() == reflect.Slice || + reflectValue.Kind() == reflect.Array { + for i := 0; i < reflectValue.Len(); i++ { + iteratorData = append(iteratorData, reflectValue.Index(i).Interface()) + } + } + + return &GenericIterator{ + data: iteratorData, + index: -1, + } +} + +func (g *GenericIterator) CurrentData(val interface{}) error { + reflectVal := reflect.ValueOf(val) + if len(g.data) == 0 { + return errors.New("iterator is empty") + } + + if reflectVal.Kind() != reflect.Ptr || reflectVal.IsNil() { + return errors.New("val must be a pointer") + } + + if !reflect.TypeOf(g.data[g.index]).AssignableTo(reflect.TypeOf(val).Elem()) { + return fmt.Errorf("type:%T can't be assignable to type %T", g.data[g.index], val) + } + reflectCurrentData := reflect.ValueOf(g.data[g.index]) + reflectVal.Elem().Set(reflectCurrentData) + return nil +} + +func (g *GenericIterator) HasNext() bool { + return (g.index + 1) < len(g.data) +} + +func (g *GenericIterator) Next() bool { + if g.HasNext() { + g.index++ + return true + } + return false +} + +// func (g *GenericIterator) GetType() string { +// if len(g.data) == 0 { +// return "" +// } +// return reflect.TypeOf(g.data[0]).Name() +// } From e3bc16ad6a2db30c33fe4fcaa7ceb53dad619701 Mon Sep 17 00:00:00 2001 From: stdevHsequeda Date: Sun, 22 Dec 2019 20:49:18 -0500 Subject: [PATCH 2/6] [generic] refs 290 Modified SkycoinAddressIterator to wrap Iterator type using util.GenericIterator in cipher.go file in skycoin package. Created NewSkycoinAddressIterator function in cipher.go file in skycoin package. Reimplemented all SkycoinAddressIterator implementation. --- src/coin/skycoin/models/account.go | 34 +++++++++++++++++++------ src/coin/skycoin/models/cipher.go | 25 ++++-------------- src/coin/skycoin/models/cipher_test.go | 6 +++-- src/coin/skycoin/models/wallet.go | 35 +++++++++++++++----------- src/coin/skycoin/models/wallet_test.go | 16 ++++++++---- src/core/cipher.go | 10 -------- src/core/wallet.go | 4 +-- src/util/genericIterator.go | 27 ++++++++++---------- 8 files changed, 83 insertions(+), 74 deletions(-) diff --git a/src/coin/skycoin/models/account.go b/src/coin/skycoin/models/account.go index ec278569..d07d5d63 100644 --- a/src/coin/skycoin/models/account.go +++ b/src/coin/skycoin/models/account.go @@ -1,4 +1,4 @@ -package skycoin //nolint goimports +package skycoin // nolint goimports import ( "path/filepath" @@ -105,7 +105,7 @@ func (addr *SkycoinAddress) ListTransactions() core.TransactionIterator { return NewSkycoinTransactionIterator(transactions) } -func (addr *SkycoinAddress) ListPendingTransactions() (core.TransactionIterator, error) { //------TODO +func (addr *SkycoinAddress) ListPendingTransactions() (core.TransactionIterator, error) { // ------TODO return nil, nil } @@ -145,8 +145,13 @@ func (wlt *RemoteWallet) ScanUnspentOutputs() core.TransactionOutputIterator { return nil } unOuts := make([]core.TransactionOutput, 0) + var addr core.Address for addressesIter.Next() { - outsIter := addressesIter.Value().GetCryptoAccount().ScanUnspentOutputs() + if err := addressesIter.CurrentData(&addr); err != nil { + log.Error(err) + return nil + } + outsIter := addr.GetCryptoAccount().ScanUnspentOutputs() for outsIter.Next() { unOuts = append(unOuts, outsIter.Value()) } @@ -162,8 +167,13 @@ func (wlt *RemoteWallet) ListTransactions() core.TransactionIterator { return nil } txns := make([]core.Transaction, 0) + var addr core.Address for addressesIter.Next() { - txnsIter := addressesIter.Value().GetCryptoAccount().ListTransactions() + if err := addressesIter.CurrentData(&addr); err != nil { + log.Error(err) + return nil + } + txnsIter := addr.GetCryptoAccount().ListTransactions() for txnsIter.Next() { txns = append(txns, txnsIter.Value()) } @@ -267,8 +277,13 @@ func (wlt *LocalWallet) ScanUnspentOutputs() core.TransactionOutputIterator { return nil } unOuts := make([]core.TransactionOutput, 0) + var addr core.Address for addressesIter.Next() { - outsIter := addressesIter.Value().GetCryptoAccount().ScanUnspentOutputs() + if err := addressesIter.CurrentData(&addr); err != nil { + log.Error(err) + return nil + } + outsIter := addr.GetCryptoAccount().ScanUnspentOutputs() for outsIter.Next() { unOuts = append(unOuts, outsIter.Value()) } @@ -283,8 +298,13 @@ func (wlt *LocalWallet) ListTransactions() core.TransactionIterator { return nil } txns := make([]core.Transaction, 0) + var addr core.Address for addressesIter.Next() { - txnsIter := addressesIter.Value().GetCryptoAccount().ListTransactions() + if err := addressesIter.CurrentData(&addr); err != nil { + log.Error(err) + return nil + } + txnsIter := addr.GetCryptoAccount().ListTransactions() for txnsIter.Next() { txns = append(txns, txnsIter.Value()) } @@ -293,7 +313,7 @@ func (wlt *LocalWallet) ListTransactions() core.TransactionIterator { return NewSkycoinTransactionIterator(txns) } -func (wlt *LocalWallet) ListPendingTransactions() (core.TransactionIterator, error) { //------TODO +func (wlt *LocalWallet) ListPendingTransactions() (core.TransactionIterator, error) { // ------TODO c, err := NewSkycoinApiClient(PoolSection) if err != nil { log.WithError(err).Error("Couldn't get API client") diff --git a/src/coin/skycoin/models/cipher.go b/src/coin/skycoin/models/cipher.go index ba1e0e20..431bb27b 100644 --- a/src/coin/skycoin/models/cipher.go +++ b/src/coin/skycoin/models/cipher.go @@ -3,34 +3,19 @@ package skycoin import ( "github.com/SkycoinProject/skycoin/src/cipher" "github.com/fibercrypto/fibercryptowallet/src/core" + "github.com/fibercrypto/fibercryptowallet/src/util" ) -type SkycoinAddressIterator struct { // Implements AddressIterator interfaces - current int - addresses []core.Address -} - -func (it *SkycoinAddressIterator) Value() core.Address { - return it.addresses[it.current] -} - -func (it *SkycoinAddressIterator) Next() bool { - if it.HasNext() { - it.current++ - return true - } - return false -} - -func (it *SkycoinAddressIterator) HasNext() bool { - return (it.current + 1) < len(it.addresses) +type SkycoinAddressIterator struct { + core.Iterator } func NewSkycoinAddressIterator(addresses []core.Address) *SkycoinAddressIterator { - return &SkycoinAddressIterator{addresses: addresses, current: -1} + return &SkycoinAddressIterator{Iterator: util.NewGenericIterator(addresses)} } func NewSkycoinAddress(addrStr string) (SkycoinAddress, error) { + var skyAddr cipher.Address var err error if skyAddr, err = cipher.DecodeBase58Address(addrStr); err != nil { diff --git a/src/coin/skycoin/models/cipher_test.go b/src/coin/skycoin/models/cipher_test.go index 83e3d21c..a9a370dc 100644 --- a/src/coin/skycoin/models/cipher_test.go +++ b/src/coin/skycoin/models/cipher_test.go @@ -98,7 +98,7 @@ func TestNewSkycoinAddress(t *testing.T) { } func TestNewSkycoinAddressIterator(t *testing.T) { - var got core.AddressIterator + var got core.Iterator type args struct { addresses []string } @@ -132,7 +132,9 @@ func TestNewSkycoinAddressIterator(t *testing.T) { } for got.Next() { - assert.Contains(t, tt.args.addresses, got.Value().String()) + var addr core.Address + require.NoError(t, got.CurrentData(&addr)) + assert.Contains(t, tt.args.addresses, addr.String()) } }) } diff --git a/src/coin/skycoin/models/wallet.go b/src/coin/skycoin/models/wallet.go index 453c859c..22082214 100644 --- a/src/coin/skycoin/models/wallet.go +++ b/src/coin/skycoin/models/wallet.go @@ -632,7 +632,7 @@ func (wlt *RemoteWallet) Spend(unspent, new []core.TransactionOutput, change cor return createTransaction(nil, new, unspent, change, options, createTxnFunc) } -func (wlt *RemoteWallet) GenAddresses(addrType core.AddressType, startIndex, count uint32, pwd core.PasswordReader) core.AddressIterator { +func (wlt *RemoteWallet) GenAddresses(addrType core.AddressType, startIndex, count uint32, pwd core.PasswordReader) core.Iterator { logWallet.Info("Generate new addresses in remote wallet") c, err := NewSkycoinApiClient(wlt.poolSection) if err != nil { @@ -690,7 +690,7 @@ func (wlt *RemoteWallet) GetCryptoAccount() core.CryptoAccount { return wlt } -func (wlt *RemoteWallet) GetLoadedAddresses() (core.AddressIterator, error) { +func (wlt *RemoteWallet) GetLoadedAddresses() (core.Iterator, error) { logWallet.Info("Loading addresses from remote wallet") c, err := NewSkycoinApiClient(wlt.poolSection) if err != nil { @@ -1134,11 +1134,11 @@ func (wlt *LocalWallet) signSkycoinTxn(txn core.Transaction, pwd core.PasswordRe var resultTxn core.Transaction walletDir := filepath.Join(wlt.WalletDir, wlt.Id) skyWlt, err := wallet.Load(walletDir) - var originalInputs []api.CreatedTransactionInput if err != nil { logWallet.WithError(err).Warn("Couldn't load api client") return nil, err } + var originalInputs []api.CreatedTransactionInput rTxn, isReadableTxn := txn.(skytypes.ReadableTxn) if isReadableTxn { // Readable tranasctions should not need extra API calls @@ -1299,27 +1299,23 @@ func (wlt *LocalWallet) signSkycoinTxn(txn core.Transaction, pwd core.PasswordRe for i, ux := range uxouts { calCh, err := util.GetCoinValue(originalInputs[i].CalculatedHours, CoinHour) if err != nil { + logWallet.WithError(err).Warn("Couldn't create a transaction input") return nil, err } vin := visor.TransactionInput{ UxOut: ux, CalculatedHours: calCh, } - if err != nil { - logWallet.WithError(err).Warn("Couldn't create a transaction input") - return nil, err - } + vins = append(vins, vin) } crtTxn, err := api.NewCreatedTransaction(signedTxn, vins) - if err != nil { - return nil, err - } - crtTxn.In = originalInputs + if err != nil { logWallet.WithError(err).Warn("Couldn't create an un SkycoinCreatedTransaction") return nil, err } + crtTxn.In = originalInputs resultTxn = NewSkycoinCreatedTransaction(*crtTxn) } else { resultTxn, err = NewUninjectedTransaction(signedTxn, txnFee) @@ -1402,7 +1398,12 @@ func (wlt *LocalWallet) Transfer(to core.TransactionOutput, options core.KeyValu return nil, err } for iterAddr.Next() { - addresses = append(addresses, iterAddr.Value()) + var addr core.Address + if err := iterAddr.CurrentData(&addr); err != nil { + logWallet.Error(err) + return nil, err + } + addresses = append(addresses, addr) } createTxnFunc := skyAPICreateTxn @@ -1451,7 +1452,7 @@ func (wlt LocalWallet) Spend(unspent, new []core.TransactionOutput, change core. return createTransaction(nil, new, unspent, change, options, createTxnFunc) } -func (wlt *LocalWallet) GenAddresses(addrType core.AddressType, startIndex, count uint32, pwd core.PasswordReader) core.AddressIterator { +func (wlt *LocalWallet) GenAddresses(addrType core.AddressType, startIndex, count uint32, pwd core.PasswordReader) core.Iterator { if addrType != core.AccountAddress && addrType != core.ChangeAddress { logWallet.Errorf("Incorret address type %d", addrType) @@ -1592,7 +1593,7 @@ func (wlt *LocalWallet) GetCryptoAccount() core.CryptoAccount { return wlt } -func (wlt *LocalWallet) GetLoadedAddresses() (core.AddressIterator, error) { +func (wlt *LocalWallet) GetLoadedAddresses() (core.Iterator, error) { logWallet.Info("Getting loaded addresses from local wallet") walletName := filepath.Join(wlt.WalletDir, wlt.Id) walletLoaded, err := wallet.Load(walletName) @@ -1647,7 +1648,11 @@ func checkEquivalentSkycoinWallets(wlt1, wlt2 core.Wallet) (bool, error) { if err != nil { return false, err } - return addrs1.HasNext() && addrs2.HasNext() && addrs1.Value().String() == addrs2.Value().String(), nil + var addrs core.Address + if err := addrs1.CurrentData(&addrs); err != nil { + return false, err + } + return addrs1.HasNext() && addrs2.HasNext() && addrs.String() == addrs.String(), nil } func checkTxnSupported(wlt1, wlt2 core.Wallet, txn core.Transaction) (bool, error) { diff --git a/src/coin/skycoin/models/wallet_test.go b/src/coin/skycoin/models/wallet_test.go index 65102f34..f9e47ba4 100644 --- a/src/coin/skycoin/models/wallet_test.go +++ b/src/coin/skycoin/models/wallet_test.go @@ -559,8 +559,10 @@ func TestRemoteWalletGenAddresses(t *testing.T) { return "pwd", nil } iter := wlt.GenAddresses(0, 0, 2, pwdReader) + var addr core.Address for iter.Next() { - a := iter.Value() + require.NoError(t, iter.CurrentData(&addr)) + a := addr require.Equal(t, "2JJ8pgq8EDAnrzf9xxBJapE2qkYLefW4uF8", a.String()) } } @@ -574,8 +576,10 @@ func TestRemoteWalletGetLoadedAddresses(t *testing.T) { iter, err := wlt.GetLoadedAddresses() require.NoError(t, err) items := 0 + var addr core.Address for iter.Next() { - a := iter.Value() + require.NoError(t, iter.CurrentData(&addr)) + a := addr items++ require.Equal(t, "2JJ8pgq8EDAnrzf9xxBJapE2qkYLefW4uF8", a.String()) } @@ -1007,8 +1011,10 @@ func TestLocalWalletTransfer(t *testing.T) { loadedAddrs, err := wlt.GetLoadedAddresses() require.NoError(t, err) addrs := make([]string, 0) + var addrIter core.Address for loadedAddrs.Next() { - addrs = append(addrs, loadedAddrs.Value().String()) + require.NoError(t, loadedAddrs.CurrentData(&addrIter)) + addrs = append(addrs, addrIter.String()) } opt := NewTransferOptions() @@ -1214,7 +1220,7 @@ func TestLocalWalletSpend(t *testing.T) { func TestLocalWalletSignSkycoinTxn(t *testing.T) { CleanGlobalMock() - //Test skycoinCreatedTransaction + // Test skycoinCreatedTransaction txn, keyData, uxs, err := makeTransactionMultipleInputs(t, 1) require.Nil(t, err) require.Equal(t, txn.In[0], uxs[0].Hash()) @@ -1245,7 +1251,7 @@ func TestLocalWalletSignSkycoinTxn(t *testing.T) { require.Nil(t, err) require.True(t, ok) - //Test that calculated hours were calculated ok + // Test that calculated hours were calculated ok txn.Out[0].Hours = 1000 err = txn.UpdateHeader() require.Nil(t, err) diff --git a/src/core/cipher.go b/src/core/cipher.go index 6ffe3d7a..7881f032 100644 --- a/src/core/cipher.go +++ b/src/core/cipher.go @@ -41,16 +41,6 @@ type Address interface { Null() bool } -// AddressIterator iterate over addresses in a container -type AddressIterator interface { - // Value of address at iterator pointer position - Value() Address - // Next discards current value and moves iteration pointer up to next item - Next() bool - // HasNext may be used to query whether more items are to be expected in the sequence - HasNext() bool -} - // TxnSigner defines the contract enforced upon objects able to sin transacions. type TxnSigner interface { // ReadyForTxn determines whether this signer instance can be used by wallet to sign given transaction diff --git a/src/core/wallet.go b/src/core/wallet.go index 0b01f1a7..ff9751b2 100644 --- a/src/core/wallet.go +++ b/src/core/wallet.go @@ -61,11 +61,11 @@ type Wallet interface { Spend(unspent, new []TransactionOutput, change Address, options KeyValueStore) (Transaction, error) // GenAddresses discover new addresses based on default hierarchically deterministic derivation sequences // FIXME: Support account index to be fully compatible with BIP44 - GenAddresses(addrType AddressType, startIndex, count uint32, pwd PasswordReader) AddressIterator + GenAddresses(addrType AddressType, startIndex, count uint32, pwd PasswordReader) Iterator // GetCryptoAccount instantiate object to determine wallet balance and transaction history GetCryptoAccount() CryptoAccount // GetLoadedAddresses iterates over wallet addresses discovered and known to have previous history and coins - GetLoadedAddresses() (AddressIterator, error) + GetLoadedAddresses() (Iterator, error) // Sign creates a new transaction by (fully or partially) choosing a strategy to sign given transaction // If signer instance is nil then default wallet strategy should be used for signing Sign(txn Transaction, signer TxnSigner, pwd PasswordReader, index []string) (Transaction, error) diff --git a/src/util/genericIterator.go b/src/util/genericIterator.go index 2eafdfa4..f86b5c9b 100644 --- a/src/util/genericIterator.go +++ b/src/util/genericIterator.go @@ -8,8 +8,9 @@ import ( ) type GenericIterator struct { - data []interface{} - index int + data []interface{} + index int + dataType reflect.Type } func NewGenericIterator(value interface{}) core.Iterator { @@ -23,8 +24,9 @@ func NewGenericIterator(value interface{}) core.Iterator { } return &GenericIterator{ - data: iteratorData, - index: -1, + data: iteratorData, + index: -1, + dataType: reflect.TypeOf(value).Elem(), } } @@ -37,9 +39,8 @@ func (g *GenericIterator) CurrentData(val interface{}) error { if reflectVal.Kind() != reflect.Ptr || reflectVal.IsNil() { return errors.New("val must be a pointer") } - - if !reflect.TypeOf(g.data[g.index]).AssignableTo(reflect.TypeOf(val).Elem()) { - return fmt.Errorf("type:%T can't be assignable to type %T", g.data[g.index], val) + if !g.dataType.AssignableTo(reflect.TypeOf(val).Elem()) { + return fmt.Errorf("type:%T can't be assignable to type %T", g.dataType, val) } reflectCurrentData := reflect.ValueOf(g.data[g.index]) reflectVal.Elem().Set(reflectCurrentData) @@ -58,9 +59,9 @@ func (g *GenericIterator) Next() bool { return false } -// func (g *GenericIterator) GetType() string { -// if len(g.data) == 0 { -// return "" -// } -// return reflect.TypeOf(g.data[0]).Name() -// } +func (g *GenericIterator) GetType() string { + if len(g.data) == 0 { + return "" + } + return g.dataType.Name() +} From 87c5a3566fc25ebecfa61c22e0c8daa9eeff03c4 Mon Sep 17 00:00:00 2001 From: stdevHsequeda Date: Mon, 23 Dec 2019 19:49:36 -0500 Subject: [PATCH 3/6] [generic] refs 290 Changed implementation of all remaining iterators to genericIterator. --- src/coin/mocks/Iterator.go | 52 ++++++++++++++ src/coin/mocks/PubKey.go | 54 ++++++++++++++ src/coin/mocks/SecKey.go | 54 ++++++++++++++ src/coin/skycoin/models/account.go | 48 +++++++++---- src/coin/skycoin/models/account_test.go | 52 ++++++++++---- src/coin/skycoin/models/cipher.go | 7 +- src/coin/skycoin/models/coin.go | 95 ++++++------------------- src/coin/skycoin/models/coin_test.go | 9 ++- src/coin/skycoin/models/network.go | 2 +- src/coin/skycoin/models/network_test.go | 10 ++- src/coin/skycoin/models/networking.go | 29 ++------ src/coin/skycoin/models/wallet.go | 29 ++------ src/coin/skycoin/models/wallet_test.go | 5 +- src/core/account.go | 6 +- src/core/coin.go | 30 -------- src/core/network.go | 14 +--- src/core/wallet.go | 12 +--- src/models/history/historyManager.go | 43 ++++++++--- src/models/modelWallets.go | 30 +++++--- src/models/networkingManager.go | 7 +- src/models/pending/PendingModel.go | 31 ++++++-- src/models/walletsManager.go | 61 ++++++++++++---- 22 files changed, 432 insertions(+), 248 deletions(-) create mode 100644 src/coin/mocks/Iterator.go create mode 100644 src/coin/mocks/PubKey.go create mode 100644 src/coin/mocks/SecKey.go diff --git a/src/coin/mocks/Iterator.go b/src/coin/mocks/Iterator.go new file mode 100644 index 00000000..a4066c54 --- /dev/null +++ b/src/coin/mocks/Iterator.go @@ -0,0 +1,52 @@ +// Code generated by mockery v1.0.0. DO NOT EDIT. + +package mocks + +import mock "github.com/stretchr/testify/mock" + +// Iterator is an autogenerated mock type for the Iterator type +type Iterator struct { + mock.Mock +} + +// CurrentData provides a mock function with given fields: _a0 +func (_m *Iterator) CurrentData(_a0 interface{}) error { + ret := _m.Called(_a0) + + var r0 error + if rf, ok := ret.Get(0).(func(interface{}) error); ok { + r0 = rf(_a0) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// HasNext provides a mock function with given fields: +func (_m *Iterator) HasNext() bool { + ret := _m.Called() + + var r0 bool + if rf, ok := ret.Get(0).(func() bool); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(bool) + } + + return r0 +} + +// Next provides a mock function with given fields: +func (_m *Iterator) Next() bool { + ret := _m.Called() + + var r0 bool + if rf, ok := ret.Get(0).(func() bool); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(bool) + } + + return r0 +} diff --git a/src/coin/mocks/PubKey.go b/src/coin/mocks/PubKey.go new file mode 100644 index 00000000..44cca278 --- /dev/null +++ b/src/coin/mocks/PubKey.go @@ -0,0 +1,54 @@ +// Code generated by mockery v1.0.0. DO NOT EDIT. + +package mocks + +import mock "github.com/stretchr/testify/mock" + +// PubKey is an autogenerated mock type for the PubKey type +type PubKey struct { + mock.Mock +} + +// Bytes provides a mock function with given fields: +func (_m *PubKey) Bytes() []byte { + ret := _m.Called() + + var r0 []byte + if rf, ok := ret.Get(0).(func() []byte); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]byte) + } + } + + return r0 +} + +// Null provides a mock function with given fields: +func (_m *PubKey) Null() bool { + ret := _m.Called() + + var r0 bool + if rf, ok := ret.Get(0).(func() bool); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(bool) + } + + return r0 +} + +// Verify provides a mock function with given fields: +func (_m *PubKey) Verify() error { + ret := _m.Called() + + var r0 error + if rf, ok := ret.Get(0).(func() error); ok { + r0 = rf() + } else { + r0 = ret.Error(0) + } + + return r0 +} diff --git a/src/coin/mocks/SecKey.go b/src/coin/mocks/SecKey.go new file mode 100644 index 00000000..6160f9db --- /dev/null +++ b/src/coin/mocks/SecKey.go @@ -0,0 +1,54 @@ +// Code generated by mockery v1.0.0. DO NOT EDIT. + +package mocks + +import mock "github.com/stretchr/testify/mock" + +// SecKey is an autogenerated mock type for the SecKey type +type SecKey struct { + mock.Mock +} + +// Bytes provides a mock function with given fields: +func (_m *SecKey) Bytes() []byte { + ret := _m.Called() + + var r0 []byte + if rf, ok := ret.Get(0).(func() []byte); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]byte) + } + } + + return r0 +} + +// Null provides a mock function with given fields: +func (_m *SecKey) Null() bool { + ret := _m.Called() + + var r0 bool + if rf, ok := ret.Get(0).(func() bool); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(bool) + } + + return r0 +} + +// Verify provides a mock function with given fields: +func (_m *SecKey) Verify() error { + ret := _m.Called() + + var r0 error + if rf, ok := ret.Get(0).(func() error); ok { + r0 = rf() + } else { + r0 = ret.Error(0) + } + + return r0 +} diff --git a/src/coin/skycoin/models/account.go b/src/coin/skycoin/models/account.go index d07d5d63..692f71c8 100644 --- a/src/coin/skycoin/models/account.go +++ b/src/coin/skycoin/models/account.go @@ -42,7 +42,7 @@ func (addr *SkycoinAddress) GetBalance(ticker string) (uint64, error) { func (addr *SkycoinAddress) ListAssets() []string { return []string{Sky, CoinHour} } -func (addr *SkycoinAddress) ScanUnspentOutputs() core.TransactionOutputIterator { +func (addr *SkycoinAddress) ScanUnspentOutputs() core.Iterator { c, err := NewSkycoinApiClient(PoolSection) if err != nil { log.WithError(err).Error("Couldn't get API client") @@ -74,7 +74,7 @@ func (addr *SkycoinAddress) ScanUnspentOutputs() core.TransactionOutputIterator return NewSkycoinTransactionOutputIterator(skyOutputs) } -func (addr *SkycoinAddress) ListTransactions() core.TransactionIterator { +func (addr *SkycoinAddress) ListTransactions() core.Iterator { c, err := NewSkycoinApiClient(PoolSection) if err != nil { @@ -105,7 +105,7 @@ func (addr *SkycoinAddress) ListTransactions() core.TransactionIterator { return NewSkycoinTransactionIterator(transactions) } -func (addr *SkycoinAddress) ListPendingTransactions() (core.TransactionIterator, error) { // ------TODO +func (addr *SkycoinAddress) ListPendingTransactions() (core.Iterator, error) { // ------TODO return nil, nil } @@ -137,7 +137,7 @@ func (wlt *RemoteWallet) ListAssets() []string { return []string{Sky, CoinHour} } -func (wlt *RemoteWallet) ScanUnspentOutputs() core.TransactionOutputIterator { +func (wlt *RemoteWallet) ScanUnspentOutputs() core.Iterator { log.Info("Calling RemoteWallet.GetLoadedAddresses()") addressesIter, err := wlt.GetLoadedAddresses() if err != nil { @@ -152,14 +152,19 @@ func (wlt *RemoteWallet) ScanUnspentOutputs() core.TransactionOutputIterator { return nil } outsIter := addr.GetCryptoAccount().ScanUnspentOutputs() + var out core.TransactionOutput for outsIter.Next() { - unOuts = append(unOuts, outsIter.Value()) + if err := outsIter.CurrentData(&out); err != nil { + log.Error(err) + return nil + } + unOuts = append(unOuts, out) } } return NewSkycoinTransactionOutputIterator(unOuts) } -func (wlt *RemoteWallet) ListTransactions() core.TransactionIterator { +func (wlt *RemoteWallet) ListTransactions() core.Iterator { log.Info("Calling RemoteWallet.GetLoadedAddresses()") addressesIter, err := wlt.GetLoadedAddresses() if err != nil { @@ -174,15 +179,21 @@ func (wlt *RemoteWallet) ListTransactions() core.TransactionIterator { return nil } txnsIter := addr.GetCryptoAccount().ListTransactions() + + var txn core.Transaction for txnsIter.Next() { - txns = append(txns, txnsIter.Value()) + if err := txnsIter.CurrentData(&txn); err != nil { + log.Error(err) + return nil + } + txns = append(txns, txn) } } return NewSkycoinTransactionIterator(txns) } -func (wlt *RemoteWallet) ListPendingTransactions() (core.TransactionIterator, error) { +func (wlt *RemoteWallet) ListPendingTransactions() (core.Iterator, error) { c, err := NewSkycoinApiClient(PoolSection) if err != nil { log.WithError(err).Error("Couldn't get API client") @@ -269,7 +280,7 @@ func (wlt *LocalWallet) ListAssets() []string { return []string{Sky, CoinHour} } -func (wlt *LocalWallet) ScanUnspentOutputs() core.TransactionOutputIterator { +func (wlt *LocalWallet) ScanUnspentOutputs() core.Iterator { log.Info("Calling LocalWallet.GetLoadedAddresses()") addressesIter, err := wlt.GetLoadedAddresses() if err != nil { @@ -284,14 +295,19 @@ func (wlt *LocalWallet) ScanUnspentOutputs() core.TransactionOutputIterator { return nil } outsIter := addr.GetCryptoAccount().ScanUnspentOutputs() + + var out core.TransactionOutput for outsIter.Next() { - unOuts = append(unOuts, outsIter.Value()) + if err := outsIter.CurrentData(&out); err != nil { + return nil + } + unOuts = append(unOuts, out) } } return NewSkycoinTransactionOutputIterator(unOuts) } -func (wlt *LocalWallet) ListTransactions() core.TransactionIterator { +func (wlt *LocalWallet) ListTransactions() core.Iterator { addressesIter, err := wlt.GetLoadedAddresses() if err != nil { log.WithError(err).Error("LocalWallet.GetLoadedAddresses() failed") @@ -305,15 +321,21 @@ func (wlt *LocalWallet) ListTransactions() core.TransactionIterator { return nil } txnsIter := addr.GetCryptoAccount().ListTransactions() + + var txn core.Transaction for txnsIter.Next() { - txns = append(txns, txnsIter.Value()) + if err := txnsIter.CurrentData(&txn); err != nil { + log.Error(err) + return nil + } + txns = append(txns, txn) } } return NewSkycoinTransactionIterator(txns) } -func (wlt *LocalWallet) ListPendingTransactions() (core.TransactionIterator, error) { // ------TODO +func (wlt *LocalWallet) ListPendingTransactions() (core.Iterator, error) { // ------TODO c, err := NewSkycoinApiClient(PoolSection) if err != nil { log.WithError(err).Error("Couldn't get API client") diff --git a/src/coin/skycoin/models/account_test.go b/src/coin/skycoin/models/account_test.go index 4bf12f28..14cf7297 100644 --- a/src/coin/skycoin/models/account_test.go +++ b/src/coin/skycoin/models/account_test.go @@ -55,12 +55,21 @@ func TestWalletListPendingTransactions(t *testing.T) { wallets := NewSkycoinWalletIterator([]core.Wallet{remote, local}) for wallets.Next() { - txns, err := wallets.Value().GetCryptoAccount().ListPendingTransactions() + var wallet core.Wallet + if err := wallets.CurrentData(&wallet); err != nil { + require.NoError(t, err) + } + txns, err := wallet.GetCryptoAccount().ListPendingTransactions() require.NoError(t, err) for txns.Next() { - iter := NewSkycoinTransactionOutputIterator(txns.Value().GetOutputs()) + var txn core.Transaction + require.NoError(t, txns.CurrentData(&txn)) + iter := NewSkycoinTransactionOutputIterator(txn.GetOutputs()) + + var out core.TransactionOutput for iter.Next() { - output := iter.Value() + require.NoError(t, iter.CurrentData(&out)) + output := out val, err3 := output.GetCoins(Sky) require.NoError(t, err3) require.Equal(t, val, uint64(1000000)) @@ -109,8 +118,10 @@ func TestSkycoinAddressScanUnspentOutputs(t *testing.T) { skyAddrs := addrs.GetCryptoAccount() it := skyAddrs.ScanUnspentOutputs() + var out core.TransactionOutput for it.Next() { - output := it.Value() + require.NoError(t, it.CurrentData(&out)) + output := out require.Equal(t, output.GetId(), "hash1") require.Equal(t, output.GetAddress().String(), "2JJ8pgq8EDAnrzf9xxBJapE2qkYLefW4uF8") val, err := output.GetCoins(Sky) @@ -149,11 +160,14 @@ func TestSkycoinAddressListTransactions(t *testing.T) { assert.NoError(t, err) skyAddr := addr.GetCryptoAccount() it := skyAddr.ListTransactions() + var txn core.Transaction it.Next() - thx := it.Value() + require.NoError(t, it.CurrentData(&txn)) + thx := txn require.Equal(t, thx.GetStatus(), core.TXN_STATUS_CONFIRMED) it.Next() - thx = it.Value() + require.NoError(t, it.CurrentData(&txn)) + thx = txn require.Equal(t, thx.GetStatus(), core.TXN_STATUS_PENDING) } @@ -262,8 +276,11 @@ func TestRemoteWalletScanUnspentOutputs(t *testing.T) { } iter := wlt.ScanUnspentOutputs() items := 0 + + var out core.TransactionOutput for iter.Next() { - to := iter.Value() + require.NoError(t, iter.CurrentData(&out)) + to := out items++ require.Equal(t, "2kvLEyXwAYvHfJuFCkjnYNRTUfHPyWgVwKt", to.GetAddress().String()) } @@ -276,8 +293,10 @@ func TestRemoteWalletScanUnspentOutputs(t *testing.T) { } iter = wlt.ScanUnspentOutputs() items = 0 + for iter.Next() { - to := iter.Value() + require.NoError(t, iter.CurrentData(&out)) + to := out items++ require.Nil(t, to) } @@ -321,8 +340,13 @@ func TestRemoteWalletListTransactions(t *testing.T) { } iter := wlt.ListTransactions() items := 0 + + var txn core.Transaction + for iter.Next() { - tx := iter.Value() + require.NoError(t, iter.CurrentData(&txn)) + + tx := txn items++ require.Equal(t, "hash1", tx.GetId()) } @@ -359,8 +383,11 @@ func TestLocalWalletScanUnspentOutputs(t *testing.T) { iter := wlt.ScanUnspentOutputs() items := 0 + + var out core.TransactionOutput for iter.Next() { - to := iter.Value() + require.NoError(t, iter.CurrentData(&out)) + to := out items++ require.Equal(t, "2HPiZkMTD2pB9FZ6HbCxFSXa1FGeNkLeEbP", to.GetAddress().String()) } @@ -397,10 +424,11 @@ func TestLocalWalletListTransactions(t *testing.T) { iter := wlt.ListTransactions() items := 0 + var txn core.Transaction for iter.Next() { - tx := iter.Value() + require.NoError(t, iter.CurrentData(&txn)) items++ - require.Equal(t, "hash1", tx.GetId()) + require.Equal(t, "hash1", txn.GetId()) } require.Equal(t, 4, items) } diff --git a/src/coin/skycoin/models/cipher.go b/src/coin/skycoin/models/cipher.go index 431bb27b..448b8e85 100644 --- a/src/coin/skycoin/models/cipher.go +++ b/src/coin/skycoin/models/cipher.go @@ -153,7 +153,8 @@ func (pk *SkycoinPubKey) Bytes() []byte { // Type assertions var ( - _ core.Address = &SkycoinAddress{} - _ core.PubKey = &SkycoinPubKey{} - _ core.SecKey = &SkycoinSecKey{} + _ core.Address = &SkycoinAddress{} + _ core.PubKey = &SkycoinPubKey{} + _ core.SecKey = &SkycoinSecKey{} + _ core.Iterator = &SkycoinAddressIterator{} ) diff --git a/src/coin/skycoin/models/coin.go b/src/coin/skycoin/models/coin.go index 5394b125..a0a6fbcf 100644 --- a/src/coin/skycoin/models/coin.go +++ b/src/coin/skycoin/models/coin.go @@ -226,56 +226,22 @@ func (txn *SkycoinPendingTransaction) IsFullySigned() (bool, error) { * SkycoinTransactionIterator */ type SkycoinTransactionIterator struct { // Implements TransactionIterator interface - Current int - Transactions []core.Transaction -} - -func (it *SkycoinTransactionIterator) Value() core.Transaction { - return it.Transactions[it.Current] -} - -func (it *SkycoinTransactionIterator) Next() bool { - if it.HasNext() { - it.Current++ - return true - } - return false -} - -func (it *SkycoinTransactionIterator) HasNext() bool { - return (it.Current + 1) < len(it.Transactions) + core.Iterator } func NewSkycoinTransactionIterator(transactions []core.Transaction) *SkycoinTransactionIterator { - return &SkycoinTransactionIterator{Transactions: transactions, Current: -1} + return &SkycoinTransactionIterator{Iterator: util.NewGenericIterator(transactions)} } /** * SkycoinTransactionOutputIterator */ type SkycoinTransactionOutputIterator struct { // Implements TransactionOutputIterator interface - Current int - Outputs []core.TransactionOutput -} - -func (it *SkycoinTransactionOutputIterator) Value() core.TransactionOutput { - return it.Outputs[it.Current] -} - -func (it *SkycoinTransactionOutputIterator) Next() bool { - if it.HasNext() { - it.Current++ - return true - } - return false -} - -func (it *SkycoinTransactionOutputIterator) HasNext() bool { - return (it.Current + 1) < len(it.Outputs) + core.Iterator } func NewSkycoinTransactionOutputIterator(outputs []core.TransactionOutput) *SkycoinTransactionOutputIterator { - return &SkycoinTransactionOutputIterator{Outputs: outputs, Current: -1} + return &SkycoinTransactionOutputIterator{Iterator: util.NewGenericIterator(outputs)} } func NewUninjectedTransaction(txn *coin.Transaction, fee uint64) (*SkycoinUninjectedTransaction, error) { @@ -639,28 +605,11 @@ func (in *SkycoinTransactionInput) GetCoins(ticker string) (uint64, error) { * SkycoinTransactionInputIterator */ type SkycoinTransactionInputIterator struct { - current int - data []core.TransactionInput -} - -func (iter *SkycoinTransactionInputIterator) Value() core.TransactionInput { - return iter.data[iter.current] -} - -func (iter *SkycoinTransactionInputIterator) Next() bool { - if iter.HasNext() { - iter.current++ - return true - } - return false -} - -func (iter *SkycoinTransactionInputIterator) HasNext() bool { - return (iter.current + 1) < len(iter.data) + core.Iterator } func NewSkycoinTransactioninputIterator(ins []core.TransactionInput) *SkycoinTransactionInputIterator { - return &SkycoinTransactionInputIterator{data: ins, current: -1} + return &SkycoinTransactionInputIterator{Iterator: util.NewGenericIterator(ins)} } /** @@ -997,20 +946,20 @@ func (txn *SkycoinCreatedTransaction) IsFullySigned() (bool, error) { // Type assertions to abort compilation if contracts not satisfied var ( - _ skytypes.SkycoinTxn = &SkycoinPendingTransaction{} - _ skytypes.ReadableTxn = &SkycoinPendingTransaction{} - _ core.Transaction = &SkycoinPendingTransaction{} - _ core.TransactionIterator = &SkycoinTransactionIterator{} - _ core.TransactionInputIterator = &SkycoinTransactionInputIterator{} - _ core.TransactionOutputIterator = &SkycoinTransactionOutputIterator{} - _ core.Transaction = &SkycoinUninjectedTransaction{} - _ skytypes.SkycoinTxn = &SkycoinUninjectedTransaction{} - _ skytypes.SkycoinTxn = &SkycoinTransaction{} - _ skytypes.ReadableTxn = &SkycoinTransaction{} - _ core.Transaction = &SkycoinTransaction{} - _ core.TransactionInput = &SkycoinTransactionInput{} - _ core.TransactionOutput = &SkycoinTransactionOutput{} - _ skytypes.SkycoinTxn = &SkycoinCreatedTransaction{} - _ skytypes.ReadableTxn = &SkycoinCreatedTransaction{} - _ core.Transaction = &SkycoinCreatedTransaction{} + _ skytypes.SkycoinTxn = &SkycoinPendingTransaction{} + _ skytypes.ReadableTxn = &SkycoinPendingTransaction{} + _ core.Transaction = &SkycoinPendingTransaction{} + _ core.Iterator = &SkycoinTransactionIterator{} + _ core.Iterator = &SkycoinTransactionInputIterator{} + _ core.Iterator = &SkycoinTransactionOutputIterator{} + _ core.Transaction = &SkycoinUninjectedTransaction{} + _ skytypes.SkycoinTxn = &SkycoinUninjectedTransaction{} + _ skytypes.SkycoinTxn = &SkycoinTransaction{} + _ skytypes.ReadableTxn = &SkycoinTransaction{} + _ core.Transaction = &SkycoinTransaction{} + _ core.TransactionInput = &SkycoinTransactionInput{} + _ core.TransactionOutput = &SkycoinTransactionOutput{} + _ skytypes.SkycoinTxn = &SkycoinCreatedTransaction{} + _ skytypes.ReadableTxn = &SkycoinCreatedTransaction{} + _ core.Transaction = &SkycoinCreatedTransaction{} ) diff --git a/src/coin/skycoin/models/coin_test.go b/src/coin/skycoin/models/coin_test.go index 463463b1..ce104e31 100644 --- a/src/coin/skycoin/models/coin_test.go +++ b/src/coin/skycoin/models/coin_test.go @@ -67,11 +67,14 @@ func TestSkycoinTransactionGetInputs(t *testing.T) { require.Equal(t, inputs[0].GetId(), "I1") require.Equal(t, inputs[1].GetId(), "I2") it := NewSkycoinTransactioninputIterator(inputs) + + var inp core.TransactionInput for it.Next() { - sky, err := it.Value().GetCoins(Sky) + require.NoError(t, it.CurrentData(&inp)) + sky, err := inp.GetCoins(Sky) require.NoError(t, err) require.Equal(t, sky, uint64(20000000)) - hours, err1 := it.Value().GetCoins(CoinHour) + hours, err1 := inp.GetCoins(CoinHour) require.NoError(t, err1) require.Equal(t, hours, uint64(20)) } @@ -91,7 +94,7 @@ func TestSkycoinTransactionInputGetSpentOutput(t *testing.T) { input := &SkycoinTransactionInput{skyIn: readable.TransactionInput{Hash: "in1"}} output := input.GetSpentOutput() - t.Logf("%#v",output) + t.Logf("%#v", output) require.Equal(t, output.GetId(), "out1") require.Equal(t, output.GetAddress().String(), "2JJ8pgq8EDAnrzf9xxBJapE2qkYLefW4uF8") sky, err := output.GetCoins(Sky) diff --git a/src/coin/skycoin/models/network.go b/src/coin/skycoin/models/network.go index 2c67907c..14b45013 100644 --- a/src/coin/skycoin/models/network.go +++ b/src/coin/skycoin/models/network.go @@ -118,7 +118,7 @@ func (spex *SkycoinPEX) BroadcastTxn(txn core.Transaction) error { return nil } -func (spex *SkycoinPEX) GetTxnPool() (core.TransactionIterator, error) { +func (spex *SkycoinPEX) GetTxnPool() (core.Iterator, error) { logNetwork.Info("Getting transaction pool") c, err := NewSkycoinApiClient(PoolSection) if err != nil { diff --git a/src/coin/skycoin/models/network_test.go b/src/coin/skycoin/models/network_test.go index 9ba5f489..01ae06af 100644 --- a/src/coin/skycoin/models/network_test.go +++ b/src/coin/skycoin/models/network_test.go @@ -2,6 +2,7 @@ package skycoin import ( "encoding/hex" + "github.com/fibercrypto/fibercryptowallet/src/core" "testing" "github.com/SkycoinProject/skycoin/src/visor" @@ -48,10 +49,15 @@ func TestSkycoinPEXGetTxnPool(t *testing.T) { txns, err2 := pex.GetTxnPool() require.NoError(t, err2) + var txn core.Transaction for txns.Next() { - iter := NewSkycoinTransactionOutputIterator(txns.Value().GetOutputs()) + require.NoError(t, txns.CurrentData(&txn)) + iter := NewSkycoinTransactionOutputIterator(txn.GetOutputs()) + + var out core.TransactionOutput for iter.Next() { - output := iter.Value() + require.NoError(t, iter.CurrentData(&out)) + output := out val, err3 := output.GetCoins(Sky) require.NoError(t, err3) require.Equal(t, val, uint64(1000000)) diff --git a/src/coin/skycoin/models/networking.go b/src/coin/skycoin/models/networking.go index 43b486a1..c0cfb28b 100644 --- a/src/coin/skycoin/models/networking.go +++ b/src/coin/skycoin/models/networking.go @@ -1,6 +1,7 @@ package skycoin import ( + "github.com/fibercrypto/fibercryptowallet/src/util" "strings" "github.com/SkycoinProject/skycoin/src/api" @@ -9,33 +10,15 @@ import ( ) type SkycoinPexNodeIterator struct { - //Implements PexNodeIterator interface - current int - networks []core.PexNode -} - -func (it *SkycoinPexNodeIterator) Value() core.PexNode { - return it.networks[it.current] -} - -func (it *SkycoinPexNodeIterator) Next() bool { - if it.HasNext() { - it.current++ - return true - } - return false -} - -func (it *SkycoinPexNodeIterator) HasNext() bool { - return !((it.current + 1) >= len(it.networks)) + core.Iterator } func NewSkycoinPexNodeIterator(network []core.PexNode) *SkycoinPexNodeIterator { - return &SkycoinPexNodeIterator{networks: network, current: -1} + return &SkycoinPexNodeIterator{Iterator: util.NewGenericIterator(network)} } type SkycoinNetworkConnections struct { - //Implements NetworkSet interface + // Implements NetworkSet interface nodeAddress string } @@ -47,7 +30,7 @@ func (remoteNetwork *SkycoinNetworkConnections) newClient() *api.Client { return api.NewClient(remoteNetwork.nodeAddress) } -func (remoteNetwork *SkycoinNetworkConnections) ListPeers() core.PexNodeIterator { +func (remoteNetwork *SkycoinNetworkConnections) ListPeers() core.Iterator { logNetwork.Info("Getting list of peers in Skycoin network connections") c := remoteNetwork.newClient() nets, err := c.NetworkConnections(nil) @@ -107,3 +90,5 @@ func connectionsToNetwork(connection readable.Connection) *SkycoinPexNode { Source: connection.IsTrustedPeer, } } + +var _ core.Iterator = &SkycoinPexNodeIterator{} diff --git a/src/coin/skycoin/models/wallet.go b/src/coin/skycoin/models/wallet.go index 22082214..1564aa5a 100644 --- a/src/coin/skycoin/models/wallet.go +++ b/src/coin/skycoin/models/wallet.go @@ -40,28 +40,11 @@ const ( // SkycoinWalletIterator implements WalletIterator interface type SkycoinWalletIterator struct { - current int - wallets []core.Wallet -} - -func (it *SkycoinWalletIterator) Value() core.Wallet { - return it.wallets[it.current] -} - -func (it *SkycoinWalletIterator) Next() bool { - if it.HasNext() { - it.current++ - return true - } - return false -} - -func (it *SkycoinWalletIterator) HasNext() bool { - return !((it.current + 1) >= len(it.wallets)) + core.Iterator } func NewSkycoinWalletIterator(wallets []core.Wallet) *SkycoinWalletIterator { - return &SkycoinWalletIterator{wallets: wallets, current: -1} + return &SkycoinWalletIterator{Iterator: util.NewGenericIterator(wallets)} } type SkycoinRemoteWallet struct { @@ -70,7 +53,7 @@ type SkycoinRemoteWallet struct { } // ListWallets returns an iterator over wallets in the set -func (wltSrv *SkycoinRemoteWallet) ListWallets() core.WalletIterator { +func (wltSrv *SkycoinRemoteWallet) ListWallets() core.Iterator { logWallet.Info("Listing wallets") c, err := NewSkycoinApiClient(wltSrv.poolSection) if err != nil { @@ -836,7 +819,7 @@ type SkycoinLocalWallet struct { walletDir string } -func (wltSrv *SkycoinLocalWallet) ListWallets() core.WalletIterator { +func (wltSrv *SkycoinLocalWallet) ListWallets() core.Iterator { logWallet.Info("Listing Skycoin local wallets") wallets := make([]core.Wallet, 0) entries, err := ioutil.ReadDir(wltSrv.walletDir) @@ -1397,8 +1380,9 @@ func (wlt *LocalWallet) Transfer(to core.TransactionOutput, options core.KeyValu logWallet.WithError(err).Warn("Couldn't get loaded addresses") return nil, err } + + var addr core.Address for iterAddr.Next() { - var addr core.Address if err := iterAddr.CurrentData(&addr); err != nil { logWallet.Error(err) return nil, err @@ -1704,6 +1688,7 @@ var ( _ core.Wallet = &RemoteWallet{} _ skytypes.SkycoinWallet = &LocalWallet{} _ skytypes.SkycoinWallet = &RemoteWallet{} + _ core.Iterator = &SkycoinWalletIterator{} _ core.WalletEnv = &WalletNode{} _ core.WalletEnv = &WalletDirectory{} _ core.WalletSet = &SkycoinRemoteWallet{} diff --git a/src/coin/skycoin/models/wallet_test.go b/src/coin/skycoin/models/wallet_test.go index f9e47ba4..d4feabd1 100644 --- a/src/coin/skycoin/models/wallet_test.go +++ b/src/coin/skycoin/models/wallet_test.go @@ -83,7 +83,10 @@ func TestSkycoinRemoteWalletListWallets(t *testing.T) { wltSrv := &SkycoinRemoteWallet{poolSection: PoolSection} iter := wltSrv.ListWallets() for iter.Next() { - wlt := iter.Value() + var wlt core.Wallet + if err := iter.CurrentData(&wlt); err != nil { + require.NoError(t, err) + } require.Equal(t, "wallet", wlt.GetLabel()) require.Equal(t, "FiberCrypto", wlt.GetId()) } diff --git a/src/core/account.go b/src/core/account.go index b8c03023..0592b85a 100644 --- a/src/core/account.go +++ b/src/core/account.go @@ -9,9 +9,9 @@ type CryptoAccount interface { ListAssets() []string // ScanUnspentOutputs to determine the outputs that can participate in a transaction // without incurring in double spending - ScanUnspentOutputs() TransactionOutputIterator + ScanUnspentOutputs() Iterator // ListTransactions to show account history - ListTransactions() TransactionIterator + ListTransactions() Iterator // ListPendingTransactions to obtain details of transactions pending for confirmation in the memory - ListPendingTransactions() (TransactionIterator, error) + ListPendingTransactions() (Iterator, error) } diff --git a/src/core/coin.go b/src/core/coin.go index ba03a961..79b33f78 100644 --- a/src/core/coin.go +++ b/src/core/coin.go @@ -39,16 +39,6 @@ type Transaction interface { IsFullySigned() (bool, error) } -// TransactionIterator iterates over a sequence of transactions -type TransactionIterator interface { - // Value of transaction at iterator pointer position - Value() Transaction - // Next discards current value and moves iteration pointer up to next item - Next() bool - // HasNext may be used to query whether more items are to be expected in the sequence - HasNext() bool -} - // TransactionInput provides cryptographic proof of spending funds type TransactionInput interface { // GetId provides transaction input ID @@ -62,16 +52,6 @@ type TransactionInput interface { SupportedAssets() []string } -// TransactionInputIterator iterates over a sequence of transaction inputs -type TransactionInputIterator interface { - // Value of transaction input at iterator pointer position - Value() TransactionInput - // Next discards current value and moves iteration pointer up to next item - Next() bool - // HasNext may be used to query whether more items are to be expected in the sequence - HasNext() bool -} - // TransactionOutput provides cryptographic proof of funds transfer type TransactionOutput interface { // GetId provides transaction output ID @@ -86,16 +66,6 @@ type TransactionOutput interface { SupportedAssets() []string } -// TransactionOutputIterator iterates over a sequence of transaction outputs -type TransactionOutputIterator interface { - // Value of transaction output at iterator pointer position - Value() TransactionOutput - // Next discards current value and moves iteration pointer up to next item - Next() bool - // HasNext may be used to query whether more items are to be expected in the sequence - HasNext() bool -} - // Block included in the blockchain type Block interface { // GetHash returns block ID diff --git a/src/core/network.go b/src/core/network.go index edf5b7c1..b9709958 100644 --- a/src/core/network.go +++ b/src/core/network.go @@ -16,27 +16,17 @@ var multiConnectionsPool *MultiConnectionsPool // PEX exposes cryptocurrency API for peer-to-peer communication type PEX interface { // GetTxnPool return transactions pending for confirmation by network peers - GetTxnPool() (TransactionIterator, error) + GetTxnPool() (Iterator, error) // GetConnection enumerate connectionns to peer nodes GetConnections() (PexNodeSet, error) // BroadcastTxn injects a transaction for confirmation by network peers BroadcastTxn(txn Transaction) error } -// PexNodeIterator scans nodes in a set -type PexNodeIterator interface { - // Value of PEX node data instance at iterator pointer position - Value() PexNode - // Next discards current value and moves iteration pointer up to next item - Next() bool - // HasNext may be used to query whether more items are to be expected in the sequence - HasNext() bool -} - // PexNodeSet represent a set of nodes type PexNodeSet interface { // ListPeers offers an iterator over this set of nodes - ListPeers() PexNodeIterator + ListPeers() Iterator } // PexNode represents a peer in he cryptocurrency network diff --git a/src/core/wallet.go b/src/core/wallet.go index ff9751b2..c662f538 100644 --- a/src/core/wallet.go +++ b/src/core/wallet.go @@ -1,19 +1,9 @@ package core -// WalletIterator iterates over sequences of wallets -type WalletIterator interface { - // Value of wallet at iterator pointer position - Value() Wallet - // Next discards current value and moves iteration pointer up to next item - Next() bool - // HasNext may be used to query whether more items are to be expected in the sequence - HasNext() bool -} - // WalletSet allows for creating wallets and listing those in a set type WalletSet interface { // ListWallets returns an iterator over wallets in the set - ListWallets() WalletIterator + ListWallets() Iterator // GetWallet to lookup wallet by ID GetWallet(id string) Wallet // CreateWallet instantiates a new wallet given account seed diff --git a/src/models/history/historyManager.go b/src/models/history/historyManager.go index 6ed3e4b7..2a5b21dc 100644 --- a/src/models/history/historyManager.go +++ b/src/models/history/historyManager.go @@ -87,25 +87,40 @@ func (hm *HistoryManager) getTransactionsOfAddresses(filterAddresses []string) [ logHistoryManager.WithError(nil).Warn("Couldn't get transactions of Addresses") return make([]*transactions.TransactionDetails, 0) } + + var wallet core.Wallet for wltIterator.Next() { - addressIterator, err := wltIterator.Value().GetLoadedAddresses() + if err := wltIterator.CurrentData(&wallet); err != nil { + logHistoryManager.Error(err) + } + addressIterator, err := wallet.GetLoadedAddresses() if err != nil { logHistoryManager.Warn("Couldn't get address iterator") continue } + + var addr core.Address for addressIterator.Next() { - _, ok := find[addressIterator.Value().String()] + if err := addressIterator.CurrentData(&addr); err != nil { + logHistoryManager.Error(err) + } + _, ok := find[addr.String()] if ok { - txnsIterator := addressIterator.Value().GetCryptoAccount().ListTransactions() + txnsIterator := addr.GetCryptoAccount().ListTransactions() if txnsIterator == nil { logHistoryManager.Warn("Couldn't get transaction iterator") continue } + + var txn core.Transaction for txnsIterator.Next() { - _, ok2 := txnFind[txnsIterator.Value().GetId()] + if err := txnsIterator.CurrentData(&txn); err != nil { + logHistoryManager.Error(err) + } + _, ok2 := txnFind[txn.GetId()] if !ok2 { - txns = append(txns, txnsIterator.Value()) - txnFind[txnsIterator.Value().GetId()] = struct{}{} + txns = append(txns, txn) + txnFind[txn.GetId()] = struct{}{} } } } @@ -316,7 +331,7 @@ func (hm *HistoryManager) getTransactionsOfAddresses(filterAddresses []string) [ } txnDetails.SetHoursTraspassed(util.FormatCoins(traspassedHoursMoved, accuracy)) val := float64(skyAmountMoved) - //FIXME: Error here is skipped + // FIXME: Error here is skipped accuracy, _ = util.AltcoinQuotient(params.SkycoinTicker) if err != nil { logHistoryManager.WithError(err).Warn("Couldn't get Skycoins quotient") @@ -407,15 +422,25 @@ func (hm *HistoryManager) getAddressesWithWallets() map[string]string { logHistoryManager.WithError(nil).Warn("Couldn't load addresses") return response } + + var wlt core.Wallet for it.Next() { - wlt := it.Value() + if err := it.CurrentData(&wlt); err != nil { + logHistoryManager.Error(err) + } + addresses, err := wlt.GetLoadedAddresses() if err != nil { logHistoryManager.WithError(err).Warn("Couldn't get loaded addresses") continue } + + var addr core.Address for addresses.Next() { - response[addresses.Value().String()] = wlt.GetId() + if err := addresses.CurrentData(&addr); err != nil { + logHistoryManager.Error(err) + } + response[addr.String()] = wlt.GetId() } } diff --git a/src/models/modelWallets.go b/src/models/modelWallets.go index 7e5104bf..2ae30c4e 100644 --- a/src/models/modelWallets.go +++ b/src/models/modelWallets.go @@ -110,28 +110,40 @@ func (m *ModelWallets) loadModel() { logWalletsModel.WithError(nil).Warn("Couldn't load wallet") return } + + var wlt core.Wallet for wallets.Next() { - addresses, err := wallets.Value().GetLoadedAddresses() + if err := wallets.CurrentData(&wlt); err != nil { + logWalletModel.Error(err) + } + addresses, err := wlt.GetLoadedAddresses() if err != nil { logWalletsModel.WithError(nil).Warn("Couldn't get loaded address") return } ma := NewModelAddresses(nil) - ma.SetName(wallets.Value().GetLabel()) + ma.SetName(wlt.GetLabel()) oModels := make([]*ModelOutputs, 0) + var addr core.Address for addresses.Next() { - a := addresses.Value() - outputs := a.GetCryptoAccount().ScanUnspentOutputs() + if err := addresses.CurrentData(&addr); err != nil { + logWalletModel.Error(err) + } + + outputs := addr.GetCryptoAccount().ScanUnspentOutputs() mo := NewModelOutputs(nil) - mo.SetAddress(a.String()) + mo.SetAddress(addr.String()) qOutputs := make([]*QOutput, 0) + var out core.TransactionOutput for outputs.Next() { - to := outputs.Value() + if err := outputs.CurrentData(&out); err != nil { + logWalletModel.Error(err) + } qo := NewQOutput(nil) - qo.SetOutputID(to.GetId()) - val, err := to.GetCoins(coin.Sky) + qo.SetOutputID(out.GetId()) + val, err := out.GetCoins(coin.Sky) if err != nil { logWalletsModel.WithError(nil).Warn("Couldn't get " + coin.Sky + " coins") continue @@ -143,7 +155,7 @@ func (m *ModelWallets) loadModel() { } coins := util.FormatCoins(val, accuracy) qo.SetAddressSky(coins) - val, err = to.GetCoins(coin.CoinHoursTicker) + val, err = out.GetCoins(coin.CoinHoursTicker) if err != nil { logWalletsModel.WithError(err).Warn("Couldn't get " + coin.CoinHoursTicker + " coins") continue diff --git a/src/models/networkingManager.go b/src/models/networkingManager.go index 5947e359..189a6159 100644 --- a/src/models/networkingManager.go +++ b/src/models/networkingManager.go @@ -33,8 +33,11 @@ func (net *NetworkingManager) getNetworks() []*QNetworking { return networks } for netIterator.Next() { - - networks = append(networks, INetworkToQNetworking(netIterator.Value())) + var pexNode core.PexNode + if err := netIterator.CurrentData(&pexNode); err != nil { + logNetworkingManager.Error(err) + } + networks = append(networks, INetworkToQNetworking(pexNode)) } return networks diff --git a/src/models/pending/PendingModel.go b/src/models/pending/PendingModel.go index e7eaac9c..50f1b548 100644 --- a/src/models/pending/PendingModel.go +++ b/src/models/pending/PendingModel.go @@ -1,7 +1,7 @@ package pending import ( - "github.com/fibercrypto/fibercryptowallet/src/coin/skycoin/models" //callable as skycoin + "github.com/fibercrypto/fibercryptowallet/src/coin/skycoin/models" // callable as skycoin "github.com/fibercrypto/fibercryptowallet/src/core" local "github.com/fibercrypto/fibercryptowallet/src/main" "github.com/fibercrypto/fibercryptowallet/src/util" @@ -76,8 +76,13 @@ func (model *PendingTransactionList) getAll() { return } ptModels := make([]*PendingTransaction, 0) + + var txn core.Transaction for txns.Next() { - ptModel := TransactionToPendingTransaction(txns.Value()) + if err := txns.CurrentData(&txn); err != nil { + logPendingTxn.Error(err) + } + ptModel := TransactionToPendingTransaction(txn) ptModel.SetMine(0) ptModels = append(ptModels, ptModel) } @@ -95,16 +100,25 @@ func (model *PendingTransactionList) getMine() { return } ptModels := make([]*PendingTransaction, 0) + + var wallet core.Wallet for wallets.Next() { - account := wallets.Value().GetCryptoAccount() + if err := wallets.CurrentData(&wallet); err != nil { + logPendingTxn.Error(err) + } + account := wallet.GetCryptoAccount() txns, err := account.ListPendingTransactions() if err != nil { - //display an error in qml app when Mine is selected + // display an error in qml app when Mine is selected logPendingTxn.WithError(err).Warn("Couldn't list pending transactions") continue } + var txn core.Transaction for txns.Next() { - txn := txns.Value() + if err := txns.CurrentData(&txn); err != nil { + logPendingTxn.Error(err) + } + txn := txn if txn.GetStatus() == core.TXN_STATUS_PENDING { ptModel := TransactionToPendingTransaction(txn) ptModel.SetMine(1) @@ -124,8 +138,13 @@ func TransactionToPendingTransaction(stxn core.Transaction) *PendingTransaction iterator := skycoin.NewSkycoinTransactionOutputIterator(stxn.GetOutputs()) sky, coinHours := uint64(0), uint64(0) skyErr, coinHoursErr := false, false + + var out core.TransactionOutput for iterator.Next() { - output := iterator.Value() + if err := iterator.CurrentData(&out); err != nil { + logPendingTxn.Error(err) + } + output := out val, err := output.GetCoins(skycoin.Sky) if err != nil { logPendingTxn.WithError(err).Warn("Couldn't get Skycoins") diff --git a/src/models/walletsManager.go b/src/models/walletsManager.go index e91645d9..a35142de 100644 --- a/src/models/walletsManager.go +++ b/src/models/walletsManager.go @@ -175,8 +175,12 @@ func (walletM *WalletManager) updateAddresses(wltId string) { walletM.addresseseByWallets[wltId] = qAddresses return } + + var addr core.Address for it.Next() { - addr := it.Value() + if err := it.CurrentData(&addr); err != nil { + logWalletManager.Error(err) + } qAddress := NewQAddress(nil) qml.QQmlEngine_SetObjectOwnership(qAddress, qml.QQmlEngine__CppOwnership) qAddress.SetAddress(addr.String()) @@ -228,12 +232,18 @@ func (walletM *WalletManager) updateOutputs(wltId, address string) { walletM.outputsByAddress[address] = outs return } + var addr core.Address + for addressIterator.Next() { - if addressIterator.Value().String() == address { - addr = addressIterator.Value() + if err := addressIterator.CurrentData(&addr); err != nil { + logWalletManager.Error(err) + } + + if addr.String() == address { break } + addr = nil } if addr == nil { logWalletManager.WithError(err).Warn("Couldn't get address") @@ -246,11 +256,16 @@ func (walletM *WalletManager) updateOutputs(wltId, address string) { walletM.outputsByAddress[address] = outs return } + + var out core.TransactionOutput for outsIter.Next() { + if err := outsIter.CurrentData(&out); err != nil { + logWalletManager.Error(err) + } qout := NewQOutput(nil) qml.QQmlEngine_SetObjectOwnership(qout, qml.QQmlEngine__CppOwnership) - qout.SetOutputID(outsIter.Value().GetId()) - skyV, err := outsIter.Value().GetCoins(sky.Sky) + qout.SetOutputID(out.GetId()) + skyV, err := out.GetCoins(sky.Sky) if err != nil { qout.SetAddressSky("N/A") logWalletManager.WithError(err).Warn("Couldn't get " + sky.Sky + " coins") @@ -264,7 +279,7 @@ func (walletM *WalletManager) updateOutputs(wltId, address string) { } sSky := util.FormatCoins(skyV, quotient) qout.SetAddressSky(sSky) - ch, err := outsIter.Value().GetCoins(sky.CoinHour) + ch, err := out.GetCoins(sky.CoinHour) if err != nil { qout.SetAddressCoinHours("N/A") logWalletManager.WithError(err).Warn("Couldn't get " + sky.CoinHour + " coins") @@ -293,14 +308,19 @@ func (walletM *WalletManager) updateWallets() { logWalletManager.WithError(nil).Warn("Couldn't get a wallet iterator") return } + + var wlt core.Wallet for it.Next() { + if err := it.CurrentData(&wlt); err != nil { + logWalletManager.Error(err) + } - encrypted, err := walletM.WalletEnv.GetStorage().IsEncrypted(it.Value().GetId()) + encrypted, err := walletM.WalletEnv.GetStorage().IsEncrypted(wlt.GetId()) if err != nil { logWalletManager.WithError(err).Warn("Couldn't get wallet by id") continue } - qw := fromWalletToQWallet(it.Value(), encrypted) + qw := fromWalletToQWallet(wlt, encrypted) qWallets = append(qWallets, qw) } @@ -315,8 +335,12 @@ func (walletM *WalletManager) getAllAddresses() []*QAddress { logWalletManager.Warn("Error getting the list of wallets") return nil } + var wlt core.Wallet for wltIter.Next() { - qAddresses = append(qAddresses, walletM.getAddresses(wltIter.Value().GetId())...) + if err := wltIter.CurrentData(&wlt); err != nil { + logWalletManager.Error(err) + } + qAddresses = append(qAddresses, walletM.getAddresses(wlt.GetId())...) } return qAddresses } @@ -526,8 +550,13 @@ func (walletM *WalletManager) getOutputsFromWallet(wltId string) []*QOutput { logWalletManager.WithError(err).Warn("Couldn't load addresses iterator") return nil } + + var addr core.Address for addrIter.Next() { - outs = append(outs, walletM.getOutputs(wltId, addrIter.Value().String())...) + if err := addrIter.CurrentData(&addr); err != nil { + logWalletManager.Error(err) + } + outs = append(outs, walletM.getOutputs(wltId, addr.String())...) } logWalletManager.Info("Loaded all outputs") return outs @@ -794,23 +823,27 @@ func (walletM *WalletManager) getWallets() []*QWallet { } + var wlt core.Wallet for it.Next() { + if err := it.CurrentData(&wlt); err != nil { + logWalletManager.Error(err) + } - encrypted, err := walletM.WalletEnv.GetStorage().IsEncrypted(it.Value().GetId()) + encrypted, err := walletM.WalletEnv.GetStorage().IsEncrypted(wlt.GetId()) if err != nil { logWalletManager.WithError(err).Error("Couldn't get wallets") return walletM.wallets } if encrypted { - qw := fromWalletToQWallet(it.Value(), true) + qw := fromWalletToQWallet(wlt, true) walletM.wallets = append(walletM.wallets, qw) } else { - qw := fromWalletToQWallet(it.Value(), false) + qw := fromWalletToQWallet(wlt, false) walletM.wallets = append(walletM.wallets, qw) } } - //walletM.wallets = make([]*QWallet, 0) + // walletM.wallets = make([]*QWallet, 0) logWalletManager.Info("Wallets obtained") return walletM.wallets From aa6c467a64533d5a3dcc5bf7d9de179942979035 Mon Sep 17 00:00:00 2001 From: stdevHsequeda Date: Mon, 23 Dec 2019 20:06:14 -0500 Subject: [PATCH 4/6] [generic] refs 290 Solved conflict with modelWallets.go file in model package. --- src/coin/mocks/Address.go | 66 ++++++++++++++++++- src/coin/mocks/AltcoinManager.go | 6 +- src/coin/mocks/AltcoinPlugin.go | 75 +++++++++++++++++++++- src/coin/mocks/Block.go | 6 +- src/coin/mocks/BlockchainSignService.go | 6 +- src/coin/mocks/BlockchainStatus.go | 6 +- src/coin/mocks/BlockchainTransactionAPI.go | 6 +- src/coin/mocks/CryptoAccount.go | 30 +++++---- src/coin/mocks/MultiPool.go | 6 +- src/coin/mocks/PEX.go | 14 ++-- src/coin/mocks/PexNodeSet.go | 14 ++-- src/coin/mocks/Transaction.go | 6 +- src/coin/mocks/TransactionInput.go | 6 +- src/coin/mocks/TransactionOutput.go | 6 +- src/coin/mocks/TxnSigner.go | 6 +- src/coin/mocks/TxnSignerIterator.go | 6 +- src/coin/mocks/Wallet.go | 22 ++++--- src/coin/mocks/WalletAddress.go | 6 +- src/coin/mocks/WalletEnv.go | 6 +- src/coin/mocks/WalletOutput.go | 6 +- src/coin/mocks/WalletSet.go | 58 +++++++++++++---- src/coin/mocks/WalletStorage.go | 6 +- src/models/modelWallets.go | 6 ++ 23 files changed, 292 insertions(+), 83 deletions(-) diff --git a/src/coin/mocks/Address.go b/src/coin/mocks/Address.go index 124e4378..6fed5f8e 100644 --- a/src/coin/mocks/Address.go +++ b/src/coin/mocks/Address.go @@ -2,14 +2,48 @@ package mocks -import core "github.com/fibercrypto/fibercryptowallet/src/core" -import mock "github.com/stretchr/testify/mock" +import ( + core "github.com/fibercrypto/fibercryptowallet/src/core" + mock "github.com/stretchr/testify/mock" +) // Address is an autogenerated mock type for the Address type type Address struct { mock.Mock } +// Bytes provides a mock function with given fields: +func (_m *Address) Bytes() []byte { + ret := _m.Called() + + var r0 []byte + if rf, ok := ret.Get(0).(func() []byte); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]byte) + } + } + + return r0 +} + +// Checksum provides a mock function with given fields: +func (_m *Address) Checksum() core.Checksum { + ret := _m.Called() + + var r0 core.Checksum + if rf, ok := ret.Get(0).(func() core.Checksum); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(core.Checksum) + } + } + + return r0 +} + // GetCryptoAccount provides a mock function with given fields: func (_m *Address) GetCryptoAccount() core.CryptoAccount { ret := _m.Called() @@ -40,6 +74,20 @@ func (_m *Address) IsBip32() bool { return r0 } +// Null provides a mock function with given fields: +func (_m *Address) Null() bool { + ret := _m.Called() + + var r0 bool + if rf, ok := ret.Get(0).(func() bool); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(bool) + } + + return r0 +} + // String provides a mock function with given fields: func (_m *Address) String() string { ret := _m.Called() @@ -53,3 +101,17 @@ func (_m *Address) String() string { return r0 } + +// Verify provides a mock function with given fields: _a0 +func (_m *Address) Verify(_a0 core.PubKey) error { + ret := _m.Called(_a0) + + var r0 error + if rf, ok := ret.Get(0).(func(core.PubKey) error); ok { + r0 = rf(_a0) + } else { + r0 = ret.Error(0) + } + + return r0 +} diff --git a/src/coin/mocks/AltcoinManager.go b/src/coin/mocks/AltcoinManager.go index de070fc3..2e24ebb2 100644 --- a/src/coin/mocks/AltcoinManager.go +++ b/src/coin/mocks/AltcoinManager.go @@ -2,8 +2,10 @@ package mocks -import core "github.com/fibercrypto/fibercryptowallet/src/core" -import mock "github.com/stretchr/testify/mock" +import ( + core "github.com/fibercrypto/fibercryptowallet/src/core" + mock "github.com/stretchr/testify/mock" +) // AltcoinManager is an autogenerated mock type for the AltcoinManager type type AltcoinManager struct { diff --git a/src/coin/mocks/AltcoinPlugin.go b/src/coin/mocks/AltcoinPlugin.go index 3c99d3d3..58bf3c60 100644 --- a/src/coin/mocks/AltcoinPlugin.go +++ b/src/coin/mocks/AltcoinPlugin.go @@ -2,14 +2,39 @@ package mocks -import core "github.com/fibercrypto/fibercryptowallet/src/core" -import mock "github.com/stretchr/testify/mock" +import ( + core "github.com/fibercrypto/fibercryptowallet/src/core" + mock "github.com/stretchr/testify/mock" +) // AltcoinPlugin is an autogenerated mock type for the AltcoinPlugin type type AltcoinPlugin struct { mock.Mock } +// AddressFromString provides a mock function with given fields: _a0 +func (_m *AltcoinPlugin) AddressFromString(_a0 string) (core.Address, error) { + ret := _m.Called(_a0) + + var r0 core.Address + if rf, ok := ret.Get(0).(func(string) core.Address); ok { + r0 = rf(_a0) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(core.Address) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(string) error); ok { + r1 = rf(_a0) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + // GetDescription provides a mock function with given fields: func (_m *AltcoinPlugin) GetDescription() string { ret := _m.Called() @@ -155,7 +180,53 @@ func (_m *AltcoinPlugin) LoadWalletEnvs() []core.WalletEnv { return r0 } +// PubKeyFromBytes provides a mock function with given fields: _a0 +func (_m *AltcoinPlugin) PubKeyFromBytes(_a0 []byte) (core.PubKey, error) { + ret := _m.Called(_a0) + + var r0 core.PubKey + if rf, ok := ret.Get(0).(func([]byte) core.PubKey); ok { + r0 = rf(_a0) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(core.PubKey) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func([]byte) error); ok { + r1 = rf(_a0) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + // RegisterTo provides a mock function with given fields: manager func (_m *AltcoinPlugin) RegisterTo(manager core.AltcoinManager) { _m.Called(manager) } + +// SecKeyFromBytes provides a mock function with given fields: _a0 +func (_m *AltcoinPlugin) SecKeyFromBytes(_a0 []byte) (core.SecKey, error) { + ret := _m.Called(_a0) + + var r0 core.SecKey + if rf, ok := ret.Get(0).(func([]byte) core.SecKey); ok { + r0 = rf(_a0) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(core.SecKey) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func([]byte) error); ok { + r1 = rf(_a0) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} diff --git a/src/coin/mocks/Block.go b/src/coin/mocks/Block.go index 01299560..115722d2 100644 --- a/src/coin/mocks/Block.go +++ b/src/coin/mocks/Block.go @@ -2,8 +2,10 @@ package mocks -import core "github.com/fibercrypto/fibercryptowallet/src/core" -import mock "github.com/stretchr/testify/mock" +import ( + core "github.com/fibercrypto/fibercryptowallet/src/core" + mock "github.com/stretchr/testify/mock" +) // Block is an autogenerated mock type for the Block type type Block struct { diff --git a/src/coin/mocks/BlockchainSignService.go b/src/coin/mocks/BlockchainSignService.go index 2fda5274..0b68ec7d 100644 --- a/src/coin/mocks/BlockchainSignService.go +++ b/src/coin/mocks/BlockchainSignService.go @@ -2,8 +2,10 @@ package mocks -import core "github.com/fibercrypto/fibercryptowallet/src/core" -import mock "github.com/stretchr/testify/mock" +import ( + core "github.com/fibercrypto/fibercryptowallet/src/core" + mock "github.com/stretchr/testify/mock" +) // BlockchainSignService is an autogenerated mock type for the BlockchainSignService type type BlockchainSignService struct { diff --git a/src/coin/mocks/BlockchainStatus.go b/src/coin/mocks/BlockchainStatus.go index e7081868..aa1cff1d 100644 --- a/src/coin/mocks/BlockchainStatus.go +++ b/src/coin/mocks/BlockchainStatus.go @@ -2,8 +2,10 @@ package mocks -import core "github.com/fibercrypto/fibercryptowallet/src/core" -import mock "github.com/stretchr/testify/mock" +import ( + core "github.com/fibercrypto/fibercryptowallet/src/core" + mock "github.com/stretchr/testify/mock" +) // BlockchainStatus is an autogenerated mock type for the BlockchainStatus type type BlockchainStatus struct { diff --git a/src/coin/mocks/BlockchainTransactionAPI.go b/src/coin/mocks/BlockchainTransactionAPI.go index af133a91..581669bc 100644 --- a/src/coin/mocks/BlockchainTransactionAPI.go +++ b/src/coin/mocks/BlockchainTransactionAPI.go @@ -2,8 +2,10 @@ package mocks -import core "github.com/fibercrypto/fibercryptowallet/src/core" -import mock "github.com/stretchr/testify/mock" +import ( + core "github.com/fibercrypto/fibercryptowallet/src/core" + mock "github.com/stretchr/testify/mock" +) // BlockchainTransactionAPI is an autogenerated mock type for the BlockchainTransactionAPI type type BlockchainTransactionAPI struct { diff --git a/src/coin/mocks/CryptoAccount.go b/src/coin/mocks/CryptoAccount.go index eebf8290..8d7f0b53 100644 --- a/src/coin/mocks/CryptoAccount.go +++ b/src/coin/mocks/CryptoAccount.go @@ -2,8 +2,10 @@ package mocks -import core "github.com/fibercrypto/fibercryptowallet/src/core" -import mock "github.com/stretchr/testify/mock" +import ( + core "github.com/fibercrypto/fibercryptowallet/src/core" + mock "github.com/stretchr/testify/mock" +) // CryptoAccount is an autogenerated mock type for the CryptoAccount type type CryptoAccount struct { @@ -48,15 +50,15 @@ func (_m *CryptoAccount) ListAssets() []string { } // ListPendingTransactions provides a mock function with given fields: -func (_m *CryptoAccount) ListPendingTransactions() (core.TransactionIterator, error) { +func (_m *CryptoAccount) ListPendingTransactions() (core.Iterator, error) { ret := _m.Called() - var r0 core.TransactionIterator - if rf, ok := ret.Get(0).(func() core.TransactionIterator); ok { + var r0 core.Iterator + if rf, ok := ret.Get(0).(func() core.Iterator); ok { r0 = rf() } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(core.TransactionIterator) + r0 = ret.Get(0).(core.Iterator) } } @@ -71,15 +73,15 @@ func (_m *CryptoAccount) ListPendingTransactions() (core.TransactionIterator, er } // ListTransactions provides a mock function with given fields: -func (_m *CryptoAccount) ListTransactions() core.TransactionIterator { +func (_m *CryptoAccount) ListTransactions() core.Iterator { ret := _m.Called() - var r0 core.TransactionIterator - if rf, ok := ret.Get(0).(func() core.TransactionIterator); ok { + var r0 core.Iterator + if rf, ok := ret.Get(0).(func() core.Iterator); ok { r0 = rf() } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(core.TransactionIterator) + r0 = ret.Get(0).(core.Iterator) } } @@ -87,15 +89,15 @@ func (_m *CryptoAccount) ListTransactions() core.TransactionIterator { } // ScanUnspentOutputs provides a mock function with given fields: -func (_m *CryptoAccount) ScanUnspentOutputs() core.TransactionOutputIterator { +func (_m *CryptoAccount) ScanUnspentOutputs() core.Iterator { ret := _m.Called() - var r0 core.TransactionOutputIterator - if rf, ok := ret.Get(0).(func() core.TransactionOutputIterator); ok { + var r0 core.Iterator + if rf, ok := ret.Get(0).(func() core.Iterator); ok { r0 = rf() } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(core.TransactionOutputIterator) + r0 = ret.Get(0).(core.Iterator) } } diff --git a/src/coin/mocks/MultiPool.go b/src/coin/mocks/MultiPool.go index 61d1b531..e24988f8 100644 --- a/src/coin/mocks/MultiPool.go +++ b/src/coin/mocks/MultiPool.go @@ -2,8 +2,10 @@ package mocks -import core "github.com/fibercrypto/fibercryptowallet/src/core" -import mock "github.com/stretchr/testify/mock" +import ( + core "github.com/fibercrypto/fibercryptowallet/src/core" + mock "github.com/stretchr/testify/mock" +) // MultiPool is an autogenerated mock type for the MultiPool type type MultiPool struct { diff --git a/src/coin/mocks/PEX.go b/src/coin/mocks/PEX.go index 1b8a5cd7..49277b6d 100644 --- a/src/coin/mocks/PEX.go +++ b/src/coin/mocks/PEX.go @@ -2,8 +2,10 @@ package mocks -import core "github.com/fibercrypto/fibercryptowallet/src/core" -import mock "github.com/stretchr/testify/mock" +import ( + core "github.com/fibercrypto/fibercryptowallet/src/core" + mock "github.com/stretchr/testify/mock" +) // PEX is an autogenerated mock type for the PEX type type PEX struct { @@ -48,15 +50,15 @@ func (_m *PEX) GetConnections() (core.PexNodeSet, error) { } // GetTxnPool provides a mock function with given fields: -func (_m *PEX) GetTxnPool() (core.TransactionIterator, error) { +func (_m *PEX) GetTxnPool() (core.Iterator, error) { ret := _m.Called() - var r0 core.TransactionIterator - if rf, ok := ret.Get(0).(func() core.TransactionIterator); ok { + var r0 core.Iterator + if rf, ok := ret.Get(0).(func() core.Iterator); ok { r0 = rf() } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(core.TransactionIterator) + r0 = ret.Get(0).(core.Iterator) } } diff --git a/src/coin/mocks/PexNodeSet.go b/src/coin/mocks/PexNodeSet.go index 46a15cd3..2df9c56f 100644 --- a/src/coin/mocks/PexNodeSet.go +++ b/src/coin/mocks/PexNodeSet.go @@ -2,8 +2,10 @@ package mocks -import core "github.com/fibercrypto/fibercryptowallet/src/core" -import mock "github.com/stretchr/testify/mock" +import ( + core "github.com/fibercrypto/fibercryptowallet/src/core" + mock "github.com/stretchr/testify/mock" +) // PexNodeSet is an autogenerated mock type for the PexNodeSet type type PexNodeSet struct { @@ -11,15 +13,15 @@ type PexNodeSet struct { } // ListPeers provides a mock function with given fields: -func (_m *PexNodeSet) ListPeers() core.PexNodeIterator { +func (_m *PexNodeSet) ListPeers() core.Iterator { ret := _m.Called() - var r0 core.PexNodeIterator - if rf, ok := ret.Get(0).(func() core.PexNodeIterator); ok { + var r0 core.Iterator + if rf, ok := ret.Get(0).(func() core.Iterator); ok { r0 = rf() } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(core.PexNodeIterator) + r0 = ret.Get(0).(core.Iterator) } } diff --git a/src/coin/mocks/Transaction.go b/src/coin/mocks/Transaction.go index 8a847125..c5aa0213 100644 --- a/src/coin/mocks/Transaction.go +++ b/src/coin/mocks/Transaction.go @@ -2,8 +2,10 @@ package mocks -import core "github.com/fibercrypto/fibercryptowallet/src/core" -import mock "github.com/stretchr/testify/mock" +import ( + core "github.com/fibercrypto/fibercryptowallet/src/core" + mock "github.com/stretchr/testify/mock" +) // Transaction is an autogenerated mock type for the Transaction type type Transaction struct { diff --git a/src/coin/mocks/TransactionInput.go b/src/coin/mocks/TransactionInput.go index 1c92673d..4b805038 100644 --- a/src/coin/mocks/TransactionInput.go +++ b/src/coin/mocks/TransactionInput.go @@ -2,8 +2,10 @@ package mocks -import core "github.com/fibercrypto/fibercryptowallet/src/core" -import mock "github.com/stretchr/testify/mock" +import ( + core "github.com/fibercrypto/fibercryptowallet/src/core" + mock "github.com/stretchr/testify/mock" +) // TransactionInput is an autogenerated mock type for the TransactionInput type type TransactionInput struct { diff --git a/src/coin/mocks/TransactionOutput.go b/src/coin/mocks/TransactionOutput.go index cc048507..bf9c4252 100644 --- a/src/coin/mocks/TransactionOutput.go +++ b/src/coin/mocks/TransactionOutput.go @@ -2,8 +2,10 @@ package mocks -import core "github.com/fibercrypto/fibercryptowallet/src/core" -import mock "github.com/stretchr/testify/mock" +import ( + core "github.com/fibercrypto/fibercryptowallet/src/core" + mock "github.com/stretchr/testify/mock" +) // TransactionOutput is an autogenerated mock type for the TransactionOutput type type TransactionOutput struct { diff --git a/src/coin/mocks/TxnSigner.go b/src/coin/mocks/TxnSigner.go index 1a6b3f40..237cf0db 100644 --- a/src/coin/mocks/TxnSigner.go +++ b/src/coin/mocks/TxnSigner.go @@ -2,8 +2,10 @@ package mocks -import core "github.com/fibercrypto/fibercryptowallet/src/core" -import mock "github.com/stretchr/testify/mock" +import ( + core "github.com/fibercrypto/fibercryptowallet/src/core" + mock "github.com/stretchr/testify/mock" +) // TxnSigner is an autogenerated mock type for the TxnSigner type type TxnSigner struct { diff --git a/src/coin/mocks/TxnSignerIterator.go b/src/coin/mocks/TxnSignerIterator.go index be49a8b4..1ae85e7c 100644 --- a/src/coin/mocks/TxnSignerIterator.go +++ b/src/coin/mocks/TxnSignerIterator.go @@ -2,8 +2,10 @@ package mocks -import core "github.com/fibercrypto/fibercryptowallet/src/core" -import mock "github.com/stretchr/testify/mock" +import ( + core "github.com/fibercrypto/fibercryptowallet/src/core" + mock "github.com/stretchr/testify/mock" +) // TxnSignerIterator is an autogenerated mock type for the TxnSignerIterator type type TxnSignerIterator struct { diff --git a/src/coin/mocks/Wallet.go b/src/coin/mocks/Wallet.go index d35a0180..a42abf62 100644 --- a/src/coin/mocks/Wallet.go +++ b/src/coin/mocks/Wallet.go @@ -2,8 +2,10 @@ package mocks -import core "github.com/fibercrypto/fibercryptowallet/src/core" -import mock "github.com/stretchr/testify/mock" +import ( + core "github.com/fibercrypto/fibercryptowallet/src/core" + mock "github.com/stretchr/testify/mock" +) // Wallet is an autogenerated mock type for the Wallet type type Wallet struct { @@ -11,15 +13,15 @@ type Wallet struct { } // GenAddresses provides a mock function with given fields: addrType, startIndex, count, pwd -func (_m *Wallet) GenAddresses(addrType core.AddressType, startIndex uint32, count uint32, pwd core.PasswordReader) core.AddressIterator { +func (_m *Wallet) GenAddresses(addrType core.AddressType, startIndex uint32, count uint32, pwd core.PasswordReader) core.Iterator { ret := _m.Called(addrType, startIndex, count, pwd) - var r0 core.AddressIterator - if rf, ok := ret.Get(0).(func(core.AddressType, uint32, uint32, core.PasswordReader) core.AddressIterator); ok { + var r0 core.Iterator + if rf, ok := ret.Get(0).(func(core.AddressType, uint32, uint32, core.PasswordReader) core.Iterator); ok { r0 = rf(addrType, startIndex, count, pwd) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(core.AddressIterator) + r0 = ret.Get(0).(core.Iterator) } } @@ -71,15 +73,15 @@ func (_m *Wallet) GetLabel() string { } // GetLoadedAddresses provides a mock function with given fields: -func (_m *Wallet) GetLoadedAddresses() (core.AddressIterator, error) { +func (_m *Wallet) GetLoadedAddresses() (core.Iterator, error) { ret := _m.Called() - var r0 core.AddressIterator - if rf, ok := ret.Get(0).(func() core.AddressIterator); ok { + var r0 core.Iterator + if rf, ok := ret.Get(0).(func() core.Iterator); ok { r0 = rf() } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(core.AddressIterator) + r0 = ret.Get(0).(core.Iterator) } } diff --git a/src/coin/mocks/WalletAddress.go b/src/coin/mocks/WalletAddress.go index 35a4fd3e..550cc205 100644 --- a/src/coin/mocks/WalletAddress.go +++ b/src/coin/mocks/WalletAddress.go @@ -2,8 +2,10 @@ package mocks -import core "github.com/fibercrypto/fibercryptowallet/src/core" -import mock "github.com/stretchr/testify/mock" +import ( + core "github.com/fibercrypto/fibercryptowallet/src/core" + mock "github.com/stretchr/testify/mock" +) // WalletAddress is an autogenerated mock type for the WalletAddress type type WalletAddress struct { diff --git a/src/coin/mocks/WalletEnv.go b/src/coin/mocks/WalletEnv.go index b3cc6724..efdcbc47 100644 --- a/src/coin/mocks/WalletEnv.go +++ b/src/coin/mocks/WalletEnv.go @@ -2,8 +2,10 @@ package mocks -import core "github.com/fibercrypto/fibercryptowallet/src/core" -import mock "github.com/stretchr/testify/mock" +import ( + core "github.com/fibercrypto/fibercryptowallet/src/core" + mock "github.com/stretchr/testify/mock" +) // WalletEnv is an autogenerated mock type for the WalletEnv type type WalletEnv struct { diff --git a/src/coin/mocks/WalletOutput.go b/src/coin/mocks/WalletOutput.go index 58ac6516..e83a8175 100644 --- a/src/coin/mocks/WalletOutput.go +++ b/src/coin/mocks/WalletOutput.go @@ -2,8 +2,10 @@ package mocks -import core "github.com/fibercrypto/fibercryptowallet/src/core" -import mock "github.com/stretchr/testify/mock" +import ( + core "github.com/fibercrypto/fibercryptowallet/src/core" + mock "github.com/stretchr/testify/mock" +) // WalletOutput is an autogenerated mock type for the WalletOutput type type WalletOutput struct { diff --git a/src/coin/mocks/WalletSet.go b/src/coin/mocks/WalletSet.go index 9fb40e99..d51f55b6 100644 --- a/src/coin/mocks/WalletSet.go +++ b/src/coin/mocks/WalletSet.go @@ -2,21 +2,23 @@ package mocks -import core "github.com/fibercrypto/fibercryptowallet/src/core" -import mock "github.com/stretchr/testify/mock" +import ( + core "github.com/fibercrypto/fibercryptowallet/src/core" + mock "github.com/stretchr/testify/mock" +) // WalletSet is an autogenerated mock type for the WalletSet type type WalletSet struct { mock.Mock } -// CreateWallet provides a mock function with given fields: name, seed, isEncryptrd, pwd, scanAddressesN -func (_m *WalletSet) CreateWallet(name string, seed string, isEncryptrd bool, pwd core.PasswordReader, scanAddressesN int) (core.Wallet, error) { - ret := _m.Called(name, seed, isEncryptrd, pwd, scanAddressesN) +// CreateWallet provides a mock function with given fields: name, seed, walletType, isEncryptrd, pwd, scanAddressesN +func (_m *WalletSet) CreateWallet(name string, seed string, walletType string, isEncryptrd bool, pwd core.PasswordReader, scanAddressesN int) (core.Wallet, error) { + ret := _m.Called(name, seed, walletType, isEncryptrd, pwd, scanAddressesN) var r0 core.Wallet - if rf, ok := ret.Get(0).(func(string, string, bool, core.PasswordReader, int) core.Wallet); ok { - r0 = rf(name, seed, isEncryptrd, pwd, scanAddressesN) + if rf, ok := ret.Get(0).(func(string, string, string, bool, core.PasswordReader, int) core.Wallet); ok { + r0 = rf(name, seed, walletType, isEncryptrd, pwd, scanAddressesN) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(core.Wallet) @@ -24,8 +26,8 @@ func (_m *WalletSet) CreateWallet(name string, seed string, isEncryptrd bool, pw } var r1 error - if rf, ok := ret.Get(1).(func(string, string, bool, core.PasswordReader, int) error); ok { - r1 = rf(name, seed, isEncryptrd, pwd, scanAddressesN) + if rf, ok := ret.Get(1).(func(string, string, string, bool, core.PasswordReader, int) error); ok { + r1 = rf(name, seed, walletType, isEncryptrd, pwd, scanAddressesN) } else { r1 = ret.Error(1) } @@ -33,6 +35,20 @@ func (_m *WalletSet) CreateWallet(name string, seed string, isEncryptrd bool, pw return r0, r1 } +// DefaultWalletType provides a mock function with given fields: +func (_m *WalletSet) DefaultWalletType() string { + ret := _m.Called() + + var r0 string + if rf, ok := ret.Get(0).(func() string); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(string) + } + + return r0 +} + // GetWallet provides a mock function with given fields: id func (_m *WalletSet) GetWallet(id string) core.Wallet { ret := _m.Called(id) @@ -50,15 +66,31 @@ func (_m *WalletSet) GetWallet(id string) core.Wallet { } // ListWallets provides a mock function with given fields: -func (_m *WalletSet) ListWallets() core.WalletIterator { +func (_m *WalletSet) ListWallets() core.Iterator { + ret := _m.Called() + + var r0 core.Iterator + if rf, ok := ret.Get(0).(func() core.Iterator); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(core.Iterator) + } + } + + return r0 +} + +// SupportedWalletTypes provides a mock function with given fields: +func (_m *WalletSet) SupportedWalletTypes() []string { ret := _m.Called() - var r0 core.WalletIterator - if rf, ok := ret.Get(0).(func() core.WalletIterator); ok { + var r0 []string + if rf, ok := ret.Get(0).(func() []string); ok { r0 = rf() } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(core.WalletIterator) + r0 = ret.Get(0).([]string) } } diff --git a/src/coin/mocks/WalletStorage.go b/src/coin/mocks/WalletStorage.go index 3802abb2..d84350db 100644 --- a/src/coin/mocks/WalletStorage.go +++ b/src/coin/mocks/WalletStorage.go @@ -2,8 +2,10 @@ package mocks -import core "github.com/fibercrypto/fibercryptowallet/src/core" -import mock "github.com/stretchr/testify/mock" +import ( + core "github.com/fibercrypto/fibercryptowallet/src/core" + mock "github.com/stretchr/testify/mock" +) // WalletStorage is an autogenerated mock type for the WalletStorage type type WalletStorage struct { diff --git a/src/models/modelWallets.go b/src/models/modelWallets.go index 2d827bfb..475d97c3 100644 --- a/src/models/modelWallets.go +++ b/src/models/modelWallets.go @@ -136,6 +136,12 @@ func (m *ModelWallets) loadModel() { mo.SetAddress(addr.String()) qOutputs := make([]*QOutput, 0) + if outputs == nil { + logWalletModel.Warn("unspent outputs not founds") + return + } + + var out core.TransactionOutput for outputs.Next() { if err := outputs.CurrentData(&out); err != nil { logWalletModel.Error(err) From 47fbdbcf8418534c5449c0c3a7af99ea7c9df2ae Mon Sep 17 00:00:00 2001 From: stdevHsequeda Date: Mon, 23 Dec 2019 22:02:29 -0500 Subject: [PATCH 5/6] [generic] refs 290 Created test and added comments to GenericIterators methods in util package. --- src/util/genericIterator.go | 28 +++++--- src/util/genericIterator_test.go | 115 +++++++++++++++++++++++++++++++ 2 files changed, 135 insertions(+), 8 deletions(-) create mode 100644 src/util/genericIterator_test.go diff --git a/src/util/genericIterator.go b/src/util/genericIterator.go index f86b5c9b..39677f72 100644 --- a/src/util/genericIterator.go +++ b/src/util/genericIterator.go @@ -7,12 +7,19 @@ import ( "reflect" ) +var ( + errIteratorEmpty = errors.New("iterator is empty") + errMustBePointer = errors.New("val must be a pointer") +) + +// GenericIterator implement the iterator interface for any type. type GenericIterator struct { data []interface{} index int dataType reflect.Type } +// NewGenericIterator return a new instance of GenericIterator func NewGenericIterator(value interface{}) core.Iterator { var iteratorData []interface{} reflectValue := reflect.ValueOf(value) @@ -30,14 +37,16 @@ func NewGenericIterator(value interface{}) core.Iterator { } } +// CurrentData write in val parameter the current data of the iterator. If val is not a pointer or is nil +// return an error. If iterator type is not assignable to val type return an error. func (g *GenericIterator) CurrentData(val interface{}) error { reflectVal := reflect.ValueOf(val) if len(g.data) == 0 { - return errors.New("iterator is empty") + return errIteratorEmpty } if reflectVal.Kind() != reflect.Ptr || reflectVal.IsNil() { - return errors.New("val must be a pointer") + return errMustBePointer } if !g.dataType.AssignableTo(reflect.TypeOf(val).Elem()) { return fmt.Errorf("type:%T can't be assignable to type %T", g.dataType, val) @@ -47,10 +56,13 @@ func (g *GenericIterator) CurrentData(val interface{}) error { return nil } +// HasNext ask if next instance of the iterator is not nil. func (g *GenericIterator) HasNext() bool { return (g.index + 1) < len(g.data) } +// Next assign to the current data the data of the next instance of the iterator and return true. +// If the next instance not exist (is nil) return false. func (g *GenericIterator) Next() bool { if g.HasNext() { g.index++ @@ -59,9 +71,9 @@ func (g *GenericIterator) Next() bool { return false } -func (g *GenericIterator) GetType() string { - if len(g.data) == 0 { - return "" - } - return g.dataType.Name() -} +// func (g *GenericIterator) GetType() string { +// if len(g.data) == 0 { +// return "" +// } +// return g.dataType.Name() +// } diff --git a/src/util/genericIterator_test.go b/src/util/genericIterator_test.go new file mode 100644 index 00000000..87b19401 --- /dev/null +++ b/src/util/genericIterator_test.go @@ -0,0 +1,115 @@ +package util + +import ( + "github.com/stretchr/testify/require" + "testing" +) + +type testInterface interface { + testParams() string +} + +type testStruct1 struct { + param1 string +} + +func (t testStruct1) testParams() string { + return t.param1 +} + +type testStruct2 struct { + param1 bool + param2 int +} + +func (t *testStruct2) testParams() string { + return "this is a test" +} + +func TestGenericIterator_CurrentData(t *testing.T) { + tests := []struct { + name string + test func(t *testing.T) + wantErr bool + }{ + {name: "int", test: func(t *testing.T) { + var list = []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 0} + it := NewGenericIterator(list) + require.True(t, it.HasNext()) + for it.Next() { + var i int + require.NoError(t, it.CurrentData(&i)) + require.Contains(t, list, i) + } + require.False(t, it.HasNext()) + }, wantErr: false}, + {name: "struct", test: func(t *testing.T) { + type Writer struct { + name string + Age int + } + var writers = []Writer{{ + name: "Mary Shelly", + Age: 25, + }, { + name: "Walter Scott", + Age: 49, + }, { + name: "John Milton", + Age: 59, + }, { + name: "Oscar Wilde", + Age: 36, + }, { + name: "Abraham Stoker", + Age: 50, + }} + it := NewGenericIterator(writers) + require.True(t, it.HasNext()) + for it.Next() { + var i Writer + require.NoError(t, it.CurrentData(&i)) + require.Contains(t, writers, i) + require.NotNil(t, i.name) + require.NotNil(t, i.Age) + } + require.False(t, it.HasNext()) + }, wantErr: false}, + {name: "implementing interfaces", test: func(t *testing.T) { + var list = []testInterface{ + testStruct1{param1: "a1"}, + &testStruct2{ + param1: true, + param2: 23, + }, &testStruct2{ + param1: false, + param2: 32, + }} + it := NewGenericIterator(list) + require.True(t, it.HasNext()) + + for it.Next() { + var i testInterface + require.NoError(t, it.CurrentData(&i)) + require.Contains(t, list, i) + } + require.False(t, it.HasNext()) + + }, wantErr: false}, + {name: "wrong", test: func(t *testing.T) { + var list = []string{"1", "2", "3", "4"} + it := NewGenericIterator(list) + require.True(t, it.HasNext()) + + for it.Next() { + var i int + require.Error(t, it.CurrentData(&i)) + } + require.False(t, it.HasNext()) + + }, wantErr: true}, + } + for _, tt := range tests { + t.Run(tt.name, tt.test) + } +} From 63752d97f35f47c1db0ceb2955afa5b05440a98a Mon Sep 17 00:00:00 2001 From: stdevHsequeda Date: Mon, 23 Dec 2019 22:04:19 -0500 Subject: [PATCH 6/6] [generic] refs 290 Comment Iterator interface in core package. --- src/core/generic.go | 1 + 1 file changed, 1 insertion(+) diff --git a/src/core/generic.go b/src/core/generic.go index 56577d4d..d2b4e8bf 100644 --- a/src/core/generic.go +++ b/src/core/generic.go @@ -1,5 +1,6 @@ package core +// Iterator defines a generic iterator. type Iterator interface { CurrentData(interface{}) error HasNext() bool