unit testing for account balances

This commit is contained in:
Dustin Brickwood 2018-08-01 15:17:38 -04:00
parent f066a8e461
commit d299d2baeb
3 changed files with 439 additions and 419 deletions

View file

@ -37,11 +37,36 @@ func InitDBTest() (*sql.DB, error){
} }
func DBConnection() (*sql.DB, error) { func DBConnection() (*sql.DB, error) {
if (blockExplorerDb == nil) { if blockExplorerDb == nil {
_, err := InitDB() _, err := InitDB()
if(err != nil) { if err != nil {
return nil, err return nil, err
} }
} }
return blockExplorerDb, nil return blockExplorerDb, nil
} }
func ClearTables() {
sqldb, err := DBConnection()
if err != nil {
panic(err)
}
sqlStatementTx:= `DELETE FROM txs`
_, err = sqldb.Exec(sqlStatementTx)
if err != nil {
panic(err)
}
sqlStatementAcc:= `DELETE FROM accounts`
_, err = sqldb.Exec(sqlStatementAcc)
if err != nil {
panic(err)
}
sqlStatement := `DELETE FROM blocks`
_, err = sqldb.Exec(sqlStatement)
if err != nil {
panic(err)
}
}

View file

@ -1,18 +1,19 @@
package core package core
import ( import (
"math/big"
"time"
"strconv"
"database/sql" "database/sql"
"log"
_ "github.com/lib/pq"
"github.com/ShyftNetwork/go-empyrean/common"
"github.com/ShyftNetwork/go-empyrean/core/types"
Rewards "github.com/ShyftNetwork/go-empyrean/consensus/ethash"
"github.com/ShyftNetwork/go-empyrean/shyfttracerinterface"
"strings"
"fmt" "fmt"
"log"
"math/big"
"strconv"
"strings"
"time"
"github.com/ShyftNetwork/go-empyrean/common"
Rewards "github.com/ShyftNetwork/go-empyrean/consensus/ethash"
"github.com/ShyftNetwork/go-empyrean/core/types"
"github.com/ShyftNetwork/go-empyrean/shyfttracerinterface"
_ "github.com/lib/pq"
) )
var IShyftTracer shyfttracerinterface.IShyftTracer var IShyftTracer shyfttracerinterface.IShyftTracer
@ -253,27 +254,35 @@ func swriteFromBalance(sqldb *sql.DB, tx *types.Transaction) error {
From: tx.From().Hex(), From: tx.From().Hex(),
Amount: tx.Value().String(), Amount: tx.Value().String(),
} }
value := tx.Value()
toAddressBalance, toAccountNonce, err := AccountExists(sqldb, sendAndReceiveData.To) _, _, err := AccountExists(sqldb, sendAndReceiveData.To)
switch { switch {
case err == sql.ErrNoRows: case err == sql.ErrNoRows:
accountNonce := strconv.FormatUint(tx.Nonce(), 10) accountNonce := strconv.FormatUint(tx.Nonce(), 10)
CreateAccount(sqldb, sendAndReceiveData.To, sendAndReceiveData.Amount, accountNonce) CreateAccount(sqldb, sendAndReceiveData.To, sendAndReceiveData.Amount, accountNonce)
balanceHelper(sqldb, sendAndReceiveData, value)
case err != nil: case err != nil:
log.Fatal(err) log.Fatal(err)
default: default:
fromAddressBalance, fromAccountNonce, err := AccountExists(sqldb, sendAndReceiveData.From) balanceHelper(sqldb, sendAndReceiveData, value)
}
return nil
}
func balanceHelper(sqldb *sql.DB, s SendAndReceive, value *big.Int) {
fromAddressBalance, fromAccountNonce, err := AccountExists(sqldb, s.From)
toAddressBalance, toAccountNonce, err := AccountExists(sqldb, s.To)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
var newBalanceReceiver, newBalanceSender, newAccountNonceReceiver, newAccountNonceSender big.Int var newBalanceReceiver, newBalanceSender, newAccountNonceReceiver, newAccountNonceSender big.Int
var nonceIncrement = big.NewInt(1) var nonceIncrement = big.NewInt(1)
fmt.Println(toAddressBalance)
//STRING TO BIG INT //STRING TO BIG INT
//BALANCES TO AND FROM ADDR //BALANCES TO AND FROM ADDR
toBalance := new(big.Int) toBalance := new(big.Int)
toBalance, _ = toBalance.SetString(toAddressBalance, 10) toBalance, _ = toBalance.SetString(toAddressBalance, 10)
fmt.Println(toBalance)
fromBalance := new(big.Int) fromBalance := new(big.Int)
fromBalance, _ = fromBalance.SetString(fromAddressBalance, 10) fromBalance, _ = fromBalance.SetString(fromAddressBalance, 10)
@ -283,19 +292,18 @@ func swriteFromBalance(sqldb *sql.DB, tx *types.Transaction) error {
fromNonce := new(big.Int) fromNonce := new(big.Int)
fromNonce, _ = fromNonce.SetString(fromAccountNonce, 10) fromNonce, _ = fromNonce.SetString(fromAccountNonce, 10)
newBalanceReceiver.Add(toBalance, tx.Value()) newBalanceReceiver.Add(toBalance, value)
newBalanceSender.Sub(fromBalance, tx.Value()) newBalanceSender.Sub(fromBalance, value)
newAccountNonceReceiver.Add(toNonce, nonceIncrement) newAccountNonceReceiver.Add(toNonce, nonceIncrement)
newAccountNonceSender.Add(fromNonce, nonceIncrement) newAccountNonceSender.Add(fromNonce, nonceIncrement)
//UPDATE ACCOUNTS BASED ON NEW BALANCES AND ACCOUNT NONCES //UPDATE ACCOUNTS BASED ON NEW BALANCES AND ACCOUNT NONCES
UpdateAccount(sqldb, sendAndReceiveData.To, newBalanceReceiver.String(), newAccountNonceReceiver.String()) UpdateAccount(sqldb, s.To, newBalanceReceiver.String(), newAccountNonceReceiver.String())
UpdateAccount(sqldb, sendAndReceiveData.From, newBalanceSender.String(), newAccountNonceSender.String()) UpdateAccount(sqldb, s.From, newBalanceSender.String(), newAccountNonceSender.String())
}
return nil
} }
//SWriteInternalTxBalances Writes internal txs and updates balances
func SWriteInternalTxBalances(sqldb *sql.DB, toAddr string, fromAddr string, amount string) error { func SWriteInternalTxBalances(sqldb *sql.DB, toAddr string, fromAddr string, amount string) error {
sendAndReceiveData := SendAndReceive{ sendAndReceiveData := SendAndReceive{
To: toAddr, To: toAddr,
@ -457,7 +465,7 @@ func AccountExists (sqldb *sql.DB, addr string) (string, string, error) {
} }
} }
func BlockExists (sqldb *sql.DB, hash string) (error) { func BlockExists(sqldb *sql.DB, hash string) error {
var res string var res string
sqlExistsStatement := `SELECT hash from blocks WHERE hash= ($1)` sqlExistsStatement := `SELECT hash from blocks WHERE hash= ($1)`
err := sqldb.QueryRow(sqlExistsStatement, strings.ToLower(hash)).Scan(&res) err := sqldb.QueryRow(sqlExistsStatement, strings.ToLower(hash)).Scan(&res)
@ -504,5 +512,3 @@ func InsertInternalTx(sqldb *sql.DB, i InteralWrite) {
panic(qerr) panic(qerr)
} }
} }

