refactored code to minimize lines

This commit is contained in:
Dustin Brickwood 2018-07-24 17:30:28 -04:00
parent 8a8c886ef1
commit 43dbd77049
4 changed files with 194 additions and 183 deletions

View file

@ -1,7 +1,6 @@
package core package core
import ( import (
"encoding/json"
"math/big" "math/big"
"time" "time"
"strconv" "strconv"
@ -24,7 +23,8 @@ func SetIShyftTracer(st shyfttracerinterface.IShyftTracer) {
type SBlock struct { type SBlock struct {
Hash string Hash string
Coinbase string Coinbase string
Age string AgeGet string
Age time.Time
ParentHash string ParentHash string
UncleHash string UncleHash string
Difficulty string Difficulty string
@ -65,7 +65,8 @@ type txRes struct {
type ShyftTxEntryPretty struct { type ShyftTxEntryPretty struct {
TxHash string TxHash string
To string To *common.Address
ToGet string
From string From string
BlockHash string BlockHash string
BlockNumber string BlockNumber string
@ -112,6 +113,7 @@ func SWriteBlock(block *types.Block, receipts []*types.Receipt) error {
Difficulty: block.Difficulty().String(), Difficulty: block.Difficulty().String(),
Size: block.Size().String(), Size: block.Size().String(),
Nonce: block.Nonce(), Nonce: block.Nonce(),
Rewards: rewards,
} }
i, err := strconv.ParseInt(block.Time().String(), 10, 64) i, err := strconv.ParseInt(block.Time().String(), 10, 64)
@ -120,12 +122,13 @@ func SWriteBlock(block *types.Block, receipts []*types.Receipt) error {
} }
age := time.Unix(i, 0) age := time.Unix(i, 0)
sqlStatement := `INSERT INTO blocks(hash, coinbase, number, gasUsed, gasLimit, txCount, uncleCount, age, parentHash, uncleHash, difficulty, size, rewards, nonce) VALUES(($1), ($2), ($3), ($4), ($5), ($6), ($7), ($8), ($9), ($10), ($11), ($12),($13), ($14)) RETURNING number` blockAge := SBlock {
qerr := sqldb.QueryRow(sqlStatement, blockData.Hash, blockData.Coinbase, blockData.Number, blockData.GasUsed, blockData.GasLimit, blockData.TxCount, blockData.UncleCount, age, blockData.ParentHash, blockData.UncleHash, blockData.Difficulty, blockData.Size, rewards, blockData.Nonce).Scan(&blockData.Number) Age: age,
if qerr != nil {
panic(qerr)
} }
//Inserts block data into DB
InsertBlock(sqldb, blockData, blockAge)
if block.Transactions().Len() > 0 { if block.Transactions().Len() > 0 {
for _, tx := range block.Transactions() { for _, tx := range block.Transactions() {
swriteTransactions(sqldb, tx, block.Header().Hash(), blockData.Number, receipts, age, blockData.GasLimit) swriteTransactions(sqldb, tx, block.Header().Hash(), blockData.Number, receipts, age, blockData.GasLimit)
@ -143,25 +146,29 @@ func SWriteBlock(block *types.Block, receipts []*types.Receipt) error {
//swriteTransactions writes to sqldb, a SHYFT postgres instance //swriteTransactions writes to sqldb, a SHYFT postgres instance
func swriteTransactions(sqldb *sql.DB, tx *types.Transaction, blockHash common.Hash, blockNumber string, receipts []*types.Receipt, age time.Time, gasLimit uint64) error { func swriteTransactions(sqldb *sql.DB, tx *types.Transaction, blockHash common.Hash, blockNumber string, receipts []*types.Receipt, age time.Time, gasLimit uint64) error {
var isContract bool var isContract bool
var statusFromReciept, contractAddressFromReciept, retNonce string var statusFromReciept string
var contractAddressFromReciept common.Address
txData := ShyftTxEntryPretty{ txData := ShyftTxEntryPretty{
TxHash: tx.Hash().Hex(), TxHash: tx.Hash().Hex(),
From: tx.From().Hex(), From: tx.From().Hex(),
To: tx.To().Hex(), To: tx.To(),
BlockHash: blockHash.Hex(), BlockHash: blockHash.Hex(),
BlockNumber: blockNumber,
Amount: tx.Value().String(), Amount: tx.Value().String(),
Cost: tx.Cost().Uint64(), Cost: tx.Cost().Uint64(),
GasPrice: tx.GasPrice().Uint64(), GasPrice: tx.GasPrice().Uint64(),
GasLimit: gasLimit,
Gas: tx.Gas(), Gas: tx.Gas(),
Nonce: tx.Nonce(), Nonce: tx.Nonce(),
Age: age,
Data: tx.Data(), Data: tx.Data(),
} }
if tx.To() == nil { if tx.To() == nil {
for _, receipt := range receipts { for _, receipt := range receipts {
statusReciept := (*types.ReceiptForStorage)(receipt).Status statusReciept := (*types.ReceiptForStorage)(receipt).Status
contractAddressFromReciept = (*types.ReceiptForStorage)(receipt).ContractAddress.String() contractAddressFromReciept = (*types.ReceiptForStorage)(receipt).ContractAddress
switch { switch {
case statusReciept == 0: case statusReciept == 0:
statusFromReciept = "FAIL" statusFromReciept = "FAIL"
@ -170,11 +177,13 @@ func swriteTransactions(sqldb *sql.DB, tx *types.Transaction, blockHash common.H
} }
} }
isContract = true isContract = true
sqlStatement := `INSERT INTO txs(txhash, from_addr, to_addr, blockhash, blockNumber, amount, gasprice, gas, gasLimit, txfee, nonce, isContract, txStatus, age, data) VALUES(($1), ($2), ($3), ($4), ($5), ($6), ($7), ($8), ($9), ($10), ($11), ($12), ($13), ($14), ($15)) RETURNING nonce` contractData := ShyftTxEntryPretty{
err := sqldb.QueryRow(sqlStatement, txData.TxHash, txData.From, contractAddressFromReciept, txData.BlockHash, blockNumber, txData.Amount, txData.GasPrice, txData.Gas, gasLimit, txData.Cost, txData.Nonce, isContract, statusFromReciept, age, txData.Data).Scan(&retNonce) Status: statusFromReciept,
if err != nil { IsContract: isContract,
panic(err) To: &contractAddressFromReciept,
} }
//Insert Tx into DB
InsertTx(sqldb, txData, contractData)
} else { } else {
isContract = false isContract = false
for _, receipt := range receipts { for _, receipt := range receipts {
@ -186,11 +195,13 @@ func swriteTransactions(sqldb *sql.DB, tx *types.Transaction, blockHash common.H
statusFromReciept = "SUCCESS" statusFromReciept = "SUCCESS"
} }
} }
sqlStatement := `INSERT INTO txs(txhash, from_addr, to_addr, blockhash, blockNumber, amount, gasprice, gas, gasLimit, txfee, nonce, isContract, txStatus, age, data) VALUES(($1), ($2), ($3), ($4), ($5), ($6), ($7), ($8), ($9), ($10), ($11), ($12), ($13), ($14), ($15)) RETURNING nonce` data := ShyftTxEntryPretty{
err := sqldb.QueryRow(sqlStatement, txData.TxHash, txData.From, txData.To, txData.BlockHash, blockNumber, txData.Amount, txData.GasPrice, txData.Gas, gasLimit, txData.Cost, txData.Nonce, isContract, statusFromReciept, age, txData.Data).Scan(&retNonce) Status: statusFromReciept,
if err != nil { IsContract: isContract,
panic(err) To: tx.To(),
} }
//Insert Tx into DB
InsertTx(sqldb, txData, data)
} }
//Runs necessary functions for tracing internal transactions through tracers.go //Runs necessary functions for tracing internal transactions through tracers.go
IShyftTracer.GetTracerToRun(tx.Hash()) IShyftTracer.GetTracerToRun(tx.Hash())
@ -205,117 +216,78 @@ func swriteContractBalance(sqldb *sql.DB, tx *types.Transaction) error {
AccountNonce: tx.Nonce(), AccountNonce: tx.Nonce(),
} }
var response string fromAddressBalance, fromAccountNonce, err := AccountExists(sqldb, sendAndReceiveData.From)
sqlExistsStatement := `SELECT balance from accounts WHERE addr = ($1)`
err := sqldb.QueryRow(sqlExistsStatement, sendAndReceiveData.From).Scan(&response)
switch { switch {
case err == sql.ErrNoRows: case err == sql.ErrNoRows:
sqlStatement := `INSERT INTO accounts(addr, balance, accountNonce) VALUES(($1), ($2), ($3)) RETURNING addr` accountNonce := strconv.FormatUint(tx.Nonce(), 10)
insertErr := sqldb.QueryRow(sqlStatement, sendAndReceiveData.From, sendAndReceiveData.Amount, sendAndReceiveData.AccountNonce).Scan(&sendAndReceiveData.From) CreateAccount(sqldb, sendAndReceiveData.From, sendAndReceiveData.Amount, accountNonce)
if insertErr != nil {
panic(insertErr)
}
default: default:
getAccountBalanceSender:= SGetAccount(sqldb, sendAndReceiveData.From)
var newBalanceSender,newAccountNonceSender big.Int var newBalanceSender,newAccountNonceSender big.Int
var nonceIncrement = big.NewInt(1) var nonceIncrement = big.NewInt(1)
var senderBalance SendAndReceive fromBalance := new(big.Int)
if err := json.Unmarshal([]byte(getAccountBalanceSender), &senderBalance); err != nil { fromBalance, _ = fromBalance.SetString(fromAddressBalance, 10)
log.Fatal(err)
}
//Converts string to UINT64 > Big.Int for adding and subtraction fromNonce := new(big.Int)
balanceSender, _ := strconv.ParseUint(senderBalance.Balance, 10, 64) fromNonce, _ = fromNonce.SetString(fromAccountNonce, 10)
balanceSen := new(big.Int).SetUint64(balanceSender)
senderAccountNonce := new(big.Int).SetUint64(sendAndReceiveData.AccountNonce)
newBalanceSender.Sub(balanceSen, tx.Value()) newBalanceSender.Sub(fromBalance, tx.Value())
newAccountNonceSender.Add(senderAccountNonce, nonceIncrement) newAccountNonceSender.Add(fromNonce, nonceIncrement)
updateSQLStatement := `UPDATE accounts SET balance = ($2), accountNonce = ($3) WHERE addr = ($1)` UpdateAccount(sqldb, sendAndReceiveData.From, newBalanceSender.String(), newAccountNonceSender.String())
_, err := sqldb.Exec(updateSQLStatement, sendAndReceiveData.From, newBalanceSender.String(), newAccountNonceSender.String())
if err != nil {
panic(err)
}
} }
return nil return nil
} }
//writeFromBalance writes senders balance to accounts db //writeFromBalance writes senders balance to accounts db
func swriteFromBalance(sqldb *sql.DB, tx *types.Transaction) error { func swriteFromBalance(sqldb *sql.DB, tx *types.Transaction) error {
sendAndReceiveData, balanceRec, balanceSen, accountNonceRec, accountNonceSen := swriteBalanceHelper(sqldb, tx)
var response string
sqlExistsStatement := `SELECT balance from accounts WHERE addr = ($1)`
err := sqldb.QueryRow(sqlExistsStatement, sendAndReceiveData.To).Scan(&response)
switch {
case err == sql.ErrNoRows:
accountNonce := strconv.FormatUint(tx.Nonce(), 10)
sqlStatement := `INSERT INTO accounts(addr, balance, accountNonce) VALUES(($1), ($2), ($3)) RETURNING addr`
insertErr := sqldb.QueryRow(sqlStatement, sendAndReceiveData.To, sendAndReceiveData.Amount, accountNonce).Scan(&sendAndReceiveData.To)
if insertErr != nil {
panic(insertErr)
}
case err != nil:
log.Fatal(err)
default:
var newBalanceReceiver, newBalanceSender, newAccountNonceReceiver, newAccountNonceSender big.Int
var nonceIncrement = big.NewInt(1)
//Convert UINT64 to BIG.INT in order to add and subtract nonces & balances
balanceR := new(big.Int).SetUint64(balanceRec)
balanceS := new(big.Int).SetUint64(balanceSen)
accountR := new(big.Int).SetUint64(accountNonceRec)
accountS := new(big.Int).SetUint64(accountNonceSen)
newBalanceReceiver.Add(balanceR, tx.Value())
newBalanceSender.Sub(balanceS, tx.Value())
newAccountNonceReceiver.Add(accountR, nonceIncrement)
newAccountNonceSender.Add(accountS, nonceIncrement)
updateSQLStatement := `UPDATE accounts SET balance = ($2), accountNonce = ($3) WHERE addr = ($1)`
_, err = sqldb.Exec(updateSQLStatement, sendAndReceiveData.To, newBalanceReceiver.String(), newAccountNonceReceiver.String())
if err != nil {
panic(err)
}
_, err = sqldb.Exec(updateSQLStatement, sendAndReceiveData.From, newBalanceSender.String(), newAccountNonceSender.String())
if err != nil {
panic(err)
}
}
return nil
}
func swriteBalanceHelper(sqldb *sql.DB, tx *types.Transaction) (SendAndReceive, uint64, uint64, uint64, uint64) {
sendAndReceiveData := SendAndReceive{ sendAndReceiveData := SendAndReceive{
To: tx.To().Hex(), To: tx.To().Hex(),
From: tx.From().Hex(), From: tx.From().Hex(),
Amount: tx.Value().String(), Amount: tx.Value().String(),
} }
getAccountBalanceReceiver := SGetAccount(sqldb, sendAndReceiveData.To) toAddressBalance, toAccountNonce, err := AccountExists(sqldb, sendAndReceiveData.To)
getAccountBalanceSender:= SGetAccount(sqldb, sendAndReceiveData.From)
var receiverData SendAndReceive switch {
if err := json.Unmarshal([]byte(getAccountBalanceReceiver), &receiverData); err != nil { case err == sql.ErrNoRows:
accountNonce := strconv.FormatUint(tx.Nonce(), 10)
CreateAccount(sqldb, sendAndReceiveData.To, sendAndReceiveData.Amount, accountNonce)
case err != nil:
log.Fatal(err)
default:
fromAddressBalance, fromAccountNonce, err := AccountExists(sqldb, sendAndReceiveData.From)
if err != nil {
log.Fatal(err) log.Fatal(err)
} }
var newBalanceReceiver, newBalanceSender, newAccountNonceReceiver, newAccountNonceSender big.Int
var nonceIncrement = big.NewInt(1)
var senderData SendAndReceive //STRING TO BIG INT
if err := json.Unmarshal([]byte(getAccountBalanceSender), &senderData); err != nil { //BALANCES TO AND FROM ADDR
log.Fatal(err) toBalance := new(big.Int)
toBalance, _ = toBalance.SetString(toAddressBalance, 10)
fromBalance := new(big.Int)
fromBalance, _ = fromBalance.SetString(fromAddressBalance, 10)
//ACCOUNT NONCES
toNonce := new(big.Int)
toNonce, _ = toNonce.SetString(toAccountNonce, 10)
fromNonce := new(big.Int)
fromNonce, _ = fromNonce.SetString(fromAccountNonce, 10)
newBalanceReceiver.Add(toBalance, tx.Value())
newBalanceSender.Sub(fromBalance, tx.Value())
newAccountNonceReceiver.Add(toNonce, nonceIncrement)
newAccountNonceSender.Add(fromNonce, nonceIncrement)
//UPDATE ACCOUNTS BASED ON NEW BALANCES AND ACCOUNT NONCES
UpdateAccount(sqldb, sendAndReceiveData.To, newBalanceReceiver.String(), newAccountNonceReceiver.String())
UpdateAccount(sqldb, sendAndReceiveData.From, newBalanceSender.String(), newAccountNonceSender.String())
} }
return nil
balanceReceiver, _ := strconv.ParseUint(receiverData.Balance, 10, 64)
balanceSender, _ := strconv.ParseUint(senderData.Balance, 10, 64)
return sendAndReceiveData, balanceReceiver, balanceSender, receiverData.AccountNonce, senderData.AccountNonce
} }
// @NOTE: This function is extremely complex and requires heavy testing and knowdlege of edge cases: // @NOTE: This function is extremely complex and requires heavy testing and knowdlege of edge cases:
@ -369,19 +341,12 @@ func swriteMinerRewards(sqldb *sql.DB, block *types.Block) string {
func sstoreReward(sqldb *sql.DB, address string, reward *big.Int) { func sstoreReward(sqldb *sql.DB, address string, reward *big.Int) {
// Check if address exists // Check if address exists
var addressBalance string addressBalance, accountNonce, err := AccountExists(sqldb, address)
addressExistsStatement := `SELECT balance from accounts WHERE addr = ($1)`
err := sqldb.QueryRow(addressExistsStatement, address).Scan(&addressBalance)
if err == sql.ErrNoRows { if err == sql.ErrNoRows {
// Addr does not exist, thus create new entry // Addr does not exist, thus create new entry
createAddressSqlStatement := `INSERT INTO accounts(addr, balance, accountNonce) VALUES(($1), ($2), ($3)) RETURNING addr`
// We convert totalReward into a string and postgres converts into number // We convert totalReward into a string and postgres converts into number
_, insertErr := sqldb.Exec(createAddressSqlStatement, address, reward.String(), 1) CreateAccount(sqldb, address, reward.String(), "1")
if insertErr != nil {
panic(insertErr)
}
return return
} else if err != nil { } else if err != nil {
// Something went wrong panic // Something went wrong panic
@ -389,34 +354,77 @@ func sstoreReward(sqldb *sql.DB, address string, reward *big.Int) {
} else { } else {
// Addr exists, update existing balance // Addr exists, update existing balance
bigBalance := new(big.Int) bigBalance := new(big.Int)
bigBalance, err := bigBalance.SetString(addressBalance, 0) var nonceIncrement = big.NewInt(1)
currentAccountNonce := new(big.Int)
currentAccountNonce, errorr := currentAccountNonce.SetString(accountNonce, 10)
if !errorr {
panic(errorr)
}
bigBalance, err := bigBalance.SetString(addressBalance, 10)
if !err { if !err {
panic(err) panic(err)
} }
newBalance := new(big.Int) newBalance := new(big.Int)
newAccountNonce := new(big.Int)
newBalance.Add(newBalance, bigBalance) newBalance.Add(newBalance, bigBalance)
newBalance.Add(newBalance, reward) newBalance.Add(newBalance, reward)
newAccountNonce.Add(currentAccountNonce, nonceIncrement)
updateAddressSQLStatement := `UPDATE accounts SET balance = ($1) WHERE addr = ($2)` //Update the balance and nonce
UpdateAccount(sqldb, address, newBalance.String(), newAccountNonce.String())
// We convert totalReward into a string and postgres converts into number
_, updateErr := sqldb.Exec(updateAddressSQLStatement, newBalance.String(), address)
if updateErr != nil {
panic(updateErr)
}
return return
} }
} }
///////////////////////
func CreateAccount (sqldb *sql.DB, addr string, amount uint64, accountNonce uint64) { //DB Utility functions
//////////////////////
func CreateAccount (sqldb *sql.DB, addr string, balance string, accountNonce string) {
sqlStatement := `INSERT INTO accounts(addr, balance, accountNonce) VALUES(($1), ($2), ($3)) RETURNING addr` sqlStatement := `INSERT INTO accounts(addr, balance, accountNonce) VALUES(($1), ($2), ($3)) RETURNING addr`
insertErr := sqldb.QueryRow(sqlStatement, addr, amount, accountNonce).Scan(&addr) insertErr := sqldb.QueryRow(sqlStatement, addr, balance, accountNonce).Scan(&addr)
if insertErr != nil { if insertErr != nil {
panic(insertErr) panic(insertErr)
} }
}
func AccountExists (sqldb *sql.DB, addr string) (string, string, error) {
var addressBalance, accountNonce string
sqlExistsStatement := `SELECT balance, accountNonce from accounts WHERE addr = ($1)`
err := sqldb.QueryRow(sqlExistsStatement, addr).Scan(&addressBalance, &accountNonce)
switch {
case err == sql.ErrNoRows:
return addressBalance, accountNonce, err
case err != nil:
panic(err)
default:
return addressBalance, accountNonce, err
}
}
func UpdateAccount(sqldb *sql.DB, addr string, balance string, accountNonce string) {
updateSQLStatement := `UPDATE accounts SET balance = ($2), accountNonce = ($3) WHERE addr = ($1)`
_, updateErr := sqldb.Exec(updateSQLStatement, addr, balance, accountNonce)
if updateErr != nil {
panic(updateErr)
}
}
func InsertBlock(sqldb *sql.DB, blockData SBlock, blockAge SBlock) {
sqlStatement := `INSERT INTO blocks(hash, coinbase, number, gasUsed, gasLimit, txCount, uncleCount, age, parentHash, uncleHash, difficulty, size, rewards, nonce) VALUES(($1), ($2), ($3), ($4), ($5), ($6), ($7), ($8), ($9), ($10), ($11), ($12),($13), ($14)) RETURNING number`
qerr := sqldb.QueryRow(sqlStatement, blockData.Hash, blockData.Coinbase, blockData.Number, blockData.GasUsed, blockData.GasLimit, blockData.TxCount, blockData.UncleCount, blockAge.Age, blockData.ParentHash, blockData.UncleHash, blockData.Difficulty, blockData.Size, blockData.Rewards, blockData.Nonce).Scan(&blockData.Number)
if qerr != nil {
panic(qerr)
}
}
func InsertTx (sqldb *sql.DB, txData ShyftTxEntryPretty, data ShyftTxEntryPretty) {
var retNonce string
sqlStatement := `INSERT INTO txs(txhash, from_addr, to_addr, blockhash, blockNumber, amount, gasprice, gas, gasLimit, txfee, nonce, isContract, txStatus, age, data) VALUES(($1), ($2), ($3), ($4), ($5), ($6), ($7), ($8), ($9), ($10), ($11), ($12), ($13), ($14), ($15)) RETURNING nonce`
err := sqldb.QueryRow(sqlStatement, txData.TxHash, txData.From, data.To.String(), txData.BlockHash, txData.BlockNumber, txData.Amount, txData.GasPrice, txData.Gas, txData.GasLimit, txData.Cost, txData.Nonce, data.IsContract, data.Status, txData.Age, txData.Data).Scan(&retNonce)
if err != nil {
panic(err)
}
} }

View file

@ -34,7 +34,7 @@ func SGetAllBlocks(sqldb *sql.DB) string {
GasLimit: gasLimit, GasLimit: gasLimit,
TxCount: txCount, TxCount: txCount,
UncleCount: uncleCount, UncleCount: uncleCount,
Age: age, AgeGet: age,
ParentHash: parentHash, ParentHash: parentHash,
UncleHash: uncleHash, UncleHash: uncleHash,
Difficulty: difficulty, Difficulty: difficulty,
@ -70,7 +70,7 @@ func SGetBlock(sqldb *sql.DB, blockNumber string) string {
GasLimit: gasLimit, GasLimit: gasLimit,
TxCount: txCount, TxCount: txCount,
UncleCount: uncleCount, UncleCount: uncleCount,
Age: age, AgeGet: age,
ParentHash: parentHash, ParentHash: parentHash,
UncleHash: uncleHash, UncleHash: uncleHash,
Difficulty: difficulty, Difficulty: difficulty,
@ -100,7 +100,7 @@ func SGetRecentBlock(sqldb *sql.DB) string {
GasLimit: gasLimit, GasLimit: gasLimit,
TxCount: txCount, TxCount: txCount,
UncleCount: uncleCount, UncleCount: uncleCount,
Age: age, AgeGet: age,
ParentHash: parentHash, ParentHash: parentHash,
UncleHash: uncleHash, UncleHash: uncleHash,
Difficulty: difficulty, Difficulty: difficulty,
@ -135,7 +135,7 @@ func SGetAllTransactionsFromBlock(sqldb *sql.DB, blockNumber string) string {
arr.TxEntry = append(arr.TxEntry, ShyftTxEntryPretty{ arr.TxEntry = append(arr.TxEntry, ShyftTxEntryPretty{
TxHash: txhash, TxHash: txhash,
To: to_addr, ToGet: to_addr,
From: from_addr, From: from_addr,
BlockHash: blockhash, BlockHash: blockhash,
BlockNumber: blocknumber, BlockNumber: blocknumber,
@ -183,7 +183,7 @@ func SGetAllBlocksMinedByAddress(sqldb *sql.DB, coinbase string) string {
GasLimit: gasLimit, GasLimit: gasLimit,
TxCount: txCount, TxCount: txCount,
UncleCount: uncleCount, UncleCount: uncleCount,
Age: age, AgeGet: age,
ParentHash: parentHash, ParentHash: parentHash,
UncleHash: uncleHash, UncleHash: uncleHash,
Difficulty: difficulty, Difficulty: difficulty,
@ -222,7 +222,7 @@ func SGetAllTransactions(sqldb *sql.DB) string {
arr.TxEntry = append(arr.TxEntry, ShyftTxEntryPretty{ arr.TxEntry = append(arr.TxEntry, ShyftTxEntryPretty{
TxHash: txhash, TxHash: txhash,
To: to_addr, ToGet: to_addr,
From: from_addr, From: from_addr,
BlockHash: blockhash, BlockHash: blockhash,
BlockNumber: blocknumber, BlockNumber: blocknumber,
@ -260,7 +260,7 @@ func SGetTransaction(sqldb *sql.DB, txHash string) string {
tx := ShyftTxEntryPretty{ tx := ShyftTxEntryPretty{
TxHash: txhash, TxHash: txhash,
To: to_addr, ToGet: to_addr,
From: from_addr, From: from_addr,
BlockHash: blockhash, BlockHash: blockhash,
BlockNumber: blocknumber, BlockNumber: blocknumber,
@ -362,7 +362,7 @@ func SGetAccountTxs(sqldb *sql.DB, address string) string {
arr.TxEntry = append(arr.TxEntry, ShyftTxEntryPretty{ arr.TxEntry = append(arr.TxEntry, ShyftTxEntryPretty{
TxHash: txhash, TxHash: txhash,
To: to_addr, ToGet: to_addr,
From: from_addr, From: from_addr,
BlockHash: blockhash, BlockHash: blockhash,
BlockNumber: blocknumber, BlockNumber: blocknumber,

View file

@ -32,6 +32,7 @@ import (
"github.com/ShyftNetwork/go-empyrean/crypto" "github.com/ShyftNetwork/go-empyrean/crypto"
"github.com/ShyftNetwork/go-empyrean/log" "github.com/ShyftNetwork/go-empyrean/log"
"gopkg.in/olebedev/go-duktape.v3" "gopkg.in/olebedev/go-duktape.v3"
"strconv"
) )
// bigIntegerJS is the minified version of https://github.com/peterolson/BigInteger.js. // bigIntegerJS is the minified version of https://github.com/peterolson/BigInteger.js.
@ -599,10 +600,12 @@ func (i *Internals) SWriteInteralTxs(hash common.Hash) {
gas, _ := hexutil.DecodeUint64(i.Gas) gas, _ := hexutil.DecodeUint64(i.Gas)
gasUsed, _ := hexutil.DecodeUint64(i.GasUsed) gasUsed, _ := hexutil.DecodeUint64(i.GasUsed)
value, _ := hexutil.DecodeUint64(i.Value)
amount := strconv.FormatUint(value, 10)
var returnValue string var returnValue string
sqlStatement := `INSERT INTO internaltxs(type, txhash, from_addr, to_addr, amount, gas, gasUsed, time, input, output) VALUES(($1), ($2), ($3), ($4), ($5), ($6), ($7), ($8), ($9), ($10)) RETURNING txHash` sqlStatement := `INSERT INTO internaltxs(type, txhash, from_addr, to_addr, amount, gas, gasUsed, time, input, output) VALUES(($1), ($2), ($3), ($4), ($5), ($6), ($7), ($8), ($9), ($10)) RETURNING txHash`
qerr := sqldb.QueryRow(sqlStatement, i.Type, hash.Hex(), i.From, i.To, i.Value, gas, gasUsed, i.Time, i.Input, i.Output).Scan(&returnValue) qerr := sqldb.QueryRow(sqlStatement, i.Type, hash.Hex(), i.From, i.To, amount, gas, gasUsed, i.Time, i.Input, i.Output).Scan(&returnValue)
if qerr != nil { if qerr != nil {
fmt.Println(qerr) fmt.Println(qerr)

View file

@ -9,9 +9,9 @@ import (
"math/big" "math/big"
//"time" //"time"
"encoding/json" "encoding/json"
"fmt"
"github.com/ShyftNetwork/go-empyrean/crypto" "github.com/ShyftNetwork/go-empyrean/crypto"
"github.com/ShyftNetwork/go-empyrean/consensus/ethash" "github.com/ShyftNetwork/go-empyrean/consensus/ethash"
"strconv"
) )
type ShyftTracer struct {} type ShyftTracer struct {}
@ -66,12 +66,11 @@ func TestBlock(t *testing.T) {
receipts := []*types.Receipt{receipt} receipts := []*types.Receipt{receipt}
block := types.NewBlock(&types.Header{Number: big.NewInt(315)}, txs, nil, receipts) block := types.NewBlock(&types.Header{Number: big.NewInt(315)}, txs, nil, receipts)
fmt.Println("++++++HERE")
// Write and verify the block in the database // Write and verify the block in the database
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)
} }
fmt.Println("++++++AND HERE")
sqldb, err := core.DBConnection() sqldb, err := core.DBConnection()
if err != nil { if err != nil {
panic(err) panic(err)
@ -264,7 +263,7 @@ t.Run("TestContractCreationTx", func (t *testing.T) {
if tx.Hash().String() != data.TxHash { if 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 contractAddressFromReciept != data.To { 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 tx.From().String() != data.From {
@ -366,7 +365,7 @@ t.Run("TestTransactionsToReturnTransactions", func(t *testing.T) {
if tx.From().String() != data.From { if 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.To { if 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 {
@ -429,17 +428,17 @@ t.Run("TestAccountsToReturnAccounts",func(t *testing.T) {
toAddr3 := common.BytesToAddress([]byte{0x33}) toAddr3 := common.BytesToAddress([]byte{0x33})
toAmount1 := big.NewInt(111) toAmount1 := big.NewInt(111)
var toAmountPrev1 uint64 = 3968686868 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) core.CreateAccount(sqldb, toAddr1.Hex(), toAmountPrev1, "1")
core.CreateAccount(sqldb, toAddr2.Hex(), 423798729847, 1) core.CreateAccount(sqldb, toAddr2.Hex(), "423798729847", "1")
core.CreateAccount(sqldb, toAddr3.Hex(), 0, 1) core.CreateAccount(sqldb, toAddr3.Hex(), "0", "1")
core.CreateAccount(sqldb, "0x71562b71999873DB5b286dF957af199Ec94617F7", 3968686868, 1) 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, toAddr1, toAmount1, 1111, big.NewInt(11111), []byte{0x11, 0x11, 0x11})
@ -474,11 +473,11 @@ t.Run("TestAccountsToReturnAccounts",func(t *testing.T) {
accountAddrTo, _ := core.InnerSGetAccount(sqldb, toAddr1.String()) accountAddrTo, _ := core.InnerSGetAccount(sqldb, toAddr1.String())
//ewAccountNonceReceiver.Add(accountR, nonceIncrement) //ewAccountNonceReceiver.Add(accountR, nonceIncrement)
addedAmount := new(big.Int) addedAmount := new(big.Int)
b := new(big.Int).SetUint64(toAmountPrev1) toAmountPrevious1, _ := strconv.ParseUint(toAmountPrev1, 10, 64)
b := new(big.Int).SetUint64(toAmountPrevious1)
addedAmount.Add(toAmount1, b) addedAmount.Add(toAmount1, b)
toBalance := new(big.Int) toBalance := new(big.Int)
toBalance, l := toBalance.SetString(accountAddrTo.Balance, 10) toBalance, _ = toBalance.SetString(accountAddrTo.Balance, 10)
fmt.Println(l)
if toBalance.Cmp(addedAmount) != 0 { if toBalance.Cmp(addedAmount) != 0 {
t.Fatalf("To address balance [%v]: To address balance not correct FFO", toBalance) t.Fatalf("To address balance [%v]: To address balance not correct FFO", toBalance)
@ -499,17 +498,18 @@ t.Run("TestAccountsToReturnAccounts",func(t *testing.T) {
// if strconv.FormatUint(tx.Nonce(), 10) != accountDataTo.AccountNonce { // if strconv.FormatUint(tx.Nonce(), 10) != accountDataTo.AccountNonce {
// t.Fatalf("To account nonce [%v]: To account nonce not found", accountDataTo.AccountNonce) // t.Fatalf("To account nonce [%v]: To account nonce not found", accountDataTo.AccountNonce)
// } // }
// if getAllAccountTxs := core.SGetAccountTxs(sqldb, tx.To().String()); len(getAllAccountTxs) == 0 {
// t.Fatalf("GetAccountTxs [%v]: GetAccountTxs did not return correctly", getAllAccountTxs)
// }
//} //}
if getAllAccountTxs := core.SGetAccountTxs(sqldb, toAddr1.String()); len(getAllAccountTxs) == 0 {
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() ClearTables()
}) })
//ClearTables() ClearTables()
} }