Merge pull request #48 from ShyftNetwork/update/accountBalances

Update/account balances
This commit is contained in:
Priom Chowdhury 2018-08-13 10:31:36 -04:00 committed by GitHub
commit f345b88d07
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
23 changed files with 853 additions and 900 deletions

View file

@ -29,7 +29,6 @@ import (
"sync/atomic" "sync/atomic"
"time" "time"
"github.com/ShyftNetwork/go-empyrean/common" "github.com/ShyftNetwork/go-empyrean/common"
"github.com/ShyftNetwork/go-empyrean/common/mclock" "github.com/ShyftNetwork/go-empyrean/common/mclock"
"github.com/ShyftNetwork/go-empyrean/consensus" "github.com/ShyftNetwork/go-empyrean/consensus"

View file

@ -21,8 +21,8 @@ import (
"encoding/binary" "encoding/binary"
"encoding/json" "encoding/json"
"errors" "errors"
"math/big"
"fmt" "fmt"
"math/big"
"github.com/ShyftNetwork/go-empyrean/common" "github.com/ShyftNetwork/go-empyrean/common"
"github.com/ShyftNetwork/go-empyrean/core/types" "github.com/ShyftNetwork/go-empyrean/core/types"
@ -283,14 +283,7 @@ func GetTxLookupEntry(db DatabaseReader, hash common.Hash) (common.Hash, uint64,
// its added positional metadata. // its added positional metadata.
func GetTransaction(db DatabaseReader, hash common.Hash) (*types.Transaction, common.Hash, uint64, uint64) { func GetTransaction(db DatabaseReader, hash common.Hash) (*types.Transaction, common.Hash, uint64, uint64) {
// Retrieve the lookup metadata and resolve the transaction from the body // Retrieve the lookup metadata and resolve the transaction from the body
//fmt.Println("INSIDE GET TRANSACTION ++++++++")
//fmt.Println("The hash and db reader are")
//fmt.Println(hash)
//fmt.Println(db)
blockHash, blockNumber, txIndex := GetTxLookupEntry(db, hash) blockHash, blockNumber, txIndex := GetTxLookupEntry(db, hash)
//fmt.Println(blockHash)
//fmt.Println(blockNumber)
if blockHash != (common.Hash{}) { if blockHash != (common.Hash{}) {
body := GetBody(db, blockHash, blockNumber) body := GetBody(db, blockHash, blockNumber)
if body == nil || len(body.Transactions) <= int(txIndex) { if body == nil || len(body.Transactions) <= int(txIndex) {

View file

@ -62,3 +62,28 @@ func DBConnection() (*sql.DB, error) {
} }
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

@ -18,26 +18,27 @@ package core
import ( import (
"bytes" "bytes"
"database/sql"
"encoding/hex" "encoding/hex"
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"math/big" "math/big"
"strconv"
"strings" "strings"
"time"
_ "github.com/lib/pq"
"github.com/ShyftNetwork/go-empyrean/common" "github.com/ShyftNetwork/go-empyrean/common"
"github.com/ShyftNetwork/go-empyrean/common/hexutil" "github.com/ShyftNetwork/go-empyrean/common/hexutil"
"github.com/ShyftNetwork/go-empyrean/common/math" "github.com/ShyftNetwork/go-empyrean/common/math"
stypes "github.com/ShyftNetwork/go-empyrean/core/sTypes"
"github.com/ShyftNetwork/go-empyrean/core/state" "github.com/ShyftNetwork/go-empyrean/core/state"
"github.com/ShyftNetwork/go-empyrean/core/types" "github.com/ShyftNetwork/go-empyrean/core/types"
"github.com/ShyftNetwork/go-empyrean/ethdb" "github.com/ShyftNetwork/go-empyrean/ethdb"
"github.com/ShyftNetwork/go-empyrean/log" "github.com/ShyftNetwork/go-empyrean/log"
"github.com/ShyftNetwork/go-empyrean/params" "github.com/ShyftNetwork/go-empyrean/params"
"github.com/ShyftNetwork/go-empyrean/rlp" "github.com/ShyftNetwork/go-empyrean/rlp"
"database/sql" _ "github.com/lib/pq"
"strconv"
"time"
) )
//go:generate gencodec -type Genesis -field-override genesisSpecMarshaling -out gen_genesis.go //go:generate gencodec -type Genesis -field-override genesisSpecMarshaling -out gen_genesis.go
@ -143,85 +144,90 @@ func (e *GenesisMismatchError) Error() string {
//WriteShyftGen writes the genesis block to Shyft db //WriteShyftGen writes the genesis block to Shyft db
//@NOTE:SHYFT //@NOTE:SHYFT
func WriteShyftGen(gen *Genesis, block *types.Block) { func WriteShyftGen(gen *Genesis, block *types.Block) {
sqldb, _ := DBConnection() sqldb, _ := DBConnection()
for k, v := range gen.Alloc {
for k := range gen.Alloc { _, _, err := AccountExists(sqldb, k.String())
addr := k.String()
var response string
sqlExistsStatement := `SELECT balance from accounts WHERE addr = ($1)`
err := sqldb.QueryRow(sqlExistsStatement, addr).Scan(&response)
switch { switch {
case err == sql.ErrNoRows: case err == sql.ErrNoRows:
for k, v := range gen.Alloc { var toAddr *common.Address
number := block.Header().Number.String() var data []byte
gasUsed := block.Header().GasUsed var cost, gasPrice uint64
gasLimit := block.Header().GasLimit //Initializing proper types for tx struct
gasPrice := 0 toAddr = &k
txFee := 0 cost = 0
txStatus := "" gasPrice = 0
isContract := false //Appending GENESIS to address stored as txHash and From Addr
data:= "" Genesis := []string{"GENESIS_", k.String()}
addr := k.String() GENESIS := "GENESIS"
txHash := strings.Join(Genesis, k.String())
//Create the accountNonce, set to 1 (1 incoming tx), format type
accountNonce := v.Nonce + 1 accountNonce := v.Nonce + 1
accountNoncee := strconv.FormatUint(accountNonce, 10)
i, err := strconv.ParseInt(block.Time().String(), 10, 64) i, err := strconv.ParseInt(block.Time().String(), 10, 64)
if err != nil { if err != nil {
panic(err) panic(err)
} }
age := time.Unix(i, 0) age := time.Unix(i, 0)
Genesis := []string{"GENESIS_", addr}
GENESIS := "GENESIS"
txHash := strings.Join(Genesis, addr)
sqlStatement := `INSERT INTO accounts(addr, balance, accountnonce) VALUES(($1), ($2), ($3)) RETURNING addr` txData := stypes.ShyftTxEntryPretty{
insertErr := sqldb.QueryRow(sqlStatement, addr, v.Balance.String(), accountNonce).Scan(&addr) TxHash: txHash,
if insertErr != nil { From: GENESIS,
panic(insertErr) To: toAddr,
BlockHash: block.Header().Hash().Hex(),
BlockNumber: block.Header().Number.String(),
Amount: v.Balance.String(),
Cost: cost,
GasPrice: gasPrice,
GasLimit: block.GasLimit(),
Gas: block.GasUsed(),
Nonce: accountNonce,
Age: age,
Data: data,
Status: "SUCCESS",
IsContract: false,
} }
//Create account and store tx
CreateAccount(sqldb, k.String(), v.Balance.String(), accountNoncee)
InsertTx(sqldb, txData)
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,accountNonce,txStatus, isContract, age, data).Scan(&retNonce)
if insertError != nil {
panic(insertError)
}
}
default: default:
log.Info("Found Genesis Block") log.Info("Found Genesis Block")
}}} }
}
}
//WriteShyftBlockZero writes block 0 to postgres db
func WriteShyftBlockZero(block *types.Block, gen *Genesis) error { func WriteShyftBlockZero(block *types.Block, gen *Genesis) error {
sqldb, _ := DBConnection() sqldb, _ := DBConnection()
coinbase := block.Header().Coinbase.String() i, error := strconv.ParseInt(block.Time().String(), 10, 64)
number := block.Header().Number.String() if error != nil {
gasUsed := block.Header().GasUsed panic(error)
gasLimit := block.Header().GasLimit
uncleCount := len(block.Uncles())
parentHash := block.ParentHash().String()
uncleHash := block.UncleHash().String()
blockDifficulty := block.Difficulty().String()
blockSize := block.Size().String()
blockNonce := block.Nonce()
genesisTxCount := len(gen.Alloc)
i, err := strconv.ParseInt(block.Time().String(), 10, 64)
if err != nil {
panic(err)
} }
age := time.Unix(i, 0) age := time.Unix(i, 0)
var response string blockData := stypes.SBlock{
sqlExistsStatement := `SELECT hash from blocks WHERE hash= ($1)` Hash: block.Header().Hash().Hex(),
err = sqldb.QueryRow(sqlExistsStatement, block.Header().Hash().Hex()).Scan(&response) Coinbase: block.Header().Coinbase.String(),
Number: block.Header().Number.String(),
GasUsed: block.Header().GasUsed,
GasLimit: block.Header().GasLimit,
TxCount: len(gen.Alloc),
UncleCount: len(block.Uncles()),
Age: age,
ParentHash: block.ParentHash().String(),
UncleHash: block.UncleHash().String(),
Difficulty: block.Difficulty().String(),
Size: block.Size().String(),
Nonce: block.Nonce(),
Rewards: "0",
}
err := BlockExists(sqldb, blockData.Hash)
switch { switch {
case err == sql.ErrNoRows: case err == sql.ErrNoRows:
sqlStatement := `INSERT INTO blocks(hash, coinbase, number, gasUsed, gasLimit, txCount, uncleCount, age, parentHash, uncleHash, difficulty, size, nonce) VALUES(($1), ($2), ($3), ($4), ($5), ($6), ($7), ($8), ($9), ($10), ($11), ($12),($13)) RETURNING number` InsertBlock(sqldb, blockData)
qerr := sqldb.QueryRow(sqlStatement, block.Header().Hash().Hex(), coinbase, number, gasUsed, gasLimit, genesisTxCount, uncleCount, age, parentHash, uncleHash, blockDifficulty, blockSize, blockNonce).Scan(&number)
if qerr != nil {
panic(qerr)
}
case err != nil: case err != nil:
panic(err) panic(err)
default: default:
@ -229,6 +235,7 @@ func WriteShyftBlockZero(block *types.Block, gen *Genesis) error {
} }
return nil return nil
} }
// SetupGenesisBlock writes or updates the genesis block in db. // SetupGenesisBlock writes or updates the genesis block in db.
// The block that will be used is: // The block that will be used is:
// //
@ -256,11 +263,20 @@ func SetupGenesisBlock(db ethdb.Database, genesis *Genesis) (*params.ChainConfig
log.Info("Writing custom genesis block") log.Info("Writing custom genesis block")
} }
block, err := genesis.Commit(db) block, err := genesis.Commit(db)
//@NOTE:SHYFT SWITCH CASE ENSURES SHYFT GENESIS FUNCTIONS ARE ONLY CALLED ONCE
sqldb, _ := DBConnection()
serror := BlockExists(sqldb, block.Hash().String())
switch {
case serror == sql.ErrNoRows:
//@NOTE:SHYFT WRITE TO BLOCK ZERO DB //@NOTE:SHYFT WRITE TO BLOCK ZERO DB
WriteShyftBlockZero(block, genesis) WriteShyftBlockZero(block, genesis)
//@NOTE:SHYFT WRITE TO DB //@NOTE:SHYFT WRITE TO DB
WriteShyftGen(genesis, block) WriteShyftGen(genesis, block)
case serror != nil:
panic(serror)
default:
log.Info("Genesis Block Written")
}
return genesis.Config, block.Hash(), err return genesis.Config, block.Hash(), err
} }
@ -315,6 +331,7 @@ func (g *Genesis) configOrDefault(ghash common.Hash) *params.ChainConfig {
return params.AllEthashProtocolChanges return params.AllEthashProtocolChanges
} }
} }
// ToBlock creates the genesis block and writes state of a genesis specification // ToBlock creates the genesis block and writes state of a genesis specification
// to the given database (or discards it if nil). // to the given database (or discards it if nil).
func (g *Genesis) ToBlock(db ethdb.Database) *types.Block { func (g *Genesis) ToBlock(db ethdb.Database) *types.Block {
@ -439,6 +456,7 @@ func DefaultRinkebyGenesisBlock() *Genesis {
Alloc: decodePrealloc(rinkebyAllocData), Alloc: decodePrealloc(rinkebyAllocData),
} }
} }
// DeveloperGenesisBlock returns the 'geth --dev' genesis block. Note, this must // DeveloperGenesisBlock returns the 'geth --dev' genesis block. Note, this must
// be seeded with the // be seeded with the
func DeveloperGenesisBlock(period uint64, faucet common.Address) *Genesis { func DeveloperGenesisBlock(period uint64, faucet common.Address) *Genesis {

92
core/sTypes/stypes.go Normal file
View file

@ -0,0 +1,92 @@
package stypes
import (
"time"
"github.com/ShyftNetwork/go-empyrean/common"
)
//SBlock type
type SBlock struct {
Hash string
Coinbase string
AgeGet string
Age time.Time
ParentHash string
UncleHash string
Difficulty string
Size string
Rewards string
Number string
GasUsed uint64
GasLimit uint64
Nonce uint64
TxCount int
UncleCount int
Blocks []SBlock
}
type InteralWrite struct {
Hash string
Type string
From string
To string
Value string
Gas uint64
GasUsed uint64
Input string
Output string
Time string
}
//blockRes struct
type BlockRes struct {
hash string
coinbase string
number string
Blocks []SBlock
}
type SAccounts struct {
Addr string
Balance string
AccountNonce string
}
type AccountRes struct {
addr string
balance string
AllAccounts []SAccounts
}
type TxRes struct {
TxEntry []ShyftTxEntryPretty
}
type ShyftTxEntryPretty struct {
TxHash string
To *common.Address
ToGet string
From string
BlockHash string
BlockNumber string
Amount string
GasPrice uint64
Gas uint64
GasLimit uint64
Cost uint64
Nonce uint64
Status string
IsContract bool
Age time.Time
Data []byte
}
type SendAndReceive struct {
To string
From string
Amount string
Address string
Balance string
AccountNonce uint64 `json:",string"`
}

View file

@ -1,106 +1,47 @@
package core package core
import ( import (
"math/big"
"time"
"strconv"
"database/sql" "database/sql"
"fmt"
"log" "log"
_ "github.com/lib/pq" "math/big"
"strconv"
"strings"
"time"
"github.com/ShyftNetwork/go-empyrean/common" "github.com/ShyftNetwork/go-empyrean/common"
"github.com/ShyftNetwork/go-empyrean/core/types"
Rewards "github.com/ShyftNetwork/go-empyrean/consensus/ethash" Rewards "github.com/ShyftNetwork/go-empyrean/consensus/ethash"
stypes "github.com/ShyftNetwork/go-empyrean/core/sTypes"
"github.com/ShyftNetwork/go-empyrean/core/types"
"github.com/ShyftNetwork/go-empyrean/shyfttracerinterface" "github.com/ShyftNetwork/go-empyrean/shyfttracerinterface"
_ "github.com/lib/pq"
) )
//IShyftTracer Used to initialize ShyftTracer
var IShyftTracer shyfttracerinterface.IShyftTracer var IShyftTracer shyfttracerinterface.IShyftTracer
//SetIShyftTracer sets tracer type
func SetIShyftTracer(st shyfttracerinterface.IShyftTracer) { func SetIShyftTracer(st shyfttracerinterface.IShyftTracer) {
IShyftTracer = st IShyftTracer = st
} }
//SBlock type //SWriteBlock writes to block info to sql db
type SBlock struct {
Hash string
Coinbase string
AgeGet string
Age time.Time
ParentHash string
UncleHash string
Difficulty string
Size string
Rewards string
Number string
GasUsed uint64
GasLimit uint64
Nonce uint64
TxCount int
UncleCount int
Blocks []SBlock
}
//blockRes struct
type blockRes struct {
hash string
coinbase string
number string
Blocks []SBlock
}
type SAccounts struct {
Addr string
Balance string
AccountNonce string
}
type accountRes struct {
addr string
balance string
AllAccounts []SAccounts
}
type txRes struct {
TxEntry []ShyftTxEntryPretty
}
type ShyftTxEntryPretty struct {
TxHash string
To *common.Address
ToGet string
From string
BlockHash string
BlockNumber string
Amount string
GasPrice uint64
Gas uint64
GasLimit uint64
Cost uint64
Nonce uint64
Status string
IsContract bool
Age time.Time
Data []byte
}
type SendAndReceive struct {
To string
From string
Amount string
Address string
Balance string
AccountNonce uint64 `json:",string"`
}
//WriteBlock writes to block info to sql db
func SWriteBlock(block *types.Block, receipts []*types.Receipt) error { func SWriteBlock(block *types.Block, receipts []*types.Receipt) error {
sqldb, err := DBConnection() sqldb, err := DBConnection()
if err != nil { if err != nil {
panic(err) panic(err)
} }
//Get miner rewards
rewards := swriteMinerRewards(sqldb, block) rewards := swriteMinerRewards(sqldb, block)
//Format block time to be stored
i, err := strconv.ParseInt(block.Time().String(), 10, 64)
if err != nil {
panic(err)
}
age := time.Unix(i, 0)
blockData := SBlock{ blockData := stypes.SBlock{
Hash: block.Header().Hash().Hex(), Hash: block.Header().Hash().Hex(),
Coinbase: block.Header().Coinbase.String(), Coinbase: block.Header().Coinbase.String(),
Number: block.Header().Number.String(), Number: block.Header().Number.String(),
@ -114,30 +55,15 @@ func SWriteBlock(block *types.Block, receipts []*types.Receipt) error {
Size: block.Size().String(), Size: block.Size().String(),
Nonce: block.Nonce(), Nonce: block.Nonce(),
Rewards: rewards, Rewards: rewards,
}
i, err := strconv.ParseInt(block.Time().String(), 10, 64)
if err != nil {
panic(err)
}
age := time.Unix(i, 0)
blockAge := SBlock {
Age: age, Age: age,
} }
//Inserts block data into DB //Inserts block data into DB
InsertBlock(sqldb, blockData, blockAge) InsertBlock(sqldb, blockData)
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)
if block.Transactions()[0].To() != nil {
swriteFromBalance(sqldb, tx)
}
if block.Transactions()[0].To() == nil {
swriteContractBalance(sqldb, tx)
}
} }
} }
return nil return nil
@ -147,24 +73,9 @@ func SWriteBlock(block *types.Block, receipts []*types.Receipt) error {
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 string var statusFromReciept string
var toAddr *common.Address
var contractAddressFromReciept common.Address var contractAddressFromReciept common.Address
txData := ShyftTxEntryPretty{
TxHash: tx.Hash().Hex(),
From: tx.From().Hex(),
To: tx.To(),
BlockHash: blockHash.Hex(),
BlockNumber: blockNumber,
Amount: tx.Value().String(),
Cost: tx.Cost().Uint64(),
GasPrice: tx.GasPrice().Uint64(),
GasLimit: gasLimit,
Gas: tx.Gas(),
Nonce: tx.Nonce(),
Age: age,
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
@ -177,13 +88,7 @@ func swriteTransactions(sqldb *sql.DB, tx *types.Transaction, blockHash common.H
} }
} }
isContract = true isContract = true
contractData := ShyftTxEntryPretty{ toAddr = &contractAddressFromReciept
Status: statusFromReciept,
IsContract: isContract,
To: &contractAddressFromReciept,
}
//Insert Tx into DB
InsertTx(sqldb, txData, contractData)
} else { } else {
isContract = false isContract = false
for _, receipt := range receipts { for _, receipt := range receipts {
@ -195,34 +100,67 @@ func swriteTransactions(sqldb *sql.DB, tx *types.Transaction, blockHash common.H
statusFromReciept = "SUCCESS" statusFromReciept = "SUCCESS"
} }
} }
data := ShyftTxEntryPretty{ toAddr = tx.To()
}
txData := stypes.ShyftTxEntryPretty{
TxHash: tx.Hash().Hex(),
From: tx.From().Hex(),
To: toAddr,
BlockHash: blockHash.Hex(),
BlockNumber: blockNumber,
Amount: tx.Value().String(),
Cost: tx.Cost().Uint64(),
GasPrice: tx.GasPrice().Uint64(),
GasLimit: gasLimit,
Gas: tx.Gas(),
Nonce: tx.Nonce(),
Age: age,
Data: tx.Data(),
Status: statusFromReciept, Status: statusFromReciept,
IsContract: isContract, IsContract: isContract,
To: tx.To(),
}
//Insert Tx into DB
InsertTx(sqldb, txData, data)
} }
//Inserts Tx into DB
InsertTx(sqldb, txData)
//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())
return nil return nil
} }
func swriteContractBalance(sqldb *sql.DB, tx *types.Transaction) error { //SWriteInternalTxBalances Writes internal txs and updates balances
sendAndReceiveData := SendAndReceive{ func SWriteInternalTxBalances(sqldb *sql.DB, toAddr string, fromAddr string, amount string) error {
From: tx.From().Hex(), sendAndReceiveData := stypes.SendAndReceive{
Amount: tx.Value().String(), To: toAddr,
AccountNonce: tx.Nonce(), From: fromAddr,
Amount: amount,
} }
_, _, err := AccountExists(sqldb, sendAndReceiveData.To)
fromAddressBalance, fromAccountNonce, err := AccountExists(sqldb, sendAndReceiveData.From) value := new(big.Int)
value, _ = value.SetString(amount, 10)
switch { switch {
case err == sql.ErrNoRows: case err == sql.ErrNoRows:
accountNonce := strconv.FormatUint(tx.Nonce(), 10) accountNonce := "1"
CreateAccount(sqldb, sendAndReceiveData.From, sendAndReceiveData.Amount, accountNonce) CreateAccount(sqldb, sendAndReceiveData.To, sendAndReceiveData.Amount, accountNonce)
adjustBalanceFromAddr(sqldb, sendAndReceiveData, value)
case err != nil:
log.Fatal(err)
default: default:
balanceHelper(sqldb, sendAndReceiveData, amount)
}
return nil
}
func adjustBalanceFromAddr(sqldb *sql.DB, s stypes.SendAndReceive, value *big.Int) {
fromAddressBalance, fromAccountNonce, err := AccountExists(sqldb, s.From)
switch {
case err == sql.ErrNoRows:
CreateAccount(sqldb, s.From, "0", "1")
fmt.Println("New From account created")
}
if err != nil {
log.Fatal(err)
}
var newBalanceSender, newAccountNonceSender big.Int var newBalanceSender, newAccountNonceSender big.Int
var nonceIncrement = big.NewInt(1) var nonceIncrement = big.NewInt(1)
@ -232,32 +170,15 @@ func swriteContractBalance(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)
newBalanceSender.Sub(fromBalance, tx.Value()) newBalanceSender.Sub(fromBalance, value)
newAccountNonceSender.Add(fromNonce, nonceIncrement) newAccountNonceSender.Add(fromNonce, nonceIncrement)
UpdateAccount(sqldb, sendAndReceiveData.From, newBalanceSender.String(), newAccountNonceSender.String()) UpdateAccount(sqldb, s.From, newBalanceSender.String(), newAccountNonceSender.String())
}
return nil
} }
//writeFromBalance writes senders balance to accounts db func balanceHelper(sqldb *sql.DB, s stypes.SendAndReceive, amount string) {
func swriteFromBalance(sqldb *sql.DB, tx *types.Transaction) error { fromAddressBalance, fromAccountNonce, err := AccountExists(sqldb, s.From)
sendAndReceiveData := SendAndReceive{ toAddressBalance, toAccountNonce, err := AccountExists(sqldb, s.To)
To: tx.To().Hex(),
From: tx.From().Hex(),
Amount: tx.Value().String(),
}
toAddressBalance, toAccountNonce, err := AccountExists(sqldb, sendAndReceiveData.To)
switch {
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 { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
@ -268,26 +189,29 @@ func swriteFromBalance(sqldb *sql.DB, tx *types.Transaction) error {
//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)
fromBalance := new(big.Int) fromBalance := new(big.Int)
fromBalance, _ = fromBalance.SetString(fromAddressBalance, 10) fromBalance, _ = fromBalance.SetString(fromAddressBalance, 10)
amountValue := new(big.Int)
amountValue, _ = amountValue.SetString(amount, 10)
//ACCOUNT NONCES //ACCOUNT NONCES
toNonce := new(big.Int) toNonce := new(big.Int)
toNonce, _ = toNonce.SetString(toAccountNonce, 10) toNonce, _ = toNonce.SetString(toAccountNonce, 10)
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, amountValue)
newBalanceSender.Sub(fromBalance, tx.Value()) newBalanceSender.Sub(fromBalance, amountValue)
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
} }
// @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:
@ -378,19 +302,21 @@ func sstoreReward(sqldb *sql.DB, address string, reward *big.Int) {
/////////////////////// ///////////////////////
//DB Utility functions //DB Utility functions
////////////////////// //////////////////////
//CreateAccount writes new account to Postgres Db
func CreateAccount(sqldb *sql.DB, addr string, balance string, accountNonce string) { 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, balance, accountNonce).Scan(&addr) insertErr := sqldb.QueryRow(sqlStatement, strings.ToLower(addr), balance, accountNonce).Scan(&addr)
if insertErr != nil { if insertErr != nil {
panic(insertErr) panic(insertErr)
} }
} }
//AccountExists checks if account exists in Postgres Db
func AccountExists(sqldb *sql.DB, addr string) (string, string, error) { func AccountExists(sqldb *sql.DB, addr string) (string, string, error) {
var addressBalance, accountNonce string var addressBalance, accountNonce string
sqlExistsStatement := `SELECT balance, accountNonce from accounts WHERE addr = ($1)` sqlExistsStatement := `SELECT balance, accountNonce from accounts WHERE addr = ($1)`
err := sqldb.QueryRow(sqlExistsStatement, addr).Scan(&addressBalance, &accountNonce) err := sqldb.QueryRow(sqlExistsStatement, strings.ToLower(addr)).Scan(&addressBalance, &accountNonce)
switch { switch {
case err == sql.ErrNoRows: case err == sql.ErrNoRows:
return addressBalance, accountNonce, err return addressBalance, accountNonce, err
@ -401,30 +327,55 @@ func AccountExists (sqldb *sql.DB, addr string) (string, string, error) {
} }
} }
//BlockExists checks if block exists in Postgres Db
func BlockExists(sqldb *sql.DB, hash string) error {
var res string
sqlExistsStatement := `SELECT hash from blocks WHERE hash= ($1)`
err := sqldb.QueryRow(sqlExistsStatement, strings.ToLower(hash)).Scan(&res)
switch {
case err == sql.ErrNoRows:
return err
panic(err)
default:
return err
}
}
//UpdateAccount updates account in Postgres Db
func UpdateAccount(sqldb *sql.DB, addr string, balance string, accountNonce string) { func UpdateAccount(sqldb *sql.DB, addr string, balance string, accountNonce string) {
updateSQLStatement := `UPDATE accounts SET balance = ($2), accountNonce = ($3) WHERE addr = ($1)` updateSQLStatement := `UPDATE accounts SET balance = ($2), accountNonce = ($3) WHERE addr = ($1)`
_, updateErr := sqldb.Exec(updateSQLStatement, addr, balance, accountNonce) _, updateErr := sqldb.Exec(updateSQLStatement, strings.ToLower(addr), balance, accountNonce)
if updateErr != nil { if updateErr != nil {
panic(updateErr) panic(updateErr)
} }
} }
func InsertBlock(sqldb *sql.DB, blockData SBlock, blockAge SBlock) { //InsertBlock writes block to Postgres Db
func InsertBlock(sqldb *sql.DB, blockData stypes.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` 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) qerr := sqldb.QueryRow(sqlStatement, strings.ToLower(blockData.Hash), blockData.Coinbase, blockData.Number, blockData.GasUsed, blockData.GasLimit, blockData.TxCount, blockData.UncleCount, blockData.Age, blockData.ParentHash, blockData.UncleHash, blockData.Difficulty, blockData.Size, blockData.Rewards, blockData.Nonce).Scan(&blockData.Number)
if qerr != nil { if qerr != nil {
panic(qerr) panic(qerr)
} }
} }
//InsertTx writes tx to Postgres Db
func InsertTx (sqldb *sql.DB, txData ShyftTxEntryPretty, data ShyftTxEntryPretty) { func InsertTx(sqldb *sql.DB, txData stypes.ShyftTxEntryPretty) {
var retNonce string 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` 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) err := sqldb.QueryRow(sqlStatement, strings.ToLower(txData.TxHash), strings.ToLower(txData.From), strings.ToLower(txData.To.String()), strings.ToLower(txData.BlockHash), txData.BlockNumber, txData.Amount, txData.GasPrice, txData.Gas, txData.GasLimit, txData.Cost, txData.Nonce, txData.IsContract, txData.Status, txData.Age, txData.Data).Scan(&retNonce)
if err != nil { if err != nil {
panic(err) panic(err)
} }
} }
//InsertInternalTx writes internal tx to Postgres Db
func InsertInternalTx(sqldb *sql.DB, i stypes.InteralWrite) {
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, strings.ToLower(i.Hash), strings.ToLower(i.From), strings.ToLower(i.To), i.Value, i.Gas, i.GasUsed, i.Time, i.Input, i.Output).Scan(&returnValue)
if qerr != nil {
fmt.Println(qerr)
panic(qerr)
}
}

