Squashed commit of the following:

commit f345b88d07
Merge: 1d07665d4 a908f3fd0
Author: Priom Chowdhury <priom.galaxy@gmail.com>
Date:   Mon Aug 13 10:31:36 2018 -0400

    Merge pull request #48 from ShyftNetwork/update/accountBalances

    Update/account balances

commit a908f3fd02
Author: greg <gregorymarkou@gmail.com>
Date:   Fri Aug 10 21:23:21 2018 +0300

    remove fmt

commit 74491b644c
Merge: de13a538f e1a36f6d8
Author: Dustin Brickwood <dustinbrickwood204@gmail.com>
Date:   Wed Aug 8 17:59:49 2018 -0400

    Merge branch 'update/accountBalances' of github.com:ShyftNetwork/shyft_go-ethereum into update/accountBalances

commit de13a538f6
Author: Dustin Brickwood <dustinbrickwood204@gmail.com>
Date:   Wed Aug 8 17:59:26 2018 -0400

    resolved conflicts

commit e1a36f6d89
Merge: a37f60d6a 1d07665d4
Author: Dustin Brickwood <dustinbrickwood204@gmail.com>
Date:   Wed Aug 8 17:45:11 2018 -0400

    Merge branch 'staging' into update/accountBalances

commit a37f60d6a3
Author: Dustin Brickwood <dustinbrickwood204@gmail.com>
Date:   Wed Aug 8 17:43:56 2018 -0400

    removed fmt prints, created types file and fixed UI

commit ba48ad13e9
Author: Dustin Brickwood <dustinbrickwood204@gmail.com>
Date:   Tue Aug 7 16:48:08 2018 -0400

    updating balances working correctly, test suite incomplete for accounts

commit d760a7caa7
Author: Dustin Brickwood <dustinbrickwood204@gmail.com>
Date:   Tue Aug 7 13:38:08 2018 -0400

    refactored account balance updating

commit 3acdd3f5c5
Author: Dustin Brickwood <dustinbrickwood204@gmail.com>
Date:   Mon Aug 6 17:38:01 2018 -0400

    need to clean up updating account balances functions

commit 2abd54c29e
Author: Dustin Brickwood <dustinbrickwood204@gmail.com>
Date:   Thu Aug 2 14:47:11 2018 -0400

    refactored unit tests to include set up and tear down

commit 494e62c69a
Author: Dustin Brickwood <dustinbrickwood204@gmail.com>
Date:   Wed Aug 1 15:59:38 2018 -0400

    wip

commit c121072d0f
Author: Dustin Brickwood <dustinbrickwood204@gmail.com>
Date:   Wed Aug 1 15:58:14 2018 -0400

    added create from account for each test

commit 112c47bf29
Author: Dustin Brickwood <dustinbrickwood204@gmail.com>
Date:   Wed Aug 1 15:44:18 2018 -0400

    unit tests for account balances wip

commit d299d2baeb
Author: Dustin Brickwood <dustinbrickwood204@gmail.com>
Date:   Wed Aug 1 15:17:38 2018 -0400

    unit testing for account balances

commit f066a8e461
Author: Dustin Brickwood <dustinbrickwood204@gmail.com>
Date:   Mon Jul 30 11:37:18 2018 -0400

    all hashes stored as lower case

commit ab8d98ad91
Author: Dustin Brickwood <dustinbrickwood204@gmail.com>
Date:   Thu Jul 26 17:03:50 2018 -0400

    updating accounts from internal txs

commit 3f6bdfc0e4
Author: Dustin Brickwood <dustinbrickwood204@gmail.com>
Date:   Thu Jul 26 15:46:48 2018 -0400

    refactored gen write functions for internals

commit dc379b811c
Author: Dustin Brickwood <dustinbrickwood204@gmail.com>
Date:   Wed Jul 25 16:36:16 2018 -0400

    need to fix gen write before internals