View file

@ -1,17 +1,19 @@
package shyftdb package shyftdb
import ( import (
"encoding/json"
"fmt"
"math/big"
"strconv"
"strings"
"testing" "testing"
"github.com/ShyftNetwork/go-empyrean/common" "github.com/ShyftNetwork/go-empyrean/common"
"github.com/ShyftNetwork/go-empyrean/consensus/ethash"
"github.com/ShyftNetwork/go-empyrean/core" "github.com/ShyftNetwork/go-empyrean/core"
"github.com/ShyftNetwork/go-empyrean/core/types" "github.com/ShyftNetwork/go-empyrean/core/types"
"github.com/ShyftNetwork/go-empyrean/eth"
"math/big"
//"time"
"encoding/json"
"github.com/ShyftNetwork/go-empyrean/crypto" "github.com/ShyftNetwork/go-empyrean/crypto"
"github.com/ShyftNetwork/go-empyrean/consensus/ethash" "github.com/ShyftNetwork/go-empyrean/eth"
"strconv"
) )
type ShyftTracer struct{} type ShyftTracer struct{}
@ -23,8 +25,8 @@ const (
func TestBlock(t *testing.T) { func TestBlock(t *testing.T) {
eth.NewShyftTestLDB() eth.NewShyftTestLDB()
core.InitDBTest() core.InitDBTest()
shyft_tracer := new(eth.ShyftTracer) shyftTracer := new(eth.ShyftTracer)
core.SetIShyftTracer(shyft_tracer) core.SetIShyftTracer(shyftTracer)
ethConf := &eth.Config{ ethConf := &eth.Config{
Genesis: core.DeveloperGenesisBlock(15, common.Address{}), Genesis: core.DeveloperGenesisBlock(15, common.Address{}),
@ -37,6 +39,7 @@ func TestBlock(t *testing.T) {
eth.SetGlobalConfig(ethConf) eth.SetGlobalConfig(ethConf)
eth.InitTracerEnv() eth.InitTracerEnv()
core.ClearTables()
t.Run("TestBlockToReturnBlock", func(t *testing.T) { t.Run("TestBlockToReturnBlock", func(t *testing.T) {
key, _ := crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") key, _ := crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
@ -123,8 +126,8 @@ func TestBlock(t *testing.T) {
if getAllBlocksMinedByAddress := core.SGetAllBlocksMinedByAddress(sqldb, block.Coinbase().String()); len(getAllBlocksMinedByAddress) == 0 { if getAllBlocksMinedByAddress := core.SGetAllBlocksMinedByAddress(sqldb, block.Coinbase().String()); len(getAllBlocksMinedByAddress) == 0 {
t.Fatalf("GetAllBlocksMinedByAddress [%v]: GetAllBlocksMinedByAddress did not return correctly", getAllBlocksMinedByAddress) t.Fatalf("GetAllBlocksMinedByAddress [%v]: GetAllBlocksMinedByAddress did not return correctly", getAllBlocksMinedByAddress)
} }
fmt.Println("passed")
ClearTables() core.ClearTables()
}) })
t.Run("TestGetRecentBlock", func(t *testing.T) { t.Run("TestGetRecentBlock", func(t *testing.T) {
@ -166,7 +169,7 @@ func TestBlock(t *testing.T) {
} }
sqldb, err := core.DBConnection() sqldb, err := core.DBConnection()
if (err != nil) { if err != nil {
panic(err) panic(err)
} }
@ -212,10 +215,10 @@ func TestBlock(t *testing.T) {
if allTxsFromBlock := core.SGetAllTransactionsFromBlock(sqldb, block2.Number().String()); len(allTxsFromBlock) == 0 { if allTxsFromBlock := core.SGetAllTransactionsFromBlock(sqldb, block2.Number().String()); len(allTxsFromBlock) == 0 {
t.Fatalf("GetAllTransactionsFromBlock [%v]: GetAllTransactionsFromBlock did not return correctly", allTxsFromBlock) t.Fatalf("GetAllTransactionsFromBlock [%v]: GetAllTransactionsFromBlock did not return correctly", allTxsFromBlock)
} }
ClearTables() fmt.Println("Passed 2")
core.ClearTables()
}) })
//
t.Run("TestContractCreationTx", func(t *testing.T) { t.Run("TestContractCreationTx", func(t *testing.T) {
key, _ := crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") key, _ := crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
signer := types.NewEIP155Signer(big.NewInt(2147483647)) signer := types.NewEIP155Signer(big.NewInt(2147483647))
@ -250,7 +253,7 @@ t.Run("TestContractCreationTx", func (t *testing.T) {
} }
sqldb, err := core.DBConnection() sqldb, err := core.DBConnection()
if (err != nil) { if err != nil {
panic(err) panic(err)
} }
@ -266,7 +269,7 @@ t.Run("TestContractCreationTx", func (t *testing.T) {
if contractAddressFromReciept != data.ToGet { if contractAddressFromReciept != data.ToGet {
t.Fatalf("Contract Addr [%v]: Contract addr not found", contractAddressFromReciept) t.Fatalf("Contract Addr [%v]: Contract addr not found", contractAddressFromReciept)
} }
if tx.From().String() != data.From { if strings.ToLower(tx.From().String()) != data.From {
t.Fatalf("From Addr [%v]: From addr not found", tx.From().String()) t.Fatalf("From Addr [%v]: From addr not found", tx.From().String())
} }
if tx.Nonce() != data.Nonce { if tx.Nonce() != data.Nonce {
@ -313,9 +316,10 @@ t.Run("TestContractCreationTx", func (t *testing.T) {
t.Fatalf("isContract [%v]: isContract bool is incorrect", isContract) t.Fatalf("isContract [%v]: isContract bool is incorrect", isContract)
} }
} }
ClearTables() fmt.Println("Passed 3")
core.ClearTables()
}) })
//
t.Run("TestTransactionsToReturnTransactions", func(t *testing.T) { t.Run("TestTransactionsToReturnTransactions", func(t *testing.T) {
key, _ := crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") key, _ := crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
signer := types.NewEIP155Signer(big.NewInt(2147483647)) signer := types.NewEIP155Signer(big.NewInt(2147483647))
@ -348,7 +352,7 @@ t.Run("TestTransactionsToReturnTransactions", func(t *testing.T) {
t.Fatalf("Failed to write block into database: %v", err) t.Fatalf("Failed to write block into database: %v", err)
} }
sqldb, err := core.DBConnection() sqldb, err := core.DBConnection()
if (err != nil) { if err != nil {
panic(err) panic(err)
} }
@ -359,13 +363,13 @@ t.Run("TestTransactionsToReturnTransactions", func(t *testing.T) {
json.Unmarshal(byt, &data) json.Unmarshal(byt, &data)
//TODO age, data //TODO age, data
if tx.Hash().String() != data.TxHash { if strings.ToLower(tx.Hash().String()) != data.TxHash {
t.Fatalf("txHash [%v]: tx Hash not found", tx.Hash().String()) t.Fatalf("txHash [%v]: tx Hash not found", tx.Hash().String())
} }
if tx.From().String() != data.From { if strings.ToLower(tx.From().String()) != data.From {
t.Fatalf("From Addr [%v]: From addr not found", tx.From().String()) t.Fatalf("From Addr [%v]: From addr not found", tx.From().String())
} }
if tx.To().String() != data.ToGet { if strings.ToLower(tx.To().String()) != data.ToGet {
t.Fatalf("To Addr [%v]: To addr not found", tx.To().String()) t.Fatalf("To Addr [%v]: To addr not found", tx.To().String())
} }
if tx.Nonce() != data.Nonce { if tx.Nonce() != data.Nonce {
@ -416,36 +420,29 @@ t.Run("TestTransactionsToReturnTransactions", func(t *testing.T) {
if getAllTx := core.SGetAllTransactions(sqldb); len(getAllTx) == 0 { if getAllTx := core.SGetAllTransactions(sqldb); len(getAllTx) == 0 {
t.Fatalf("GetAllTransactions [%v]: GetAllTransactions did not return correctly", getAllTx) t.Fatalf("GetAllTransactions [%v]: GetAllTransactions did not return correctly", getAllTx)
} }
ClearTables() fmt.Println("Passed 4")
core.ClearTables()
}) })
//
t.Run("TestAccountsToReturnAccounts", func(t *testing.T) { t.Run("TestAccountsToReturnAccounts", func(t *testing.T) {
key, _ := crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") key, _ := crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
signer := types.NewEIP155Signer(big.NewInt(2147483647)) signer := types.NewEIP155Signer(big.NewInt(2147483647))
toAddr1 := common.BytesToAddress([]byte{0x11})
toAddr2 := common.BytesToAddress([]byte{0x22})
toAddr3 := common.BytesToAddress([]byte{0x33})
toAmount1 := big.NewInt(111)
var toAmountPrev1 string = "3968686868"
sqldb, err := core.DBConnection() sqldb, err := core.DBConnection()
if (err != nil) { if err != nil {
panic(err) panic(err)
} }
core.CreateAccount(sqldb, toAddr1.Hex(), toAmountPrev1, "1") fromAddr := "0x71562b71999873db5b286df957af199ec94617f7"
core.CreateAccount(sqldb, toAddr2.Hex(), "423798729847", "1") core.CreateAccount(sqldb, fromAddr, "50", "1")
core.CreateAccount(sqldb, toAddr3.Hex(), "0", "1") toAddr := common.BytesToAddress([]byte{0x11})
core.CreateAccount(sqldb, "0x71562b71999873DB5b286dF957af199Ec94617F7", "3968686868", "1")
//Nonce, To Address,Value, GasLimit, Gasprice, data //Nonce, To Address,Value, GasLimit, Gasprice, data
tx1 := types.NewTransaction(1, toAddr1, toAmount1, 1111, big.NewInt(11111), []byte{0x11, 0x11, 0x11}) tx1 := types.NewTransaction(1, common.BytesToAddress([]byte{0x11}), big.NewInt(5), 1111, big.NewInt(11111), []byte{0x11, 0x11, 0x11})
mytx, _ := types.SignTx(tx1, signer, key) mytx, _ := types.SignTx(tx1, signer, key)
tx2 := types.NewTransaction(2, toAddr2, big.NewInt(222), 2222, big.NewInt(22222), []byte{0x22, 0x22, 0x22}) tx2 := types.NewTransaction(2, common.BytesToAddress([]byte{0x22}), big.NewInt(5), 2222, big.NewInt(22222), []byte{0x22, 0x22, 0x22})
mytx2, _ := types.SignTx(tx2, signer, key) mytx2, _ := types.SignTx(tx2, signer, key)
tx3 := types.NewTransaction(3, toAddr3, big.NewInt(333), 3333, big.NewInt(33333), []byte{0x33, 0x33, 0x33}) tx3 := types.NewTransaction(3, common.BytesToAddress([]byte{0x33}), big.NewInt(5), 3333, big.NewInt(33333), []byte{0x33, 0x33, 0x33})
mytx3, _ := types.SignTx(tx3, signer, key) mytx3, _ := types.SignTx(tx3, signer, key)
txs := []*types.Transaction{mytx, mytx2, mytx3} txs := []*types.Transaction{mytx, mytx2, mytx3}
@ -462,54 +459,46 @@ t.Run("TestAccountsToReturnAccounts",func(t *testing.T) {
} }
receipts := []*types.Receipt{receipt1} receipts := []*types.Receipt{receipt1}
block := types.NewBlock(&types.Header{Number: big.NewInt(315)}, txs, nil, receipts) block := types.NewBlock(&types.Header{Number: big.NewInt(319)}, txs, nil, receipts)
if err := core.SWriteBlock(block, receipts); err != nil { if err := core.SWriteBlock(block, receipts); err != nil {
t.Fatalf("Failed to write block into database: %v", err) t.Fatalf("Failed to write block into database: %v", err)
} }
if toAddr1.String() != tx1.To().String() { for _, tx := range txs {
t.Fatalf("To address [%v]: To address not found", toAddr1.String()) accountAddrTo := core.SGetAccount(sqldb, tx.To().String())
byts := []byte(accountAddrTo)
var accountDataTo core.SAccounts
json.Unmarshal(byts, &accountDataTo)
if strings.ToLower(tx.To().String()) != accountDataTo.Addr {
t.Fatalf("To address [%v]: To address not found", accountDataTo.Addr)
} }
accountAddrTo, _ := core.InnerSGetAccount(sqldb, toAddr1.String()) if tx.Value().String() != accountDataTo.Balance {
//ewAccountNonceReceiver.Add(accountR, nonceIncrement) t.Fatalf("To address balance [%v]: To address balance not found", accountDataTo.Balance)
addedAmount := new(big.Int)
toAmountPrevious1, _ := strconv.ParseUint(toAmountPrev1, 10, 64)
b := new(big.Int).SetUint64(toAmountPrevious1)
addedAmount.Add(toAmount1, b)
toBalance := new(big.Int)
toBalance, _ = toBalance.SetString(accountAddrTo.Balance, 10)
if toBalance.Cmp(addedAmount) != 0 {
t.Fatalf("To address balance [%v]: To address balance not correct FFO", toBalance)
} }
if strconv.FormatUint(tx.Nonce(), 10) != accountDataTo.AccountNonce {
t.Fatalf("To account nonce [%v]: To account nonce not found", accountDataTo.AccountNonce)
}
}
accountAddrFrom := core.SGetAccount(sqldb, fromAddr)
byts := []byte(accountAddrFrom)
var accountDataFrom core.SAccounts
json.Unmarshal(byts, &accountDataFrom)
//for _, tx := range txs { fmt.Println("FROM", accountDataFrom)
// accountAddrTo := core.SGetAccount(sqldb, tx.To().String())
// byts := []byte(accountAddrTo)
// var accountDataTo core.SAccounts
// json.Unmarshal(byts, &accountDataTo)
//
// if tx.To().String() != accountDataTo.Addr {
// t.Fatalf("To address [%v]: To address not found", accountDataTo.Addr)
// }
// if tx.Value().String() != accountDataTo.Balance {
// t.Fatalf("To address balance [%v]: To address balance not found", accountDataTo.Balance)
// }
// if strconv.FormatUint(tx.Nonce(), 10) != accountDataTo.AccountNonce {
// t.Fatalf("To account nonce [%v]: To account nonce not found", accountDataTo.AccountNonce)
// }
//}
if getAllAccountTxs := core.SGetAccountTxs(sqldb, toAddr1.String()); len(getAllAccountTxs) == 0 { if getAllAccountTxs := core.SGetAccountTxs(sqldb, toAddr.String()); len(getAllAccountTxs) == 0 {
t.Fatalf("GetAccountTxs [%v]: GetAccountTxs did not return correctly", getAllAccountTxs) t.Fatalf("GetAccountTxs [%v]: GetAccountTxs did not return correctly", getAllAccountTxs)
} }
if getAllAccounts := core.SGetAllAccounts(sqldb); len(getAllAccounts) == 0 { if getAllAccounts := core.SGetAllAccounts(sqldb); len(getAllAccounts) == 0 {
t.Fatalf("GetAllAccounts [%v]: GetAllAccounts did not return correctly", getAllAccounts) t.Fatalf("GetAllAccounts [%v]: GetAllAccounts did not return correctly", getAllAccounts)
} }
ClearTables()
fmt.Println("Passed 5")
core.ClearTables()
}) })
ClearTables() core.ClearTables()
} }