View file

@ -1,17 +1,19 @@
package core package core
import ( import (
"encoding/json"
"database/sql" "database/sql"
"encoding/json"
"fmt" "fmt"
"time" "time"
stypes "github.com/ShyftNetwork/go-empyrean/core/sTypes"
) )
/////////// ///////////
// Getters // Getters
////////// //////////
func SGetAllBlocks(sqldb *sql.DB) string { func SGetAllBlocks(sqldb *sql.DB) string {
var arr blockRes var arr stypes.BlockRes
var blockArr string var blockArr string
rows, err := sqldb.Query(`SELECT * FROM blocks`) rows, err := sqldb.Query(`SELECT * FROM blocks`)
if err != nil { if err != nil {
@ -25,9 +27,9 @@ func SGetAllBlocks(sqldb *sql.DB) string {
var txCount, uncleCount int var txCount, uncleCount int
err = rows.Scan( err = rows.Scan(
&hash, &coinbase, &gasUsed, &gasLimit, &txCount, &uncleCount, &age, &parentHash, &uncleHash, &difficulty, &size, &nonce, &rewards, &num,) &hash, &coinbase, &gasUsed, &gasLimit, &txCount, &uncleCount, &age, &parentHash, &uncleHash, &difficulty, &size, &nonce, &rewards, &num)
arr.Blocks = append(arr.Blocks, SBlock{ arr.Blocks = append(arr.Blocks, stypes.SBlock{
Hash: hash, Hash: hash,
Coinbase: coinbase, Coinbase: coinbase,
GasUsed: gasUsed, GasUsed: gasUsed,
@ -61,9 +63,9 @@ func SGetBlock(sqldb *sql.DB, blockNumber string) string {
var txCount, uncleCount int var txCount, uncleCount int
row.Scan( row.Scan(
&hash, &coinbase, &gasUsed, &gasLimit, &txCount, &uncleCount, &age, &parentHash, &uncleHash, &difficulty, &size, &nonce, &rewards, &num,) &hash, &coinbase, &gasUsed, &gasLimit, &txCount, &uncleCount, &age, &parentHash, &uncleHash, &difficulty, &size, &nonce, &rewards, &num)
block := SBlock{ block := stypes.SBlock{
Hash: hash, Hash: hash,
Coinbase: coinbase, Coinbase: coinbase,
GasUsed: gasUsed, GasUsed: gasUsed,
@ -91,9 +93,9 @@ func SGetRecentBlock(sqldb *sql.DB) string {
var txCount, uncleCount int var txCount, uncleCount int
row.Scan( row.Scan(
&hash, &coinbase, &gasUsed, &gasLimit, &txCount, &uncleCount, &age, &parentHash, &uncleHash, &difficulty, &size, &nonce, &rewards, &num,) &hash, &coinbase, &gasUsed, &gasLimit, &txCount, &uncleCount, &age, &parentHash, &uncleHash, &difficulty, &size, &nonce, &rewards, &num)
block := SBlock{ block := stypes.SBlock{
Hash: hash, Hash: hash,
Coinbase: coinbase, Coinbase: coinbase,
GasUsed: gasUsed, GasUsed: gasUsed,
@ -114,7 +116,7 @@ func SGetRecentBlock(sqldb *sql.DB) string {
} }
func SGetAllTransactionsFromBlock(sqldb *sql.DB, blockNumber string) string { func SGetAllTransactionsFromBlock(sqldb *sql.DB, blockNumber string) string {
var arr txRes var arr stypes.TxRes
var txx string var txx string
sqlStatement := `SELECT * FROM txs WHERE blocknumber=$1` sqlStatement := `SELECT * FROM txs WHERE blocknumber=$1`
rows, err := sqldb.Query(sqlStatement, blockNumber) rows, err := sqldb.Query(sqlStatement, blockNumber)
@ -133,7 +135,7 @@ func SGetAllTransactionsFromBlock(sqldb *sql.DB, blockNumber string) string {
&txhash, &to_addr, &from_addr, &blockhash, &blocknumber, &amount, &gasprice, &gas, &gasLimit, &txfee, &nonce, &status, &isContract, &age, &data, &txhash, &to_addr, &from_addr, &blockhash, &blocknumber, &amount, &gasprice, &gas, &gasLimit, &txfee, &nonce, &status, &isContract, &age, &data,
) )
arr.TxEntry = append(arr.TxEntry, ShyftTxEntryPretty{ arr.TxEntry = append(arr.TxEntry, stypes.ShyftTxEntryPretty{
TxHash: txhash, TxHash: txhash,
ToGet: to_addr, ToGet: to_addr,
From: from_addr, From: from_addr,
@ -159,7 +161,7 @@ func SGetAllTransactionsFromBlock(sqldb *sql.DB, blockNumber string) string {
} }
func SGetAllBlocksMinedByAddress(sqldb *sql.DB, coinbase string) string { func SGetAllBlocksMinedByAddress(sqldb *sql.DB, coinbase string) string {
var arr blockRes var arr stypes.BlockRes
var blockArr string var blockArr string
sqlStatement := `SELECT * FROM blocks WHERE coinbase=$1` sqlStatement := `SELECT * FROM blocks WHERE coinbase=$1`
rows, err := sqldb.Query(sqlStatement, coinbase) rows, err := sqldb.Query(sqlStatement, coinbase)
@ -174,9 +176,9 @@ func SGetAllBlocksMinedByAddress(sqldb *sql.DB, coinbase string) string {
var txCount, uncleCount int var txCount, uncleCount int
err = rows.Scan( err = rows.Scan(
&hash, &coinbase, &gasUsed, &gasLimit, &txCount, &uncleCount, &age, &parentHash, &uncleHash, &difficulty, &size, &nonce, &rewards, &num,) &hash, &coinbase, &gasUsed, &gasLimit, &txCount, &uncleCount, &age, &parentHash, &uncleHash, &difficulty, &size, &nonce, &rewards, &num)
arr.Blocks = append(arr.Blocks, SBlock{ arr.Blocks = append(arr.Blocks, stypes.SBlock{
Hash: hash, Hash: hash,
Coinbase: coinbase, Coinbase: coinbase,
GasUsed: gasUsed, GasUsed: gasUsed,
@ -202,7 +204,7 @@ func SGetAllBlocksMinedByAddress(sqldb *sql.DB, coinbase string) string {
//GetAllTransactions getter fn for API //GetAllTransactions getter fn for API
func SGetAllTransactions(sqldb *sql.DB) string { func SGetAllTransactions(sqldb *sql.DB) string {
var arr txRes var arr stypes.TxRes
var txx string var txx string
rows, err := sqldb.Query(`SELECT * FROM txs`) rows, err := sqldb.Query(`SELECT * FROM txs`)
if err != nil { if err != nil {
@ -220,7 +222,7 @@ func SGetAllTransactions(sqldb *sql.DB) string {
&txhash, &to_addr, &from_addr, &blockhash, &blocknumber, &amount, &gasprice, &gas, &gasLimit, &txfee, &nonce, &status, &isContract, &age, &data, &txhash, &to_addr, &from_addr, &blockhash, &blocknumber, &amount, &gasprice, &gas, &gasLimit, &txfee, &nonce, &status, &isContract, &age, &data,
) )
arr.TxEntry = append(arr.TxEntry, ShyftTxEntryPretty{ arr.TxEntry = append(arr.TxEntry, stypes.ShyftTxEntryPretty{
TxHash: txhash, TxHash: txhash,
ToGet: to_addr, ToGet: to_addr,
From: from_addr, From: from_addr,
@ -258,7 +260,7 @@ func SGetTransaction(sqldb *sql.DB, txHash string) string {
row.Scan( row.Scan(
&txhash, &to_addr, &from_addr, &blockhash, &blocknumber, &amount, &gasprice, &gas, &gasLimit, &txfee, &nonce, &status, &isContract, &age, &data) &txhash, &to_addr, &from_addr, &blockhash, &blocknumber, &amount, &gasprice, &gas, &gasLimit, &txfee, &nonce, &status, &isContract, &age, &data)
tx := ShyftTxEntryPretty{ tx := stypes.ShyftTxEntryPretty{
TxHash: txhash, TxHash: txhash,
ToGet: to_addr, ToGet: to_addr,
From: from_addr, From: from_addr,
@ -280,14 +282,14 @@ func SGetTransaction(sqldb *sql.DB, txHash string) string {
return string(json) return string(json)
} }
func InnerSGetAccount(sqldb *sql.DB, address string) (SAccounts, bool) { func InnerSGetAccount(sqldb *sql.DB, address string) (stypes.SAccounts, bool) {
sqlStatement := `SELECT * FROM accounts WHERE addr=$1;` sqlStatement := `SELECT * FROM accounts WHERE addr=$1;`
var addr, balance, accountNonce string var addr, balance, accountNonce string
err := sqldb.QueryRow(sqlStatement, address).Scan(&addr, &balance, &accountNonce) err := sqldb.QueryRow(sqlStatement, address).Scan(&addr, &balance, &accountNonce)
if err == sql.ErrNoRows { if err == sql.ErrNoRows {
return SAccounts{}, false return stypes.SAccounts{}, false
} else { } else {
account := SAccounts{ account := stypes.SAccounts{
Addr: addr, Addr: addr,
Balance: balance, Balance: balance,
AccountNonce: accountNonce, AccountNonce: accountNonce,
@ -305,7 +307,7 @@ func SGetAccount(sqldb *sql.DB, address string) string {
//GetAllAccounts returns all accounts and balances //GetAllAccounts returns all accounts and balances
func SGetAllAccounts(sqldb *sql.DB) string { func SGetAllAccounts(sqldb *sql.DB) string {
var array accountRes var array stypes.AccountRes
var accountsArr, accountNonce string var accountsArr, accountNonce string
accs, err := sqldb.Query(` accs, err := sqldb.Query(`
@ -326,7 +328,7 @@ func SGetAllAccounts(sqldb *sql.DB) string {
&addr, &balance, &accountNonce, &addr, &balance, &accountNonce,
) )
array.AllAccounts = append(array.AllAccounts, SAccounts{ array.AllAccounts = append(array.AllAccounts, stypes.SAccounts{
Addr: addr, Addr: addr,
Balance: balance, Balance: balance,
AccountNonce: accountNonce, AccountNonce: accountNonce,
@ -341,7 +343,7 @@ func SGetAllAccounts(sqldb *sql.DB) string {
//GetAccount returns account balances //GetAccount returns account balances
func SGetAccountTxs(sqldb *sql.DB, address string) string { func SGetAccountTxs(sqldb *sql.DB, address string) string {
var arr txRes var arr stypes.TxRes
var txx string var txx string
sqlStatement := `SELECT * FROM txs WHERE to_addr=$1 OR from_addr=$1;` sqlStatement := `SELECT * FROM txs WHERE to_addr=$1 OR from_addr=$1;`
rows, err := sqldb.Query(sqlStatement, address) rows, err := sqldb.Query(sqlStatement, address)
@ -360,7 +362,7 @@ func SGetAccountTxs(sqldb *sql.DB, address string) string {
&txhash, &to_addr, &from_addr, &blockhash, &blocknumber, &amount, &gasprice, &gas, &gasLimit, &txfee, &nonce, &status, &isContract, &age, &data, &txhash, &to_addr, &from_addr, &blockhash, &blocknumber, &amount, &gasprice, &gas, &gasLimit, &txfee, &nonce, &status, &isContract, &age, &data,
) )
arr.TxEntry = append(arr.TxEntry, ShyftTxEntryPretty{ arr.TxEntry = append(arr.TxEntry, stypes.ShyftTxEntryPretty{
TxHash: txhash, TxHash: txhash,
ToGet: to_addr, ToGet: to_addr,
From: from_addr, From: from_addr,

View file

@ -631,8 +631,6 @@ func (api *PrivateDebugAPI) StraceTx(ctx context.Context, message core.Message,
} }
} }
// traceTx configures a new tracer according to the provided configuration, and // traceTx configures a new tracer according to the provided configuration, and
// executes the given message in the provided environment. The return value will // executes the given message in the provided environment. The return value will
// be tracer dependent. // be tracer dependent.

View file

@ -1,10 +1,11 @@
package eth package eth
import ( import (
"context"
"fmt"
"github.com/ShyftNetwork/go-empyrean/common" "github.com/ShyftNetwork/go-empyrean/common"
"github.com/ShyftNetwork/go-empyrean/params" "github.com/ShyftNetwork/go-empyrean/params"
"context"
) )
var EthereumObject interface{} var EthereumObject interface{}

View file

@ -25,14 +25,16 @@ import (
"time" "time"
"unsafe" "unsafe"
"strconv"
"github.com/ShyftNetwork/go-empyrean/common" "github.com/ShyftNetwork/go-empyrean/common"
"github.com/ShyftNetwork/go-empyrean/common/hexutil" "github.com/ShyftNetwork/go-empyrean/common/hexutil"
"github.com/ShyftNetwork/go-empyrean/core" "github.com/ShyftNetwork/go-empyrean/core"
stypes "github.com/ShyftNetwork/go-empyrean/core/sTypes"
"github.com/ShyftNetwork/go-empyrean/core/vm" "github.com/ShyftNetwork/go-empyrean/core/vm"
"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.
@ -603,14 +605,21 @@ func (i *Internals) SWriteInteralTxs(hash common.Hash) {
value, _ := hexutil.DecodeUint64(i.Value) value, _ := hexutil.DecodeUint64(i.Value)
amount := strconv.FormatUint(value, 10) amount := strconv.FormatUint(value, 10)
var returnValue string iTx := stypes.InteralWrite{
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` Hash: hash.Hex(),
qerr := sqldb.QueryRow(sqlStatement, i.Type, hash.Hex(), i.From, i.To, amount, gas, gasUsed, i.Time, i.Input, i.Output).Scan(&returnValue) Type: i.Type,
From: i.From,
if qerr != nil { To: i.To,
fmt.Println(qerr) Value: amount,
panic(qerr) Gas: gas,
GasUsed: gasUsed,
Input: i.Input,
Output: i.Output,
Time: i.Time,
} }
//@TODO WRITE OVER TRANSACTION STRUCT
core.SWriteInternalTxBalances(sqldb, i.To, i.From, amount)
core.InsertInternalTx(sqldb, iTx)
} }
//@NOTE:SHYFT //@NOTE:SHYFT

View file

@ -7,11 +7,12 @@ import (
_ "github.com/lib/pq" _ "github.com/lib/pq"
"bytes"
"encoding/json"
"io/ioutil"
"github.com/ShyftNetwork/go-empyrean/core" "github.com/ShyftNetwork/go-empyrean/core"
"github.com/gorilla/mux" "github.com/gorilla/mux"
"bytes"
"io/ioutil"
"encoding/json"
) )
// GetTransaction gets txs // GetTransaction gets txs
@ -239,7 +240,7 @@ func BroadcastTx(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "ERROR parsing json") fmt.Fprintln(w, "ERROR parsing json")
} }
tx_hash := dat["result"] tx_hash := dat["result"]
if(tx_hash == nil) { if tx_hash == nil {
errMap := dat["error"].(map[string]interface{}) errMap := dat["error"].(map[string]interface{})
w.Header().Set("Content-Type", "application/json; charset=UTF-8") w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)

View file

@ -21,7 +21,6 @@ class AccountTable extends Component {
} }
render() { render() {
let startNum = 1; let startNum = 1;
const sorted = [...this.state.data]; const sorted = [...this.state.data];
sorted.sort((a, b) => Number(a.Balance) > Number(b.Balance)); sorted.sort((a, b) => Number(a.Balance) > Number(b.Balance));
@ -38,7 +37,7 @@ class AccountTable extends Component {
Percentage={percentage.toFixed(2)} Percentage={percentage.toFixed(2)}
Addr={data.Addr} Addr={data.Addr}
Balance={conversion} Balance={conversion}
AcountNonce={data.AccountNonce} AccountNonce={data.AccountNonce}
detailAccountHandler={this.props.detailAccountHandler} detailAccountHandler={this.props.detailAccountHandler}
/> />
}); });

View file

@ -17,7 +17,7 @@ class AccountTransactionTable extends Component {
age={data.Age} age={data.Age}
txHash={data.TxHash} txHash={data.TxHash}
blockNumber={data.BlockNumber} blockNumber={data.BlockNumber}
to={data.To} to={data.ToGet}
from={data.From} from={data.From}
value={amountConversion} value={amountConversion}
cost={costConversion} cost={costConversion}

View file

@ -30,7 +30,7 @@ class BlocksTable extends Component {
Hash={data.Hash} Hash={data.Hash}
Number={data.Number} Number={data.Number}
Coinbase={data.Coinbase} Coinbase={data.Coinbase}
Age={data.Age} AgeGet={data.AgeGet}
GasUsed={data.GasUsed} GasUsed={data.GasUsed}
GasLimit={data.GasLimit} GasLimit={data.GasLimit}
UncleCount={data.UncleCount} UncleCount={data.UncleCount}

View file

@ -10,7 +10,7 @@ const BlockTable = (props) => {
{props.Number} {props.Number}
</Link></td> </Link></td>
<td className={classes.addressTag}>{props.Hash}</td> <td className={classes.addressTag}>{props.Hash}</td>
<td>{props.Age}</td> <td>{props.AgeGet}</td>
<td>{props.TxCount}</td> <td>{props.TxCount}</td>
<td>{props.UncleCount}</td> <td>{props.UncleCount}</td>
<td className={classes.addressTag}><Link to="/mined/blocks" onClick={() => props.getBlocksMined(props.Coinbase)}>{props.Coinbase}</Link></td> <td className={classes.addressTag}><Link to="/mined/blocks" onClick={() => props.getBlocksMined(props.Coinbase)}>{props.Coinbase}</Link></td>

View file

@ -16,7 +16,7 @@ class DetailBlockTable extends Component {
</tr> </tr>
<tr> <tr>
<th scope="col">Age:</th> <th scope="col">Age:</th>
<td>{data.Age}</td> <td>{data.AgeGet}</td>
</tr> </tr>
<tr> <tr>
<th scope="col">Txn:</th> <th scope="col">Txn:</th>

View file

@ -19,7 +19,7 @@ class BlocksMinedTable extends Component {
Hash={data.Hash} Hash={data.Hash}
Number={data.Number} Number={data.Number}
Coinbase={data.Coinbase} Coinbase={data.Coinbase}
Age={data.Age} AgeGet={data.AgeGet}
GasUsed={data.GasUsed} GasUsed={data.GasUsed}
GasLimit={data.GasLimit} GasLimit={data.GasLimit}
UncleCount={data.UncleCount} UncleCount={data.UncleCount}

View file

@ -10,7 +10,7 @@ const MinedBlockTable = (props) => {
{props.Number} {props.Number}
</Link></td> </Link></td>
<td className={classes.addressTag}>{props.Hash}</td> <td className={classes.addressTag}>{props.Hash}</td>
<td>{props.Age}</td> <td>{props.AgeGet}</td>
<td>{props.TxCount}</td> <td>{props.TxCount}</td>
<td>{props.UncleCount}</td> <td>{props.UncleCount}</td>
<td className={classes.addressTag}>{props.Coinbase}</td> <td className={classes.addressTag}>{props.Coinbase}</td>

View file

@ -32,7 +32,7 @@ class DetailTransactionTable extends Component {
</tr> </tr>
<tr> <tr>
<th scope="col">To:</th> <th scope="col">To:</th>
<td>{ `${data.IsContract}` ? `${data.To} (Contract)` : `${data.To}` }</td> <td>{ `${data.IsContract}` ? `${data.ToGet} (Contract)` : `${data.ToGet}` }</td>
</tr> </tr>
<tr> <tr>
<th scope="col">Value:</th> <th scope="col">Value:</th>

View file

@ -31,7 +31,7 @@ class TransactionTable extends Component {
age={data.Age} age={data.Age}
txHash={data.TxHash} txHash={data.TxHash}
blockNumber={data.BlockNumber} blockNumber={data.BlockNumber}
to={data.To} to={data.ToGet}
from={data.From} from={data.From}
value={data.Amount} value={data.Amount}
cost={conversion} cost={conversion}

View file

@ -16,7 +16,7 @@ CREATE TABLE IF NOT EXISTS blocks (
); );
CREATE TABLE IF NOT EXISTS txs ( CREATE TABLE IF NOT EXISTS txs (
txHash text, txHash text primary key unique,
to_addr text, to_addr text,
from_addr text, from_addr text,
blockhash text references blocks(hash), blockhash text references blocks(hash),
@ -36,5 +36,19 @@ CREATE TABLE IF NOT EXISTS txs (
CREATE TABLE IF NOT EXISTS accounts ( CREATE TABLE IF NOT EXISTS accounts (
addr text primary key unique, addr text primary key unique,
balance numeric, balance numeric,
accountnonce numeric accountNonce numeric
); );
CREATE TABLE IF NOT EXISTS internalTxs (
id SERIAL PRIMARY KEY,
txHash text references txs(txHash),
type text,
to_addr text,
from_addr text,
amount text,
gas numeric,
gasUsed numeric,
time text,
input text,
output text
)

View file

@ -1,3 +1,4 @@
DROP TABLE internalTxs;
DROP TABLE txs; DROP TABLE txs;
DROP TABLE blocks; DROP TABLE blocks;
DROP TABLE accounts; DROP TABLE accounts;

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{}
@ -21,10 +23,11 @@ const (
) )
func TestBlock(t *testing.T) { func TestBlock(t *testing.T) {
//SET UP FOR TEST FUNCTIONS
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,19 +40,25 @@ func TestBlock(t *testing.T) {
eth.SetGlobalConfig(ethConf) eth.SetGlobalConfig(ethConf)
eth.InitTracerEnv() eth.InitTracerEnv()
core.ClearTables()
t.Run("TestBlockToReturnBlock", func(t *testing.T) {
key, _ := crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") key, _ := crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
signer := types.NewEIP155Signer(big.NewInt(2147483647)) signer := types.NewEIP155Signer(big.NewInt(2147483647))
//Nonce, To Address,Value, GasLimit, Gasprice, data //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, common.BytesToAddress([]byte{0x11}), big.NewInt(5), 1111, big.NewInt(11111), []byte{0x11, 0x11, 0x11})
mytx,_ := types.SignTx(tx1, signer, key) mytx1, _ := 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, 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, common.BytesToAddress([]byte{0x33}), 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{mytx1, mytx2}
txs1 := []*types.Transaction{mytx3}
//Nonce,Value, GasLimit, Gasprice, data
contractCreation := types.NewContractCreation(1, big.NewInt(111), 1111, big.NewInt(11111), []byte{0x11, 0x11, 0x11})
mytx4, _ := types.SignTx(contractCreation, signer, key)
txs2 := []*types.Transaction{mytx4}
receipt := &types.Receipt{ receipt := &types.Receipt{
Status: types.ReceiptStatusSuccessful, Status: types.ReceiptStatusSuccessful,
@ -62,102 +71,25 @@ func TestBlock(t *testing.T) {
ContractAddress: common.BytesToAddress([]byte{0x01, 0x11, 0x11}), ContractAddress: common.BytesToAddress([]byte{0x01, 0x11, 0x11}),
GasUsed: 111111, GasUsed: 111111,
} }
receipts := []*types.Receipt{receipt} receipts := []*types.Receipt{receipt}
block := types.NewBlock(&types.Header{Number: big.NewInt(315)}, txs, nil, receipts)
// Write and verify the block in the database block1 := types.NewBlock(&types.Header{Number: big.NewInt(323)}, txs, nil, receipts)
if err := core.SWriteBlock(block, receipts); err != nil { block2 := types.NewBlock(&types.Header{Number: big.NewInt(320)}, txs1, nil, receipts)
t.Fatalf("Failed to write block into database: %v", err) block3 := types.NewBlock(&types.Header{Number: big.NewInt(322)}, txs2, nil, receipts)
} blocks := []*types.Block{block1, block2, block3}
sqldb, err := core.DBConnection() sqldb, err := core.DBConnection()
if err != nil { if err != nil {
panic(err) panic(err)
} }
entry := core.SGetBlock(sqldb, block.Number().String()) fromAddr := "0x71562b71999873db5b286df957af199ec94617f7"
byt := []byte(entry) fromAddrEndBalance := "75"
var data core.SBlock fromAddrEndNonce := "5"
json.Unmarshal(byt, &data) toAddr := common.BytesToAddress([]byte{0x11})
core.CreateAccount(sqldb, fromAddr, "201", "1")
//TODO Difficulty, rewards, age
if block.Hash().String() != data.Hash {
t.Fatalf("Block Hash [%v]: Block hash not found", block.Hash().String())
}
if block.Coinbase().String() != data.Coinbase {
t.Fatalf("Block coinbase [%v]: Block coinbase not found", block.Coinbase().String())
}
if block.Number().String() != data.Number {
t.Fatalf("Block number [%v]: Block number not found", block.Number().String())
}
if block.GasUsed() != data.GasUsed {
t.Fatalf("Gas Used [%v]: Gas used not found", block.GasUsed())
}
if block.GasLimit() != data.GasLimit {
t.Fatalf("Gas Limit [%v]: Gas limit not found", block.GasLimit())
}
if block.Transactions().Len() != data.TxCount {
t.Fatalf("Tx Count [%v]: Tx Count not found", block.Transactions().Len())
}
if len(block.Uncles()) != data.UncleCount {
t.Fatalf("Uncle count [%v]: Uncle count not found", len(block.Uncles()))
}
if block.ParentHash().String() != data.ParentHash {
t.Fatalf("Parent hash [%v]: Parent hash not found", block.ParentHash().String())
}
if block.UncleHash().String() != data.UncleHash {
t.Fatalf("Uncle hash [%v]: Uncle hash not found", block.UncleHash().String())
}
if block.Size().String() != data.Size {
t.Fatalf("Size [%v]: Size not found", block.Size().String())
}
if block.Nonce() != data.Nonce {
t.Fatalf("Block nonce [%v]: Block nonce not found", block.Nonce())
}
if getAllBlocks := core.SGetAllBlocks(sqldb); len(getAllBlocks) == 0 {
t.Fatalf("GetAllBlocks [%v]: GetAllBlocks did not return correctly", getAllBlocks)
}
if getAllBlocksMinedByAddress := core.SGetAllBlocksMinedByAddress(sqldb, block.Coinbase().String()); len(getAllBlocksMinedByAddress) == 0 {
t.Fatalf("GetAllBlocksMinedByAddress [%v]: GetAllBlocksMinedByAddress did not return correctly", getAllBlocksMinedByAddress)
}
ClearTables()
})
t.Run("TestGetRecentBlock", func(t *testing.T) {
key, _ := crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
signer := types.NewEIP155Signer(big.NewInt(2147483647))
//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})
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})
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})
mytx3,_ := types.SignTx(tx3, signer, key)
txs := []*types.Transaction{mytx, mytx2}
txs1 := []*types.Transaction{mytx3}
receipt1 := &types.Receipt{
Status: types.ReceiptStatusSuccessful,
CumulativeGasUsed: 1,
Logs: []*types.Log{
{Address: common.BytesToAddress([]byte{0x11})},
{Address: common.BytesToAddress([]byte{0x01, 0x11})},
},
TxHash: common.BytesToHash([]byte{0x11, 0x11}),
ContractAddress: common.BytesToAddress([]byte{0x01, 0x11, 0x11}),
GasUsed: 111111,
}
receipts := []*types.Receipt{receipt1}
block := types.NewBlock(&types.Header{Number: big.NewInt(322)}, txs, nil, receipts)
block2 := types.NewBlock(&types.Header{Number: big.NewInt(320)}, txs1, nil, receipts)
blocks := []*types.Block{block, block2}
t.Run("TestBlockToReturnBlock", func(t *testing.T) {
for _, bc := range blocks { for _, bc := range blocks {
// Write and verify the block in the database // Write and verify the block in the database
if err := core.SWriteBlock(bc, receipts); err != nil { if err := core.SWriteBlock(bc, receipts); err != nil {
@ -165,96 +97,107 @@ func TestBlock(t *testing.T) {
} }
} }
sqldb, err := core.DBConnection() entry := core.SGetBlock(sqldb, block1.Number().String())
if (err != nil) { byt := []byte(entry)
panic(err) var data core.SBlock
json.Unmarshal(byt, &data)
//TODO Difficulty, rewards, age
if block1.Hash().String() != data.Hash {
t.Fatalf("Block Hash [%v]: Block hash not found", block1.Hash().String())
}
if block1.Coinbase().String() != data.Coinbase {
t.Fatalf("Block coinbase [%v]: Block coinbase not found", block1.Coinbase().String())
}
if block1.Number().String() != data.Number {
t.Fatalf("Block number [%v]: Block number not found", block1.Number().String())
}
if block1.GasUsed() != data.GasUsed {
t.Fatalf("Gas Used [%v]: Gas used not found", block1.GasUsed())
}
if block1.GasLimit() != data.GasLimit {
t.Fatalf("Gas Limit [%v]: Gas limit not found", block1.GasLimit())
}
if block1.Transactions().Len() != data.TxCount {
t.Fatalf("Tx Count [%v]: Tx Count not found", block1.Transactions().Len())
}
if len(block1.Uncles()) != data.UncleCount {
t.Fatalf("Uncle count [%v]: Uncle count not found", len(block1.Uncles()))
}
if block1.ParentHash().String() != data.ParentHash {
t.Fatalf("Parent hash [%v]: Parent hash not found", block1.ParentHash().String())
}
if block1.UncleHash().String() != data.UncleHash {
t.Fatalf("Uncle hash [%v]: Uncle hash not found", block1.UncleHash().String())
}
if block1.Size().String() != data.Size {
t.Fatalf("Size [%v]: Size not found", block1.Size().String())
}
if block1.Nonce() != data.Nonce {
t.Fatalf("Block nonce [%v]: Block nonce not found", block1.Nonce())
} }
if getAllBlocks := core.SGetAllBlocks(sqldb); len(getAllBlocks) == 0 {
t.Fatalf("GetAllBlocks [%v]: GetAllBlocks did not return correctly", getAllBlocks)
}
if getAllBlocksMinedByAddress := core.SGetAllBlocksMinedByAddress(sqldb, block1.Coinbase().String()); len(getAllBlocksMinedByAddress) == 0 {
t.Fatalf("GetAllBlocksMinedByAddress [%v]: GetAllBlocksMinedByAddress did not return correctly", getAllBlocksMinedByAddress)
}
})
t.Run("TestGetRecentBlock", func(t *testing.T) {
response := core.SGetRecentBlock(sqldb) response := core.SGetRecentBlock(sqldb)
byteRes := []byte(response) byteRes := []byte(response)
var recentBlock core.SBlock var recentBlock core.SBlock
json.Unmarshal(byteRes, &recentBlock) json.Unmarshal(byteRes, &recentBlock)
if block.Hash().String() != recentBlock.Hash { if block1.Hash().String() != recentBlock.Hash {
t.Fatalf("Block Hash [%v]: Block hash not found", block.Hash().String()) t.Fatalf("Block Hash [%v]: Block hash not found", block1.Hash().String())
} }
if block.Coinbase().String() != recentBlock.Coinbase { if block1.Coinbase().String() != recentBlock.Coinbase {
t.Fatalf("Block coinbase [%v]: Block coinbase not found", block.Coinbase().String()) t.Fatalf("Block coinbase [%v]: Block coinbase not found", block1.Coinbase().String())
} }
if block.Number().String() != recentBlock.Number { if block1.Number().String() != recentBlock.Number {
t.Fatalf("Block number [%v]: Block number not found", block.Number().String()) t.Fatalf("Block number [%v]: Block number not found", block1.Number().String())
} }
if block.GasUsed() != recentBlock.GasUsed { if block1.GasUsed() != recentBlock.GasUsed {
t.Fatalf("Gas Used [%v]: Gas used not found", block.GasUsed()) t.Fatalf("Gas Used [%v]: Gas used not found", block1.GasUsed())
} }
if block.GasLimit() != recentBlock.GasLimit { if block1.GasLimit() != recentBlock.GasLimit {
t.Fatalf("Gas Limit [%v]: Gas limit not found", block.GasLimit()) t.Fatalf("Gas Limit [%v]: Gas limit not found", block1.GasLimit())
} }
if block.Transactions().Len() != recentBlock.TxCount { if block1.Transactions().Len() != recentBlock.TxCount {
t.Fatalf("Tx Count [%v]: Tx Count not found", block.Transactions().Len()) t.Fatalf("Tx Count [%v]: Tx Count not found", block1.Transactions().Len())
} }
if len(block.Uncles()) != recentBlock.UncleCount { if len(block1.Uncles()) != recentBlock.UncleCount {
t.Fatalf("Uncle count [%v]: Uncle count not found", len(block.Uncles())) t.Fatalf("Uncle count [%v]: Uncle count not found", len(block1.Uncles()))
} }
if block.ParentHash().String() != recentBlock.ParentHash { if block1.ParentHash().String() != recentBlock.ParentHash {
t.Fatalf("Parent hash [%v]: Parent hash not found", block.ParentHash().String()) t.Fatalf("Parent hash [%v]: Parent hash not found", block1.ParentHash().String())
} }
if block.UncleHash().String() != recentBlock.UncleHash { if block1.UncleHash().String() != recentBlock.UncleHash {
t.Fatalf("Uncle hash [%v]: Uncle hash not found", block.UncleHash().String()) t.Fatalf("Uncle hash [%v]: Uncle hash not found", block1.UncleHash().String())
} }
if block.Size().String() != recentBlock.Size { if block1.Size().String() != recentBlock.Size {
t.Fatalf("Size [%v]: Size not found", block.Size().String()) t.Fatalf("Size [%v]: Size not found", block1.Size().String())
} }
if block.Nonce() != recentBlock.Nonce { if block1.Nonce() != recentBlock.Nonce {
t.Fatalf("Block nonce [%v]: Block nonce not found", block.Nonce()) t.Fatalf("Block nonce [%v]: Block nonce not found", block1.Nonce())
} }
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()
}) })
//
t.Run("TestContractCreationTx", func(t *testing.T) { t.Run("TestContractCreationTx", func(t *testing.T) {
key, _ := crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
signer := types.NewEIP155Signer(big.NewInt(2147483647))
//Nonce,Value, GasLimit, Gasprice, data
contractCreation := types.NewContractCreation(1, big.NewInt(111), 1111, big.NewInt(11111), []byte{0x11, 0x11, 0x11})
mytx,_ := types.SignTx(contractCreation, signer, key)
txs := []*types.Transaction{mytx}
receipt2 := &types.Receipt{
Status: types.ReceiptStatusSuccessful,
CumulativeGasUsed: 1,
Logs: []*types.Log{
{Address: common.BytesToAddress([]byte{0x11})},
{Address: common.BytesToAddress([]byte{0x01, 0x11})},
},
TxHash: common.BytesToHash([]byte{0x11, 0x11}),
ContractAddress: common.BytesToAddress([]byte{0x01, 0x11, 0x11}),
GasUsed: 111111,
}
receipts := []*types.Receipt{receipt2}
block := types.NewBlock(&types.Header{Number: big.NewInt(314)}, txs, nil, receipts)
if err := core.SWriteBlock(block, receipts); err != nil {
t.Fatalf("Failed to write block into database: %v", err)
}
var contractAddressFromReciept string var contractAddressFromReciept string
for _, receipt := range receipts { for _, receipt := range receipts {
contractAddressFromReciept = (*types.ReceiptForStorage)(receipt).ContractAddress.String() contractAddressFromReciept = (*types.ReceiptForStorage)(receipt).ContractAddress.String()
} }
sqldb, err := core.DBConnection() for _, tx := range txs2 {
if (err != nil) {
panic(err)
}
for _, tx := range txs {
txn := core.SGetTransaction(sqldb, tx.Hash().String()) txn := core.SGetTransaction(sqldb, tx.Hash().String())
byt := []byte(txn) byt := []byte(txn)
var data core.ShyftTxEntryPretty var data core.ShyftTxEntryPretty
@ -266,7 +209,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 {
@ -278,14 +221,14 @@ t.Run("TestContractCreationTx", func (t *testing.T) {
if tx.GasPrice().Uint64() != data.GasPrice { if tx.GasPrice().Uint64() != data.GasPrice {
t.Fatalf("Gas Price [%v]: Gas price not found", tx.GasPrice().String()) t.Fatalf("Gas Price [%v]: Gas price not found", tx.GasPrice().String())
} }
if block.GasLimit() != data.GasLimit { if block1.GasLimit() != data.GasLimit {
t.Fatalf("Gas Limit [%v]: Gas limit not found", block.GasLimit()) t.Fatalf("Gas Limit [%v]: Gas limit not found", block1.GasLimit())
} }
if block.Hash().String() != data.BlockHash { if block3.Hash().String() != data.BlockHash {
t.Fatalf("Block Hash [%v]: Block hash not found", block.Hash().String()) t.Fatalf("Block Hash [%v]: Block hash not found", block1.Hash().String())
} }
if block.Number().String() != data.BlockNumber { if block3.Number().String() != data.BlockNumber {
t.Fatalf("Block Number [%v]: Block number not found", block.Number().String()) t.Fatalf("Block Number [%v]: Block number not found", block1.Number().String())
} }
if tx.Value().String() != data.Amount { if tx.Value().String() != data.Amount {
t.Fatalf("Amount [%v]: Amount not found", tx.Value().String()) t.Fatalf("Amount [%v]: Amount not found", tx.Value().String())
@ -294,10 +237,10 @@ t.Run("TestContractCreationTx", func (t *testing.T) {
t.Fatalf("Cost [%v]: Cost not found", tx.Cost().String()) t.Fatalf("Cost [%v]: Cost not found", tx.Cost().String())
} }
var status string var status string
if receipt2.Status == 1 { if receipt.Status == 1 {
status = "SUCCESS" status = "SUCCESS"
} }
if receipt2.Status == 0 { if receipt.Status == 0 {
status = "FAIL" status = "FAIL"
} }
if status != data.Status { if status != data.Status {
@ -313,45 +256,9 @@ 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()
}) })
t.Run("TestTransactionsToReturnTransactions", func(t *testing.T) { t.Run("TestTransactionsToReturnTransactions", func(t *testing.T) {
key, _ := crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
signer := types.NewEIP155Signer(big.NewInt(2147483647))
//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})
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})
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})
mytx3,_ := types.SignTx(tx3, signer, key)
txs := []*types.Transaction{mytx, mytx2, mytx3}
receipt1 := &types.Receipt{
Status: types.ReceiptStatusSuccessful,
CumulativeGasUsed: 1,
Logs: []*types.Log{
{Address: common.BytesToAddress([]byte{0x11})},
{Address: common.BytesToAddress([]byte{0x01, 0x11})},
},
TxHash: common.BytesToHash([]byte{0x11, 0x11}),
ContractAddress: common.BytesToAddress([]byte{0x01, 0x11, 0x11}),
GasUsed: 111111,
}
receipts := []*types.Receipt{receipt1}
block := types.NewBlock(&types.Header{Number: big.NewInt(314)}, txs, nil, receipts)
if err := core.SWriteBlock(block, receipts); err != nil {
t.Fatalf("Failed to write block into database: %v", err)
}
sqldb, err := core.DBConnection()
if (err != nil) {
panic(err)
}
for _, tx := range txs { for _, tx := range txs {
txn := core.SGetTransaction(sqldb, tx.Hash().String()) txn := core.SGetTransaction(sqldb, tx.Hash().String())
byt := []byte(txn) byt := []byte(txn)
@ -359,13 +266,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 {
@ -377,14 +284,14 @@ t.Run("TestTransactionsToReturnTransactions", func(t *testing.T) {
if tx.GasPrice().Uint64() != data.GasPrice { if tx.GasPrice().Uint64() != data.GasPrice {
t.Fatalf("Gas Price [%v]: Gas price not found", tx.GasPrice().String()) t.Fatalf("Gas Price [%v]: Gas price not found", tx.GasPrice().String())
} }
if block.GasLimit() != data.GasLimit { if block1.GasLimit() != data.GasLimit {
t.Fatalf("Gas Limit [%v]: Gas limit not found", block.GasLimit()) t.Fatalf("Gas Limit [%v]: Gas limit not found", block1.GasLimit())
} }
if block.Hash().String() != data.BlockHash { if block1.Hash().String() != data.BlockHash {
t.Fatalf("Block Hash [%v]: Block hash not found", block.Hash().String()) t.Fatalf("Block Hash [%v]: Block hash not found", block1.Hash().String())
} }
if block.Number().String() != data.BlockNumber { if block1.Number().String() != data.BlockNumber {
t.Fatalf("Block Number [%v]: Block number not found", block.Number().String()) t.Fatalf("Block Number [%v]: Block number not found", block1.Number().String())
} }
if tx.Value().String() != data.Amount { if tx.Value().String() != data.Amount {
t.Fatalf("Amount [%v]: Amount not found", tx.Value().String()) t.Fatalf("Amount [%v]: Amount not found", tx.Value().String())
@ -393,10 +300,10 @@ t.Run("TestTransactionsToReturnTransactions", func(t *testing.T) {
t.Fatalf("Cost [%v]: Cost not found", tx.Cost().String()) t.Fatalf("Cost [%v]: Cost not found", tx.Cost().String())
} }
var status string var status string
if receipt1.Status == 1 { if receipt.Status == 1 {
status = "SUCCESS" status = "SUCCESS"
} }
if receipt1.Status == 0 { if receipt.Status == 0 {
status = "FAIL" status = "FAIL"
} }
if status != data.Status { if status != data.Status {
@ -412,104 +319,47 @@ t.Run("TestTransactionsToReturnTransactions", func(t *testing.T) {
t.Fatalf("isContract [%v]: isContract bool is incorrect", isContract) t.Fatalf("isContract [%v]: isContract bool is incorrect", isContract)
} }
} }
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()
}) })
t.Run("TestAccountsToReturnAccounts", func(t *testing.T) { t.Run("TestAccountsToReturnAccounts", func(t *testing.T) {
key, _ := crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") for _, tx := range txs {
signer := types.NewEIP155Signer(big.NewInt(2147483647)) fmt.Println("test account", tx.To().String())
accountAddrTo := core.SGetAccount(sqldb, tx.To().String())
byts := []byte(accountAddrTo)
var accountDataTo core.SAccounts
json.Unmarshal(byts, &accountDataTo)
toAddr1 := common.BytesToAddress([]byte{0x11}) if strings.ToLower(tx.To().String()) != accountDataTo.Addr {
toAddr2 := common.BytesToAddress([]byte{0x22}) t.Fatalf("To address [%v]: To address not found", accountDataTo.Addr)
toAddr3 := common.BytesToAddress([]byte{0x33})
toAmount1 := big.NewInt(111)
var toAmountPrev1 string = "3968686868"
sqldb, err := core.DBConnection()
if (err != nil) {
panic(err)
} }
if tx.Value().String() != accountDataTo.Balance {
core.CreateAccount(sqldb, toAddr1.Hex(), toAmountPrev1, "1") t.Fatalf("To address balance [%v]: To address balance not found", accountDataTo.Balance)
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, toAddr1, toAmount1, 1111, big.NewInt(11111), []byte{0x11, 0x11, 0x11})
mytx,_ := types.SignTx(tx1, signer, key)
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, toAddr3, big.NewInt(333), 3333, big.NewInt(33333), []byte{0x33, 0x33, 0x33})
mytx3,_ := types.SignTx(tx3, signer, key)
txs := []*types.Transaction{mytx, mytx2, mytx3}
receipt1 := &types.Receipt{
Status: types.ReceiptStatusSuccessful,
CumulativeGasUsed: 1,
Logs: []*types.Log{
{Address: common.BytesToAddress([]byte{0x11})},
{Address: common.BytesToAddress([]byte{0x01, 0x11})},
},
TxHash: common.BytesToHash([]byte{0x11, 0x11}),
ContractAddress: common.BytesToAddress([]byte{0x01, 0x11, 0x11}),
GasUsed: 111111,
} }
if strconv.FormatUint(tx.Nonce(), 10) != accountDataTo.AccountNonce {
receipts := []*types.Receipt{receipt1} t.Fatalf("To account nonce [%v]: To account nonce not found", accountDataTo.AccountNonce)
block := types.NewBlock(&types.Header{Number: big.NewInt(315)}, txs, nil, receipts)
if err := core.SWriteBlock(block, receipts); err != nil {
t.Fatalf("Failed to write block into database: %v", err)
} }
if toAddr1.String() != tx1.To().String() {
t.Fatalf("To address [%v]: To address not found", toAddr1.String())
} }
accountAddrTo, _ := core.InnerSGetAccount(sqldb, toAddr1.String()) accountAddrFrom := core.SGetAccount(sqldb, fromAddr)
//ewAccountNonceReceiver.Add(accountR, nonceIncrement) byts := []byte(accountAddrFrom)
addedAmount := new(big.Int) var accountDataFrom core.SAccounts
toAmountPrevious1, _ := strconv.ParseUint(toAmountPrev1, 10, 64) json.Unmarshal(byts, &accountDataFrom)
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 { if fromAddr != accountDataFrom.Addr {
t.Fatalf("To address balance [%v]: To address balance not correct FFO", toBalance) t.Fatalf("To address [%v]: To address not found", accountDataFrom.Addr)
} }
if fromAddrEndBalance != accountDataFrom.Balance {
//for _, tx := range txs { t.Fatalf("To address balance [%v]: To address balance not found", accountDataFrom.Balance)
// accountAddrTo := core.SGetAccount(sqldb, tx.To().String()) }
// byts := []byte(accountAddrTo) if fromAddrEndNonce != accountDataFrom.AccountNonce {
// var accountDataTo core.SAccounts t.Fatalf("To account nonce [%v]: To account nonce not found", accountDataFrom.AccountNonce)
// json.Unmarshal(byts, &accountDataTo) }
// if getAllAccountTxs := core.SGetAccountTxs(sqldb, toAddr.String()); len(getAllAccountTxs) == 0 {
// 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 {
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()
}) })
ClearTables()
} }