Merge pull request #47 from ShyftNetwork/blockExplorer/refactor

Block explorer/refactor
This commit is contained in:
Gregory Markou 2018-07-25 17:11:18 +01:00 committed by GitHub
commit 8c95ce84d4
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
7 changed files with 685 additions and 908 deletions

View file

@ -163,7 +163,7 @@ func WriteShyftGen(gen *Genesis, block *types.Block) {
isContract := false
data:= ""
addr := k.String()
txCountAccount := v.Nonce +1
accountNonce := v.Nonce +1
i, err := strconv.ParseInt(block.Time().String(), 10, 64)
if err != nil {
panic(err)
@ -173,15 +173,15 @@ func WriteShyftGen(gen *Genesis, block *types.Block) {
GENESIS := "GENESIS"
txHash := strings.Join(Genesis, addr)
sqlStatement := `INSERT INTO accounts(addr, balance, txCountAccount) VALUES(($1), ($2), ($3)) RETURNING addr`
insertErr := sqldb.QueryRow(sqlStatement, addr, v.Balance.String(), txCountAccount).Scan(&addr)
sqlStatement := `INSERT INTO accounts(addr, balance, accountnonce) VALUES(($1), ($2), ($3)) RETURNING addr`
insertErr := sqldb.QueryRow(sqlStatement, addr, v.Balance.String(), accountNonce).Scan(&addr)
if insertErr != nil {
panic(insertErr)
}
var retNonce string
sqlGenTxStatement := `INSERT INTO txs(txhash, from_addr, to_addr, blockhash, blockNumber, amount,gasPrice, gas, gasLimit,txFee,nonce,txstatus, iscontract,age, data) VALUES(($1), ($2), ($3), ($4), ($5), ($6), ($7), ($8), ($9), ($10), ($11), ($12), ($13), ($14), ($15)) RETURNING nonce`
insertError := sqldb.QueryRow(sqlGenTxStatement, txHash, GENESIS, addr, block.Header().Hash().Hex(), number, v.Balance.String(), gasPrice, gasUsed, gasLimit, txFee,txCountAccount,txStatus, isContract, age, data).Scan(&retNonce)
insertError := sqldb.QueryRow(sqlGenTxStatement, txHash, GENESIS, addr, block.Header().Hash().Hex(), number, v.Balance.String(), gasPrice, gasUsed, gasLimit, txFee,accountNonce,txStatus, isContract, age, data).Scan(&retNonce)
if insertError != nil {
panic(insertError)
}

File diff suppressed because it is too large Load diff

386
core/shyft_get_utils.go Normal file
View file

@ -0,0 +1,386 @@
package core
import (
"encoding/json"
"database/sql"
"fmt"
"time"
)
///////////
// Getters
//////////
func SGetAllBlocks(sqldb *sql.DB) string {
var arr blockRes
var blockArr string
rows, err := sqldb.Query(`SELECT * FROM blocks`)
if err != nil {
fmt.Println("err")
}
defer rows.Close()
for rows.Next() {
var hash, coinbase, age, parentHash, uncleHash, difficulty, size, rewards, num string
var gasUsed, gasLimit, nonce uint64
var txCount, uncleCount int
err = rows.Scan(
&hash, &coinbase, &gasUsed, &gasLimit, &txCount, &uncleCount, &age, &parentHash, &uncleHash, &difficulty, &size, &nonce, &rewards, &num,)
arr.Blocks = append(arr.Blocks, SBlock{
Hash: hash,
Coinbase: coinbase,
GasUsed: gasUsed,
GasLimit: gasLimit,
TxCount: txCount,
UncleCount: uncleCount,
AgeGet: age,
ParentHash: parentHash,
UncleHash: uncleHash,
Difficulty: difficulty,
Size: size,
Nonce: nonce,
Rewards: rewards,
Number: num,
})
blocks, _ := json.Marshal(arr.Blocks)
blocksFmt := string(blocks)
blockArr = blocksFmt
}
return blockArr
}
//GetBlock queries to send single block info
//TODO provide blockHash arg passed from handler.go
func SGetBlock(sqldb *sql.DB, blockNumber string) string {
sqlStatement := `SELECT * FROM blocks WHERE number=$1;`
row := sqldb.QueryRow(sqlStatement, blockNumber)
var hash, coinbase, age, parentHash, uncleHash, difficulty, size, rewards, num string
var gasUsed, gasLimit, nonce uint64
var txCount, uncleCount int
row.Scan(
&hash, &coinbase, &gasUsed, &gasLimit, &txCount, &uncleCount, &age, &parentHash, &uncleHash, &difficulty, &size, &nonce, &rewards, &num,)
block := SBlock{
Hash: hash,
Coinbase: coinbase,
GasUsed: gasUsed,
GasLimit: gasLimit,
TxCount: txCount,
UncleCount: uncleCount,
AgeGet: age,
ParentHash: parentHash,
UncleHash: uncleHash,
Difficulty: difficulty,
Size: size,
Nonce: nonce,
Rewards: rewards,
Number: num,
}
json, _ := json.Marshal(block)
return string(json)
}
func SGetRecentBlock(sqldb *sql.DB) string {
sqlStatement := `SELECT * FROM blocks WHERE number=(SELECT MAX(number) FROM blocks);`
row := sqldb.QueryRow(sqlStatement)
var hash, coinbase, age, parentHash, uncleHash, difficulty, size, rewards, num string
var gasUsed, gasLimit, nonce uint64
var txCount, uncleCount int
row.Scan(
&hash, &coinbase, &gasUsed, &gasLimit, &txCount, &uncleCount, &age, &parentHash, &uncleHash, &difficulty, &size, &nonce, &rewards, &num,)
block := SBlock{
Hash: hash,
Coinbase: coinbase,
GasUsed: gasUsed,
GasLimit: gasLimit,
TxCount: txCount,
UncleCount: uncleCount,
AgeGet: age,
ParentHash: parentHash,
UncleHash: uncleHash,
Difficulty: difficulty,
Size: size,
Nonce: nonce,
Rewards: rewards,
Number: num,
}
json, _ := json.Marshal(block)
return string(json)
}
func SGetAllTransactionsFromBlock(sqldb *sql.DB, blockNumber string) string {
var arr txRes
var txx string
sqlStatement := `SELECT * FROM txs WHERE blocknumber=$1`
rows, err := sqldb.Query(sqlStatement, blockNumber)
if err != nil {
fmt.Println("err")
}
defer rows.Close()
for rows.Next() {
var txhash, to_addr, from_addr, blockhash, blocknumber, amount, status string
var gasprice, gas, gasLimit, txfee, nonce uint64
var isContract bool
var age time.Time
var data []byte
err = rows.Scan(
&txhash, &to_addr, &from_addr, &blockhash, &blocknumber, &amount, &gasprice, &gas, &gasLimit, &txfee, &nonce, &status, &isContract, &age, &data,
)
arr.TxEntry = append(arr.TxEntry, ShyftTxEntryPretty{
TxHash: txhash,
ToGet: to_addr,
From: from_addr,
BlockHash: blockhash,
BlockNumber: blocknumber,
Amount: amount,
GasPrice: gasprice,
Gas: gas,
GasLimit: gasLimit,
Cost: txfee,
Nonce: nonce,
Status: status,
IsContract: isContract,
Age: age,
Data: data,
})
tx, _ := json.Marshal(arr.TxEntry)
newtx := string(tx)
txx = newtx
}
return txx
}
func SGetAllBlocksMinedByAddress(sqldb *sql.DB, coinbase string) string {
var arr blockRes
var blockArr string
sqlStatement := `SELECT * FROM blocks WHERE coinbase=$1`
rows, err := sqldb.Query(sqlStatement, coinbase)
if err != nil {
fmt.Println("err")
}
defer rows.Close()
for rows.Next() {
var hash, coinbase, age, parentHash, uncleHash, difficulty, size, rewards, num string
var gasUsed, gasLimit, nonce uint64
var txCount, uncleCount int
err = rows.Scan(
&hash, &coinbase, &gasUsed, &gasLimit, &txCount, &uncleCount, &age, &parentHash, &uncleHash, &difficulty, &size, &nonce, &rewards, &num,)
arr.Blocks = append(arr.Blocks, SBlock{
Hash: hash,
Coinbase: coinbase,
GasUsed: gasUsed,
GasLimit: gasLimit,
TxCount: txCount,
UncleCount: uncleCount,
AgeGet: age,
ParentHash: parentHash,
UncleHash: uncleHash,
Difficulty: difficulty,
Size: size,
Nonce: nonce,
Rewards: rewards,
Number: num,
})
blocks, _ := json.Marshal(arr.Blocks)
blocksFmt := string(blocks)
blockArr = blocksFmt
}
return blockArr
}
//GetAllTransactions getter fn for API
func SGetAllTransactions(sqldb *sql.DB) string {
var arr txRes
var txx string
rows, err := sqldb.Query(`SELECT * FROM txs`)
if err != nil {
fmt.Println("err")
}
defer rows.Close()
for rows.Next() {
var txhash, to_addr, from_addr, blockhash, blocknumber, amount, status string
var gasprice, gas, gasLimit, txfee, nonce uint64
var isContract bool
var age time.Time
var data []byte
err = rows.Scan(
&txhash, &to_addr, &from_addr, &blockhash, &blocknumber, &amount, &gasprice, &gas, &gasLimit, &txfee, &nonce, &status, &isContract, &age, &data,
)
arr.TxEntry = append(arr.TxEntry, ShyftTxEntryPretty{
TxHash: txhash,
ToGet: to_addr,
From: from_addr,
BlockHash: blockhash,
BlockNumber: blocknumber,
Amount: amount,
GasPrice: gasprice,
Gas: gas,
GasLimit: gasLimit,
Cost: txfee,
Nonce: nonce,
Status: status,
IsContract: isContract,
Age: age,
Data: data,
})
tx, _ := json.Marshal(arr.TxEntry)
newtx := string(tx)
txx = newtx
}
return txx
}
//GetTransaction fn returns single tx
func SGetTransaction(sqldb *sql.DB, txHash string) string {
sqlStatement := `SELECT * FROM txs WHERE txhash=$1;`
row := sqldb.QueryRow(sqlStatement, txHash)
var txhash, to_addr, from_addr, blockhash, blocknumber, amount, status string
var gasprice, gas, gasLimit, txfee, nonce uint64
var isContract bool
var age time.Time
var data []byte
row.Scan(
&txhash, &to_addr, &from_addr, &blockhash, &blocknumber, &amount, &gasprice, &gas, &gasLimit, &txfee, &nonce, &status, &isContract, &age, &data)
tx := ShyftTxEntryPretty{
TxHash: txhash,
ToGet: to_addr,
From: from_addr,
BlockHash: blockhash,
BlockNumber: blocknumber,
Amount: amount,
GasPrice: gasprice,
Gas: gas,
GasLimit: gasLimit,
Cost: txfee,
Nonce: nonce,
Status: status,
IsContract: isContract,
Age: age,
Data: data,
}
json, _ := json.Marshal(tx)
return string(json)
}
func InnerSGetAccount(sqldb *sql.DB, address string) (SAccounts, bool) {
sqlStatement := `SELECT * FROM accounts WHERE addr=$1;`
var addr, balance, accountNonce string
err := sqldb.QueryRow(sqlStatement, address).Scan(&addr, &balance, &accountNonce)
if err == sql.ErrNoRows {
return SAccounts{}, false
} else {
account := SAccounts{
Addr: addr,
Balance: balance,
AccountNonce: accountNonce,
}
return account, true
}
}
//GetAccount returns account balances
func SGetAccount(sqldb *sql.DB, address string) string {
var account, _ = InnerSGetAccount(sqldb, address)
json, _ := json.Marshal(account)
return string(json)
}
//GetAllAccounts returns all accounts and balances
func SGetAllAccounts(sqldb *sql.DB) string {
var array accountRes
var accountsArr, accountNonce string
accs, err := sqldb.Query(`
SELECT
addr,
balance,
accountNonce
FROM accounts`)
if err != nil {
fmt.Println(err)
}
defer accs.Close()
for accs.Next() {
var addr, balance string
err = accs.Scan(
&addr, &balance, &accountNonce,
)
array.AllAccounts = append(array.AllAccounts, SAccounts{
Addr: addr,
Balance: balance,
AccountNonce: accountNonce,
})
accounts, _ := json.Marshal(array.AllAccounts)
accountsFmt := string(accounts)
accountsArr = accountsFmt
}
return accountsArr
}
//GetAccount returns account balances
func SGetAccountTxs(sqldb *sql.DB, address string) string {
var arr txRes
var txx string
sqlStatement := `SELECT * FROM txs WHERE to_addr=$1 OR from_addr=$1;`
rows, err := sqldb.Query(sqlStatement, address)
if err != nil {
fmt.Println("err", err)
}
defer rows.Close()
for rows.Next() {
var txhash, to_addr, from_addr, blockhash, blocknumber, amount, status string
var gasprice, gas, gasLimit, txfee, nonce uint64
var isContract bool
var age time.Time
var data []byte
err = rows.Scan(
&txhash, &to_addr, &from_addr, &blockhash, &blocknumber, &amount, &gasprice, &gas, &gasLimit, &txfee, &nonce, &status, &isContract, &age, &data,
)
arr.TxEntry = append(arr.TxEntry, ShyftTxEntryPretty{
TxHash: txhash,
ToGet: to_addr,
From: from_addr,
BlockHash: blockhash,
BlockNumber: blocknumber,
Amount: amount,
GasPrice: gasprice,
Gas: gas,
GasLimit: gasLimit,
Cost: txfee,
Nonce: nonce,
Status: status,
IsContract: isContract,
Age: age,
Data: data,
})
tx, _ := json.Marshal(arr.TxEntry)
newtx := string(tx)
txx = newtx
}
return txx
}

View file

@ -32,6 +32,7 @@ import (
"github.com/ShyftNetwork/go-empyrean/crypto"
"github.com/ShyftNetwork/go-empyrean/log"
"gopkg.in/olebedev/go-duktape.v3"
"strconv"
)
// bigIntegerJS is the minified version of https://github.com/peterolson/BigInteger.js.
@ -599,16 +600,19 @@ func (i *Internals) SWriteInteralTxs(hash common.Hash) {
gas, _ := hexutil.DecodeUint64(i.Gas)
gasUsed, _ := hexutil.DecodeUint64(i.GasUsed)
value, _ := hexutil.DecodeUint64(i.Value)
amount := strconv.FormatUint(value, 10)
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`
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 {
fmt.Println(qerr)
panic(qerr)
}
}
//@NOTE:SHYFT
func (i *Internals) InternalRecursive(hash common.Hash) {
i.SWriteInteralTxs(hash)

View file

@ -36,7 +36,7 @@ CREATE TABLE IF NOT EXISTS txs (
CREATE TABLE IF NOT EXISTS accounts (
addr text primary key unique,
balance numeric,
txCountAccount numeric
accountNonce numeric
);
CREATE TABLE IF NOT EXISTS contracts (

View file

@ -36,5 +36,5 @@ CREATE TABLE IF NOT EXISTS txs (
CREATE TABLE IF NOT EXISTS accounts (
addr text primary key unique,
balance numeric,
txCountAccount numeric
accountnonce numeric
);

View file

@ -263,7 +263,7 @@ t.Run("TestContractCreationTx", func (t *testing.T) {
if tx.Hash().String() != data.TxHash {
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)
}
if tx.From().String() != data.From {
@ -365,7 +365,7 @@ t.Run("TestTransactionsToReturnTransactions", func(t *testing.T) {
if tx.From().String() != data.From {
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())
}
if tx.Nonce() != data.Nonce {
@ -423,12 +423,29 @@ t.Run("TestAccountsToReturnAccounts",func(t *testing.T) {
key, _ := crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
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()
if (err != nil) {
panic(err)
}
core.CreateAccount(sqldb, toAddr1.Hex(), toAmountPrev1, "1")
core.CreateAccount(sqldb, toAddr2.Hex(), "423798729847", "1")
core.CreateAccount(sqldb, toAddr3.Hex(), "0", "1")
core.CreateAccount(sqldb, "0x71562b71999873DB5b286dF957af199Ec94617F7", "3968686868", "1")
//Nonce, To Address,Value, GasLimit, Gasprice, data
tx1 := types.NewTransaction(1, common.BytesToAddress([]byte{0x11}), big.NewInt(111), 1111, big.NewInt(11111), []byte{0x11, 0x11, 0x11})
tx1 := types.NewTransaction(1, toAddr1, toAmount1, 1111, big.NewInt(11111), []byte{0x11, 0x11, 0x11})
mytx,_ := types.SignTx(tx1, signer, key)
tx2 := types.NewTransaction(2, common.BytesToAddress([]byte{0x22}), big.NewInt(222), 2222, big.NewInt(22222), []byte{0x22, 0x22, 0x22})
tx2 := types.NewTransaction(2, toAddr2, big.NewInt(222), 2222, big.NewInt(22222), []byte{0x22, 0x22, 0x22})
mytx2,_ := types.SignTx(tx2, signer, key)
tx3 := types.NewTransaction(3, common.BytesToAddress([]byte{0x33}), big.NewInt(333), 3333, big.NewInt(33333), []byte{0x33, 0x33, 0x33})
tx3 := types.NewTransaction(3, toAddr3, big.NewInt(333), 3333, big.NewInt(33333), []byte{0x33, 0x33, 0x33})
mytx3,_ := types.SignTx(tx3, signer, key)
txs := []*types.Transaction{mytx, mytx2, mytx3}
@ -450,30 +467,42 @@ t.Run("TestAccountsToReturnAccounts",func(t *testing.T) {
t.Fatalf("Failed to write block into database: %v", err)
}
sqldb, err := core.DBConnection()
if (err != nil) {
panic(err)
if toAddr1.String() != tx1.To().String() {
t.Fatalf("To address [%v]: To address not found", toAddr1.String())
}
accountAddrTo, _ := core.InnerSGetAccount(sqldb, toAddr1.String())
//ewAccountNonceReceiver.Add(accountR, nonceIncrement)
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)
}
for _, tx := range txs {
accountAddrTo := core.SGetAccount(sqldb, tx.To().String())
byts := []byte(accountAddrTo)
var accountDataTo core.SAccounts
json.Unmarshal(byts, &accountDataTo)
//for _, tx := range txs {
// 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 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.TxCountAccount {
t.Fatalf("To account nonce [%v]: To account nonce not found", accountDataTo.TxCountAccount)
}
if getAllAccountTxs := core.SGetAccountTxs(sqldb, tx.To().String()); len(getAllAccountTxs) == 0 {
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 {
t.Fatalf("GetAllAccounts [%v]: GetAllAccounts did not return correctly", getAllAccounts)