This commit is contained in:
David Krett 2018-08-14 11:37:57 -04:00
parent d2f1349b95
commit 2e58574ae2
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"
@ -92,10 +91,10 @@ type BlockChain struct {
chainConfig *params.ChainConfig // Chain & network configuration chainConfig *params.ChainConfig // Chain & network configuration
cacheConfig *CacheConfig // Cache configuration for pruning cacheConfig *CacheConfig // Cache configuration for pruning
db ethdb.Database // Low level persistent database to store final content in db ethdb.Database // Low level persistent database to store final content in
triegc *prque.Prque // Priority queue mapping block numbers to tries to gc triegc *prque.Prque // Priority queue mapping block numbers to tries to gc
gcproc time.Duration // Accumulates canonical block processing for trie dumping gcproc time.Duration // Accumulates canonical block processing for trie dumping
hc *HeaderChain hc *HeaderChain
rmLogsFeed event.Feed rmLogsFeed event.Feed

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 {
_, _, err := AccountExists(sqldb, k.String())
switch {
case err == sql.ErrNoRows:
var toAddr *common.Address
var data []byte
var cost, gasPrice uint64
//Initializing proper types for tx struct
toAddr = &k
cost = 0
gasPrice = 0
//Appending GENESIS to address stored as txHash and From Addr
Genesis := []string{"GENESIS_", 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
accountNoncee := strconv.FormatUint(accountNonce, 10)
for k := range gen.Alloc {
addr := k.String()
var response string
sqlExistsStatement := `SELECT balance from accounts WHERE addr = ($1)`
err := sqldb.QueryRow(sqlExistsStatement, addr).Scan(&response)
switch {
case err == sql.ErrNoRows:
for k, v := range gen.Alloc {
number := block.Header().Number.String()
gasUsed := block.Header().GasUsed
gasLimit := block.Header().GasLimit
gasPrice := 0
txFee := 0
txStatus := ""
isContract := false
data:= ""
addr := k.String()
accountNonce := v.Nonce +1
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 default:
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` log.Info("Found Genesis Block")
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: }
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 WRITE TO BLOCK ZERO DB //@NOTE:SHYFT SWITCH CASE ENSURES SHYFT GENESIS FUNCTIONS ARE ONLY CALLED ONCE
WriteShyftBlockZero(block, genesis) sqldb, _ := DBConnection()
//@NOTE:SHYFT WRITE TO DB serror := BlockExists(sqldb, block.Hash().String())
WriteShyftGen(genesis, block) switch {
case serror == sql.ErrNoRows:
//@NOTE:SHYFT WRITE TO BLOCK ZERO DB
WriteShyftBlockZero(block, genesis)
//@NOTE:SHYFT WRITE TO DB
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,170 +1,81 @@
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)
} }
rewards := swriteMinerRewards(sqldb,block) //Get miner rewards
rewards := swriteMinerRewards(sqldb, block)
blockData := SBlock{ //Format block time to be stored
Hash: block.Header().Hash().Hex(),
Coinbase: block.Header().Coinbase.String(),
Number: block.Header().Number.String(),
GasUsed: block.Header().GasUsed,
GasLimit: block.Header().GasLimit,
TxCount: block.Transactions().Len(),
UncleCount: len(block.Uncles()),
ParentHash: block.ParentHash().String(),
UncleHash: block.UncleHash().String(),
Difficulty: block.Difficulty().String(),
Size: block.Size().String(),
Nonce: block.Nonce(),
Rewards: rewards,
}
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)
blockAge := SBlock { blockData := stypes.SBlock{
Age: age, Hash: block.Header().Hash().Hex(),
Coinbase: block.Header().Coinbase.String(),
Number: block.Header().Number.String(),
GasUsed: block.Header().GasUsed,
GasLimit: block.Header().GasLimit,
TxCount: block.Transactions().Len(),
UncleCount: len(block.Uncles()),
ParentHash: block.ParentHash().String(),
UncleHash: block.UncleHash().String(),
Difficulty: block.Difficulty().String(),
Size: block.Size().String(),
Nonce: block.Nonce(),
Rewards: rewards,
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
} }
//swriteTransactions writes to sqldb, a SHYFT postgres instance //swriteTransactions writes to sqldb, a SHYFT postgres instance
func swriteTransactions(sqldb *sql.DB, tx *types.Transaction, blockHash common.Hash, blockNumber string, receipts []*types.Receipt, age time.Time, gasLimit uint64) error { func swriteTransactions(sqldb *sql.DB, tx *types.Transaction, blockHash common.Hash, blockNumber string, receipts []*types.Receipt, age time.Time, gasLimit uint64) error {
var isContract bool var isContract bool
var statusFromReciept 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,99 +100,118 @@ func swriteTransactions(sqldb *sql.DB, tx *types.Transaction, blockHash common.H
statusFromReciept = "SUCCESS" statusFromReciept = "SUCCESS"
} }
} }
data := ShyftTxEntryPretty{ toAddr = tx.To()
Status: statusFromReciept,
IsContract: isContract,
To: tx.To(),
}
//Insert Tx into DB
InsertTx(sqldb, txData, data)
} }
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,
IsContract: isContract,
}
//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:
var newBalanceSender,newAccountNonceSender big.Int balanceHelper(sqldb, sendAndReceiveData, amount)
var nonceIncrement = big.NewInt(1)
fromBalance := new(big.Int)
fromBalance, _ = fromBalance.SetString(fromAddressBalance, 10)
fromNonce := new(big.Int)
fromNonce, _ = fromNonce.SetString(fromAccountNonce, 10)
newBalanceSender.Sub(fromBalance, tx.Value())
newAccountNonceSender.Add(fromNonce, nonceIncrement)
UpdateAccount(sqldb, sendAndReceiveData.From, newBalanceSender.String(), newAccountNonceSender.String())
} }
return nil return nil
} }
//writeFromBalance writes senders balance to accounts db func adjustBalanceFromAddr(sqldb *sql.DB, s stypes.SendAndReceive, value *big.Int) {
func swriteFromBalance(sqldb *sql.DB, tx *types.Transaction) error { fromAddressBalance, fromAccountNonce, err := AccountExists(sqldb, s.From)
sendAndReceiveData := SendAndReceive{
To: tx.To().Hex(),
From: tx.From().Hex(),
Amount: tx.Value().String(),
}
toAddressBalance, toAccountNonce, err := AccountExists(sqldb, sendAndReceiveData.To)
switch { switch {
case err == sql.ErrNoRows: case err == sql.ErrNoRows:
accountNonce := strconv.FormatUint(tx.Nonce(), 10) CreateAccount(sqldb, s.From, "0", "1")
CreateAccount(sqldb, sendAndReceiveData.To, sendAndReceiveData.Amount, accountNonce) fmt.Println("New From account created")
case err != nil:
log.Fatal(err)
default:
fromAddressBalance, fromAccountNonce, err := AccountExists(sqldb, sendAndReceiveData.From)
if err != nil {
log.Fatal(err)
}
var newBalanceReceiver, newBalanceSender, newAccountNonceReceiver, newAccountNonceSender big.Int
var nonceIncrement = big.NewInt(1)
//STRING TO BIG INT
//BALANCES TO AND FROM ADDR
toBalance := new(big.Int)
toBalance, _ = toBalance.SetString(toAddressBalance, 10)
fromBalance := new(big.Int)
fromBalance, _ = fromBalance.SetString(fromAddressBalance, 10)
//ACCOUNT NONCES
toNonce := new(big.Int)
toNonce, _ = toNonce.SetString(toAccountNonce, 10)
fromNonce := new(big.Int)
fromNonce, _ = fromNonce.SetString(fromAccountNonce, 10)
newBalanceReceiver.Add(toBalance, tx.Value())
newBalanceSender.Sub(fromBalance, tx.Value())
newAccountNonceReceiver.Add(toNonce, nonceIncrement)
newAccountNonceSender.Add(fromNonce, nonceIncrement)
//UPDATE ACCOUNTS BASED ON NEW BALANCES AND ACCOUNT NONCES
UpdateAccount(sqldb, sendAndReceiveData.To, newBalanceReceiver.String(), newAccountNonceReceiver.String())
UpdateAccount(sqldb, sendAndReceiveData.From, newBalanceSender.String(), newAccountNonceSender.String())
} }
return nil if err != nil {
log.Fatal(err)
}
var newBalanceSender, newAccountNonceSender big.Int
var nonceIncrement = big.NewInt(1)
fromBalance := new(big.Int)
fromBalance, _ = fromBalance.SetString(fromAddressBalance, 10)
fromNonce := new(big.Int)
fromNonce, _ = fromNonce.SetString(fromAccountNonce, 10)
newBalanceSender.Sub(fromBalance, value)
newAccountNonceSender.Add(fromNonce, nonceIncrement)
UpdateAccount(sqldb, s.From, newBalanceSender.String(), newAccountNonceSender.String())
}
func balanceHelper(sqldb *sql.DB, s stypes.SendAndReceive, amount string) {
fromAddressBalance, fromAccountNonce, err := AccountExists(sqldb, s.From)
toAddressBalance, toAccountNonce, err := AccountExists(sqldb, s.To)
if err != nil {
log.Fatal(err)
}
var newBalanceReceiver, newBalanceSender, newAccountNonceReceiver, newAccountNonceSender big.Int
var nonceIncrement = big.NewInt(1)
//STRING TO BIG INT
//BALANCES TO AND FROM ADDR
toBalance := new(big.Int)
toBalance, _ = toBalance.SetString(toAddressBalance, 10)
fromBalance := new(big.Int)
fromBalance, _ = fromBalance.SetString(fromAddressBalance, 10)
amountValue := new(big.Int)
amountValue, _ = amountValue.SetString(amount, 10)
//ACCOUNT NONCES
toNonce := new(big.Int)
toNonce, _ = toNonce.SetString(toAccountNonce, 10)
fromNonce := new(big.Int)
fromNonce, _ = fromNonce.SetString(fromAccountNonce, 10)
newBalanceReceiver.Add(toBalance, amountValue)
newBalanceSender.Sub(fromBalance, amountValue)
newAccountNonceReceiver.Add(toNonce, nonceIncrement)
newAccountNonceSender.Add(fromNonce, nonceIncrement)
//UPDATE ACCOUNTS BASED ON NEW BALANCES AND ACCOUNT NONCES
UpdateAccount(sqldb, s.To, newBalanceReceiver.String(), newAccountNonceReceiver.String())
UpdateAccount(sqldb, s.From, newBalanceSender.String(), newAccountNonceSender.String())
} }
// @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:
@ -309,7 +233,7 @@ func swriteMinerRewards(sqldb *sql.DB, block *types.Block) string {
// https://ethereum.stackexchange.com/questions/27172/different-uncles-reward // https://ethereum.stackexchange.com/questions/27172/different-uncles-reward
// line 551 in consensus.go (shyft_go-ethereum/consensus/ethash/consensus.go) // line 551 in consensus.go (shyft_go-ethereum/consensus/ethash/consensus.go)
// Some weird constants to avoid constant memory allocs for them. // Some weird constants to avoid constant memory allocs for them.
var big8 = big.NewInt(8) var big8 = big.NewInt(8)
var uncleRewards []*big.Int var uncleRewards []*big.Int
var uncleAddrs []string var uncleAddrs []string
@ -378,19 +302,21 @@ func sstoreReward(sqldb *sql.DB, address string, reward *big.Int) {
/////////////////////// ///////////////////////
//DB Utility functions //DB Utility functions
////////////////////// //////////////////////
func CreateAccount (sqldb *sql.DB, addr string, balance string, accountNonce string) {
//CreateAccount writes new account to Postgres Db
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)
} }
} }
func AccountExists (sqldb *sql.DB, addr string) (string, string, error) { //AccountExists checks if account exists in Postgres Db
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,23 +27,23 @@ 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,
GasLimit: gasLimit, GasLimit: gasLimit,
TxCount: txCount, TxCount: txCount,
UncleCount: uncleCount, UncleCount: uncleCount,
AgeGet: age, AgeGet: age,
ParentHash: parentHash, ParentHash: parentHash,
UncleHash: uncleHash, UncleHash: uncleHash,
Difficulty: difficulty, Difficulty: difficulty,
Size: size, Size: size,
Nonce: nonce, Nonce: nonce,
Rewards: rewards, Rewards: rewards,
Number: num, Number: num,
}) })
blocks, _ := json.Marshal(arr.Blocks) blocks, _ := json.Marshal(arr.Blocks)
@ -61,23 +63,23 @@ 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,
GasLimit: gasLimit, GasLimit: gasLimit,
TxCount: txCount, TxCount: txCount,
UncleCount: uncleCount, UncleCount: uncleCount,
AgeGet: age, AgeGet: age,
ParentHash: parentHash, ParentHash: parentHash,
UncleHash: uncleHash, UncleHash: uncleHash,
Difficulty: difficulty, Difficulty: difficulty,
Size: size, Size: size,
Nonce: nonce, Nonce: nonce,
Rewards: rewards, Rewards: rewards,
Number: num, Number: num,
} }
json, _ := json.Marshal(block) json, _ := json.Marshal(block)
return string(json) return string(json)
@ -91,30 +93,30 @@ 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,
GasLimit: gasLimit, GasLimit: gasLimit,
TxCount: txCount, TxCount: txCount,
UncleCount: uncleCount, UncleCount: uncleCount,
AgeGet: age, AgeGet: age,
ParentHash: parentHash, ParentHash: parentHash,
UncleHash: uncleHash, UncleHash: uncleHash,
Difficulty: difficulty, Difficulty: difficulty,
Size: size, Size: size,
Nonce: nonce, Nonce: nonce,
Rewards: rewards, Rewards: rewards,
Number: num, Number: num,
} }
json, _ := json.Marshal(block) json, _ := json.Marshal(block)
return string(json) return string(json)
} }
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,22 +135,22 @@ 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,
BlockHash: blockhash, BlockHash: blockhash,
BlockNumber: blocknumber, BlockNumber: blocknumber,
Amount: amount, Amount: amount,
GasPrice: gasprice, GasPrice: gasprice,
Gas: gas, Gas: gas,
GasLimit: gasLimit, GasLimit: gasLimit,
Cost: txfee, Cost: txfee,
Nonce: nonce, Nonce: nonce,
Status: status, Status: status,
IsContract: isContract, IsContract: isContract,
Age: age, Age: age,
Data: data, Data: data,
}) })
tx, _ := json.Marshal(arr.TxEntry) tx, _ := json.Marshal(arr.TxEntry)
@ -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,23 +176,23 @@ 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,
GasLimit: gasLimit, GasLimit: gasLimit,
TxCount: txCount, TxCount: txCount,
UncleCount: uncleCount, UncleCount: uncleCount,
AgeGet: age, AgeGet: age,
ParentHash: parentHash, ParentHash: parentHash,
UncleHash: uncleHash, UncleHash: uncleHash,
Difficulty: difficulty, Difficulty: difficulty,
Size: size, Size: size,
Nonce: nonce, Nonce: nonce,
Rewards: rewards, Rewards: rewards,
Number: num, Number: num,
}) })
blocks, _ := json.Marshal(arr.Blocks) blocks, _ := json.Marshal(arr.Blocks)
@ -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,22 +222,22 @@ 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,
BlockHash: blockhash, BlockHash: blockhash,
BlockNumber: blocknumber, BlockNumber: blocknumber,
Amount: amount, Amount: amount,
GasPrice: gasprice, GasPrice: gasprice,
Gas: gas, Gas: gas,
GasLimit: gasLimit, GasLimit: gasLimit,
Cost: txfee, Cost: txfee,
Nonce: nonce, Nonce: nonce,
Status: status, Status: status,
IsContract: isContract, IsContract: isContract,
Age: age, Age: age,
Data: data, Data: data,
}) })
tx, _ := json.Marshal(arr.TxEntry) tx, _ := json.Marshal(arr.TxEntry)
@ -258,39 +260,39 @@ 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,
BlockHash: blockhash, BlockHash: blockhash,
BlockNumber: blocknumber, BlockNumber: blocknumber,
Amount: amount, Amount: amount,
GasPrice: gasprice, GasPrice: gasprice,
Gas: gas, Gas: gas,
GasLimit: gasLimit, GasLimit: gasLimit,
Cost: txfee, Cost: txfee,
Nonce: nonce, Nonce: nonce,
Status: status, Status: status,
IsContract: isContract, IsContract: isContract,
Age: age, Age: age,
Data: data, Data: data,
} }
json, _ := json.Marshal(tx) json, _ := json.Marshal(tx)
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,
} }
return account, true return account, true
} }
@ -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,10 +328,10 @@ 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,
}) })
accounts, _ := json.Marshal(array.AllAccounts) accounts, _ := json.Marshal(array.AllAccounts)
@ -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,22 +362,22 @@ 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,
BlockHash: blockhash, BlockHash: blockhash,
BlockNumber: blocknumber, BlockNumber: blocknumber,
Amount: amount, Amount: amount,
GasPrice: gasprice, GasPrice: gasprice,
Gas: gas, Gas: gas,
GasLimit: gasLimit, GasLimit: gasLimit,
Cost: txfee, Cost: txfee,
Nonce: nonce, Nonce: nonce,
Status: status, Status: status,
IsContract: isContract, IsContract: isContract,
Age: age, Age: age,
Data: data, Data: data,
}) })
tx, _ := json.Marshal(arr.TxEntry) tx, _ := json.Marshal(arr.TxEntry)

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.
@ -646,7 +644,7 @@ func (api *PrivateDebugAPI) traceTx(ctx context.Context, message core.Message, v
case config != nil && config.Tracer != nil: case config != nil && config.Tracer != nil:
// Define a meaningful timeout of a single transaction trace // Define a meaningful timeout of a single transaction trace
timeout := defaultTraceTimeout timeout := defaultTraceTimeout
if config.Timeout != nil { if config.Timeout != nil {
if timeout, err = time.ParseDuration(*config.Timeout); err != nil { if timeout, err = time.ParseDuration(*config.Timeout); err != nil {

View file

@ -1,15 +1,16 @@
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{}
type ShyftTracer struct {} type ShyftTracer struct{}
var PrivateAPI *PrivateDebugAPI var PrivateAPI *PrivateDebugAPI
var Context context.Context var Context context.Context
@ -23,9 +24,9 @@ func InitTracerEnv() {
Context = ctx2 Context = ctx2
config := &TraceConfig{ config := &TraceConfig{
LogConfig: nil, LogConfig: nil,
Tracer: &jsTracer, // needs to be non-nil Tracer: &jsTracer, // needs to be non-nil
Timeout: nil, Timeout: nil,
Reexec: nil, Reexec: nil,
} }
TracerConfig = config TracerConfig = config
fullNode, _ := SNew(Global_config) fullNode, _ := SNew(Global_config)
@ -33,11 +34,11 @@ func InitTracerEnv() {
PrivateAPI = privateAPI PrivateAPI = privateAPI
} }
func (st ShyftTracer) GetTracerToRun (hash common.Hash) (interface{}, error) { func (st ShyftTracer) GetTracerToRun(hash common.Hash) (interface{}, error) {
return PrivateAPI.STraceTransaction(Context, hash, TracerConfig) return PrivateAPI.STraceTransaction(Context, hash, TracerConfig)
} }
func setEthObject(ethobj interface{}){ func setEthObject(ethobj interface{}) {
EthereumObject = ethobj EthereumObject = ethobj
} }
@ -45,4 +46,4 @@ var Global_config *Config
func SetGlobalConfig(c *Config) { func SetGlobalConfig(c *Config) {
Global_config = c Global_config = c
} }

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)
@ -249,4 +250,4 @@ func BroadcastTx(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
fmt.Fprintln(w, "Transaction Hash:", tx_hash) fmt.Fprintln(w, "Transaction Hash:", tx_hash)
} }
} }

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,30 +1,33 @@
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{}
const ( const (
testAddress = "0x8605cdbbdb6d264aa742e77020dcbc58fcdce182" testAddress = "0x8605cdbbdb6d264aa742e77020dcbc58fcdce182"
) )
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,127 +40,56 @@ func TestBlock(t *testing.T) {
eth.SetGlobalConfig(ethConf) eth.SetGlobalConfig(ethConf)
eth.InitTracerEnv() eth.InitTracerEnv()
core.ClearTables()
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(5), 1111, big.NewInt(11111), []byte{0x11, 0x11, 0x11})
mytx1, _ := types.SignTx(tx1, signer, key)
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)
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)
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{
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{receipt}
block1 := types.NewBlock(&types.Header{Number: big.NewInt(323)}, txs, nil, receipts)
block2 := types.NewBlock(&types.Header{Number: big.NewInt(320)}, txs1, nil, receipts)
block3 := types.NewBlock(&types.Header{Number: big.NewInt(322)}, txs2, nil, receipts)
blocks := []*types.Block{block1, block2, block3}
sqldb, err := core.DBConnection()
if err != nil {
panic(err)
}
fromAddr := "0x71562b71999873db5b286df957af199ec94617f7"
fromAddrEndBalance := "75"
fromAddrEndNonce := "5"
toAddr := common.BytesToAddress([]byte{0x11})
core.CreateAccount(sqldb, fromAddr, "201", "1")
t.Run("TestBlockToReturnBlock", func(t *testing.T) { t.Run("TestBlockToReturnBlock", 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}
receipt := &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{receipt}
block := types.NewBlock(&types.Header{Number: big.NewInt(315)}, txs, nil, receipts)
// Write and verify the block in the database
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)
}
entry := core.SGetBlock(sqldb, block.Number().String())
byt := []byte(entry)
var data core.SBlock
json.Unmarshal(byt, &data)
//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}
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,351 +97,269 @@ 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) { var contractAddressFromReciept string
key, _ := crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") for _, receipt := range receipts {
signer := types.NewEIP155Signer(big.NewInt(2147483647)) contractAddressFromReciept = (*types.ReceiptForStorage)(receipt).ContractAddress.String()
}
//Nonce,Value, GasLimit, Gasprice, data for _, tx := range txs2 {
contractCreation := types.NewContractCreation(1, big.NewInt(111), 1111, big.NewInt(11111), []byte{0x11, 0x11, 0x11}) txn := core.SGetTransaction(sqldb, tx.Hash().String())
mytx,_ := types.SignTx(contractCreation, signer, key) byt := []byte(txn)
txs := []*types.Transaction{mytx} var data core.ShyftTxEntryPretty
json.Unmarshal(byt, &data)
receipt2 := &types.Receipt{ if tx.Hash().String() != data.TxHash {
Status: types.ReceiptStatusSuccessful, t.Fatalf("txHash [%v]: tx Hash not found", tx.Hash().String())
CumulativeGasUsed: 1, }
Logs: []*types.Log{ if contractAddressFromReciept != data.ToGet {
{Address: common.BytesToAddress([]byte{0x11})}, t.Fatalf("Contract Addr [%v]: Contract addr not found", contractAddressFromReciept)
{Address: common.BytesToAddress([]byte{0x01, 0x11})}, }
}, if strings.ToLower(tx.From().String()) != data.From {
TxHash: common.BytesToHash([]byte{0x11, 0x11}), t.Fatalf("From Addr [%v]: From addr not found", tx.From().String())
ContractAddress: common.BytesToAddress([]byte{0x01, 0x11, 0x11}), }
GasUsed: 111111, if tx.Nonce() != data.Nonce {
} t.Fatalf("Nonce [%v]: Nonce not found", tx.Nonce())
}
if tx.Gas() != data.Gas {
t.Fatalf("Gas [%v]: Gas not found", tx.Gas())
}
if tx.GasPrice().Uint64() != data.GasPrice {
t.Fatalf("Gas Price [%v]: Gas price not found", tx.GasPrice().String())
}
if block1.GasLimit() != data.GasLimit {
t.Fatalf("Gas Limit [%v]: Gas limit not found", block1.GasLimit())
}
if block3.Hash().String() != data.BlockHash {
t.Fatalf("Block Hash [%v]: Block hash not found", block1.Hash().String())
}
if block3.Number().String() != data.BlockNumber {
t.Fatalf("Block Number [%v]: Block number not found", block1.Number().String())
}
if tx.Value().String() != data.Amount {
t.Fatalf("Amount [%v]: Amount not found", tx.Value().String())
}
if tx.Cost().Uint64() != data.Cost {
t.Fatalf("Cost [%v]: Cost not found", tx.Cost().String())
}
var status string
if receipt.Status == 1 {
status = "SUCCESS"
}
if receipt.Status == 0 {
status = "FAIL"
}
if status != data.Status {
t.Fatalf("Receipt status [%v]: Receipt status not found", status)
}
var isContract bool
if tx.To() != nil {
isContract = false
} else {
isContract = true
}
if isContract != data.IsContract {
t.Fatalf("isContract [%v]: isContract bool is incorrect", isContract)
}
}
})
receipts := []*types.Receipt{receipt2} t.Run("TestTransactionsToReturnTransactions", func(t *testing.T) {
block := types.NewBlock(&types.Header{Number: big.NewInt(314)}, txs, nil, receipts) for _, tx := range txs {
txn := core.SGetTransaction(sqldb, tx.Hash().String())
if err := core.SWriteBlock(block, receipts); err != nil {
t.Fatalf("Failed to write block into database: %v", err)
}
var contractAddressFromReciept string
for _, receipt := range receipts {
contractAddressFromReciept = (*types.ReceiptForStorage)(receipt).ContractAddress.String()
}
sqldb, err := core.DBConnection()
if (err != nil) {
panic(err)
}
for _, tx := range txs {
txn := core.SGetTransaction(sqldb, tx.Hash().String())
byt := []byte(txn)
var data core.ShyftTxEntryPretty
json.Unmarshal(byt, &data)
if tx.Hash().String() != data.TxHash {
t.Fatalf("txHash [%v]: tx Hash not found", tx.Hash().String())
}
if contractAddressFromReciept != data.ToGet {
t.Fatalf("Contract Addr [%v]: Contract addr not found", contractAddressFromReciept)
}
if tx.From().String() != data.From {
t.Fatalf("From Addr [%v]: From addr not found", tx.From().String())
}
if tx.Nonce() != data.Nonce {
t.Fatalf("Nonce [%v]: Nonce not found", tx.Nonce())
}
if tx.Gas() != data.Gas {
t.Fatalf("Gas [%v]: Gas not found", tx.Gas())
}
if tx.GasPrice().Uint64() != data.GasPrice {
t.Fatalf("Gas Price [%v]: Gas price not found", tx.GasPrice().String())
}
if block.GasLimit() != data.GasLimit {
t.Fatalf("Gas Limit [%v]: Gas limit not found", block.GasLimit())
}
if block.Hash().String() != data.BlockHash {
t.Fatalf("Block Hash [%v]: Block hash not found", block.Hash().String())
}
if block.Number().String() != data.BlockNumber {
t.Fatalf("Block Number [%v]: Block number not found", block.Number().String())
}
if tx.Value().String() != data.Amount {
t.Fatalf("Amount [%v]: Amount not found", tx.Value().String())
}
if tx.Cost().Uint64() != data.Cost {
t.Fatalf("Cost [%v]: Cost not found", tx.Cost().String())
}
var status string
if receipt2.Status == 1 {
status = "SUCCESS"
}
if receipt2.Status == 0 {
status = "FAIL"
}
if status != data.Status {
t.Fatalf("Receipt status [%v]: Receipt status not found", status)
}
var isContract bool
if tx.To() != nil {
isContract = false
} else {
isContract = true
}
if isContract != data.IsContract {
t.Fatalf("isContract [%v]: isContract bool is incorrect", isContract)
}
}
ClearTables()
})
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 {
txn := core.SGetTransaction(sqldb, tx.Hash().String())
byt := []byte(txn) byt := []byte(txn)
var data core.ShyftTxEntryPretty var data core.ShyftTxEntryPretty
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 strings.ToLower(tx.From().String()) != data.From {
t.Fatalf("From Addr [%v]: From addr not found", tx.From().String())
}
if strings.ToLower(tx.To().String()) != data.ToGet {
t.Fatalf("To Addr [%v]: To addr not found", tx.To().String())
}
if tx.Nonce() != data.Nonce {
t.Fatalf("Nonce [%v]: Nonce not found", tx.Nonce())
}
if tx.Gas() != data.Gas {
t.Fatalf("Gas [%v]: Gas not found", tx.Gas())
}
if tx.GasPrice().Uint64() != data.GasPrice {
t.Fatalf("Gas Price [%v]: Gas price not found", tx.GasPrice().String())
}
if block1.GasLimit() != data.GasLimit {
t.Fatalf("Gas Limit [%v]: Gas limit not found", block1.GasLimit())
}
if block1.Hash().String() != data.BlockHash {
t.Fatalf("Block Hash [%v]: Block hash not found", block1.Hash().String())
}
if block1.Number().String() != data.BlockNumber {
t.Fatalf("Block Number [%v]: Block number not found", block1.Number().String())
}
if tx.Value().String() != data.Amount {
t.Fatalf("Amount [%v]: Amount not found", tx.Value().String())
}
if tx.Cost().Uint64() != data.Cost {
t.Fatalf("Cost [%v]: Cost not found", tx.Cost().String())
}
var status string
if receipt.Status == 1 {
status = "SUCCESS"
}
if receipt.Status == 0 {
status = "FAIL"
}
if status != data.Status {
t.Fatalf("Receipt status [%v]: Receipt status not found", status)
}
var isContract bool
if tx.To() != nil {
isContract = false
} else {
isContract = true
}
if isContract != data.IsContract {
t.Fatalf("isContract [%v]: isContract bool is incorrect", isContract)
}
} }
if tx.From().String() != data.From { if getAllTx := core.SGetAllTransactions(sqldb); len(getAllTx) == 0 {
t.Fatalf("From Addr [%v]: From addr not found", tx.From().String()) t.Fatalf("GetAllTransactions [%v]: GetAllTransactions did not return correctly", getAllTx)
} }
if tx.To().String() != data.ToGet { })
t.Fatalf("To Addr [%v]: To addr not found", tx.To().String()) t.Run("TestAccountsToReturnAccounts", func(t *testing.T) {
} for _, tx := range txs {
if tx.Nonce() != data.Nonce { fmt.Println("test account", tx.To().String())
t.Fatalf("Nonce [%v]: Nonce not found", tx.Nonce()) accountAddrTo := core.SGetAccount(sqldb, tx.To().String())
} byts := []byte(accountAddrTo)
if tx.Gas() != data.Gas { var accountDataTo core.SAccounts
t.Fatalf("Gas [%v]: Gas not found", tx.Gas()) json.Unmarshal(byts, &accountDataTo)
}
if tx.GasPrice().Uint64() != data.GasPrice {
t.Fatalf("Gas Price [%v]: Gas price not found", tx.GasPrice().String())
}
if block.GasLimit() != data.GasLimit {
t.Fatalf("Gas Limit [%v]: Gas limit not found", block.GasLimit())
}
if block.Hash().String() != data.BlockHash {
t.Fatalf("Block Hash [%v]: Block hash not found", block.Hash().String())
}
if block.Number().String() != data.BlockNumber {
t.Fatalf("Block Number [%v]: Block number not found", block.Number().String())
}
if tx.Value().String() != data.Amount {
t.Fatalf("Amount [%v]: Amount not found", tx.Value().String())
}
if tx.Cost().Uint64() != data.Cost {
t.Fatalf("Cost [%v]: Cost not found", tx.Cost().String())
}
var status string
if receipt1.Status == 1 {
status = "SUCCESS"
}
if receipt1.Status == 0 {
status = "FAIL"
}
if status != data.Status {
t.Fatalf("Receipt status [%v]: Receipt status not found", status)
}
var isContract bool
if tx.To() != nil {
isContract = false
} else {
isContract = true
}
if isContract != data.IsContract {
t.Fatalf("isContract [%v]: isContract bool is incorrect", isContract)
}
}
if getAllTx := core.SGetAllTransactions(sqldb); len(getAllTx) == 0 { if strings.ToLower(tx.To().String()) != accountDataTo.Addr {
t.Fatalf("GetAllTransactions [%v]: GetAllTransactions did not return correctly", getAllTx) t.Fatalf("To address [%v]: To address not found", accountDataTo.Addr)
} }
ClearTables() if tx.Value().String() != accountDataTo.Balance {
}) t.Fatalf("To address balance [%v]: To address balance not found", accountDataTo.Balance)
}
t.Run("TestAccountsToReturnAccounts",func(t *testing.T) { if strconv.FormatUint(tx.Nonce(), 10) != accountDataTo.AccountNonce {
key, _ := crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") t.Fatalf("To account nonce [%v]: To account nonce not found", accountDataTo.AccountNonce)
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, 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,
}
receipts := []*types.Receipt{receipt1}
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)
} }
accountAddrFrom := core.SGetAccount(sqldb, fromAddr)
byts := []byte(accountAddrFrom)
var accountDataFrom core.SAccounts
json.Unmarshal(byts, &accountDataFrom)
if toAddr1.String() != tx1.To().String() { if fromAddr != accountDataFrom.Addr {
t.Fatalf("To address [%v]: To address not found", toAddr1.String()) t.Fatalf("To address [%v]: To address not found", accountDataFrom.Addr)
} }
accountAddrTo, _ := core.InnerSGetAccount(sqldb, toAddr1.String()) if fromAddrEndBalance != accountDataFrom.Balance {
//ewAccountNonceReceiver.Add(accountR, nonceIncrement) t.Fatalf("To address balance [%v]: To address balance not found", accountDataFrom.Balance)
addedAmount := new(big.Int) }
toAmountPrevious1, _ := strconv.ParseUint(toAmountPrev1, 10, 64) if fromAddrEndNonce != accountDataFrom.AccountNonce {
b := new(big.Int).SetUint64(toAmountPrevious1) t.Fatalf("To account nonce [%v]: To account nonce not found", accountDataFrom.AccountNonce)
addedAmount.Add(toAmount1, b) }
toBalance := new(big.Int) if getAllAccountTxs := core.SGetAccountTxs(sqldb, toAddr.String()); len(getAllAccountTxs) == 0 {
toBalance, _ = toBalance.SetString(accountAddrTo.Balance, 10) t.Fatalf("GetAccountTxs [%v]: GetAccountTxs did not return correctly", getAllAccountTxs)
}
if toBalance.Cmp(addedAmount) != 0 { if getAllAccounts := core.SGetAllAccounts(sqldb); len(getAllAccounts) == 0 {
t.Fatalf("To address balance [%v]: To address balance not correct FFO", toBalance) t.Fatalf("GetAllAccounts [%v]: GetAllAccounts did not return correctly", getAllAccounts)
} }
})
//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 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)
}
ClearTables()
})
ClearTables()
} }