Skip to content
This repository has been archived by the owner on Oct 26, 2020. It is now read-only.

Commit

Permalink
adds simulator + adds account tree + adds processors
Browse files Browse the repository at this point in the history
  • Loading branch information
vaibhavchellani committed Jun 1, 2020
1 parent ef7abff commit a3df492
Show file tree
Hide file tree
Showing 25 changed files with 1,213 additions and 340 deletions.
33 changes: 25 additions & 8 deletions aggregator/aggregator.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ type Aggregator struct {
core.BaseService

// contract caller to interact with contracts
loadedBazooka bazooka.Bazooka
LoadedBazooka bazooka.Bazooka

// DB instance
DB core.DB
Expand All @@ -39,14 +39,14 @@ type Aggregator struct {
func NewAggregator(db core.DB) *Aggregator {
// create logger
logger := common.Logger.With("module", AggregatingService)
loadedBazooka, err := bazooka.NewPreLoadedBazooka()
LoadedBazooka, err := bazooka.NewPreLoadedBazooka()
if err != nil {
panic(err)
}
aggregator := &Aggregator{}
aggregator.BaseService = *core.NewBaseService(logger, AggregatingService, aggregator)
aggregator.DB = db
aggregator.loadedBazooka = loadedBazooka
aggregator.LoadedBazooka = LoadedBazooka
return aggregator
}

Expand Down Expand Up @@ -96,11 +96,21 @@ func (a *Aggregator) pickBatch() {
err = a.CheckTx(txs)
if err != nil {
fmt.Println("Error while processing tx", "error", err)
return
}

// Step-3
// Finally create a merkel root of all updated leafs and push batch on-chain

rootAcc, err := a.DB.GetRoot()
if err != nil {
fmt.Println("Error while getting root", "error", err)
return
}
err = a.LoadedBazooka.SubmitBatch(rootAcc.HashToByteArray(), txs)
if err != nil {
fmt.Println("Error while submitting batch", "error", err)
return
}
}

// CheckTx fetches all the data required to validate tx from smart contact
Expand All @@ -110,32 +120,39 @@ func (a *Aggregator) CheckTx(txs []core.Tx) error {
if err != nil {
return err
}
a.Logger.Debug("Latest root", "root", rootAcc.Hash)

currentRoot, err := core.HexToByteArray(rootAcc.Hash)
if err != nil {
return err
}
currentAccountTreeRoot, err := core.HexToByteArray(rootAcc.PublicKeyHash)
if err != nil {
return err
}

for _, tx := range txs {
fromAccProof, toAccProof, PDAproof, err := a.DB.GetTxVerificationData(tx)
if err != nil {
fmt.Println(err)
fmt.Println("here", err)
return err
}

updatedRoot, updatedFromAcc, updatedToAcc, err := a.loadedBazooka.ProcessTx(currentRoot, tx, fromAccProof, toAccProof, PDAproof)
a.Logger.Debug("Fetched latest account proofs", "tx", tx.String(), "fromMP", fromAccProof, "toMP", toAccProof, "PDAProof", PDAproof)
updatedRoot, updatedFromAcc, updatedToAcc, err := a.LoadedBazooka.ProcessTx(currentRoot, currentAccountTreeRoot, tx, fromAccProof, toAccProof, PDAproof)
if err != nil {
fmt.Println(err)
fmt.Println("here2", err)
return err
}

err = a.DB.UpdateAccount(updatedFromAcc)
if err != nil {
fmt.Println("here3", err)
return err
}

err = a.DB.UpdateAccount(updatedToAcc)
if err != nil {
fmt.Println("here4", err)
return err
}

Expand Down
20 changes: 18 additions & 2 deletions bazooka/call.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,11 +68,23 @@ func (b *Bazooka) FetchBatchInputData(txHash ethCmn.Hash) (txs [][]byte, err err

// ProcessTx calls the ProcessTx function on the contract to verify the tx
// returns the updated accounts and the new balance root
func (b *Bazooka) ProcessTx(balanceTreeRoot core.ByteArray, tx core.Tx, fromMerkleProof, toMerkleProof core.AccountMerkleProof, pdaProof core.PDAMerkleProof) (newBalanceRoot core.ByteArray, from, to core.UserAccount, err error) {
updatedRoot, newBalFrom, newBalTo, IsValidTx, err := b.CoordinatorProxy.ProcessTx(nil, balanceTreeRoot, balanceTreeRoot, tx.ToABIVersion(int64(tx.From), int64(tx.To)), pdaProof.ToABIVersion(), fromMerkleProof.ToABIVersion(), toMerkleProof.ToABIVersion())
func (b *Bazooka) ProcessTx(balanceTreeRoot, accountTreeRoot core.ByteArray, tx core.Tx, fromMerkleProof, toMerkleProof core.AccountMerkleProof, pdaProof core.PDAMerkleProof) (newBalanceRoot core.ByteArray, from, to core.UserAccount, err error) {
txABIVersion := tx.ToABIVersion(int64(tx.From), int64(tx.To))

updatedRoot, newBalFrom, newBalTo, IsValidTx, err := b.CoordinatorProxy.ProcessTx(nil,
balanceTreeRoot,
accountTreeRoot,
txABIVersion,
pdaProof.ToABIVersion(),
fromMerkleProof.ToABIVersion(),
toMerkleProof.ToABIVersion(),
)
if err != nil {
return
}

b.log.Info("Processed transaction", "success", IsValidTx, "newRoot", updatedRoot)

if !IsValidTx {
return newBalanceRoot, from, to, errors.New("Tx is invalid")
}
Expand All @@ -87,3 +99,7 @@ func (b *Bazooka) ProcessTx(balanceTreeRoot core.ByteArray, tx core.Tx, fromMerk

return newBalanceRoot, from, to, nil
}

func (b *Bazooka) VerifyPDAProof(accountsRoot core.ByteArray, leaf core.ByteArray, proofpath *big.Int, siblings [][32]byte) (bool, error) {
return b.BalanceTree.VerifyLeaf(nil, accountsRoot, leaf, proofpath, siblings)
}
15 changes: 11 additions & 4 deletions bazooka/tx.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ func (b *Bazooka) FireDepositFinalisation(TBreplaced core.UserAccount, siblings
"atDepth",
subTreeHeight,
)

// TODO check latest batch on-chain and if we need to push new batch

depositSubTreeHeight := big.NewInt(0)
depositSubTreeHeight.SetUint64(subTreeHeight)
var siblingData [][32]byte
Expand All @@ -35,18 +38,22 @@ func (b *Bazooka) FireDepositFinalisation(TBreplaced core.UserAccount, siblings

accountProof := coordinatorproxy.TypesAccountMerkleProof{}
accountProof.AccountIP.PathToAccount = core.StringToBigInt(TBreplaced.Path)
accountProof.AccountIP.Account = TBreplaced.ToABIAccount()
accountProof.Siblings = siblingData
b.log.Debug("Account proof created", "accountProofPath", accountProof.AccountIP.PathToAccount, "siblings", accountProof.Siblings)
data, err := b.ContractABI[common.COORDINATOR_PROXY].Pack("finaliseDepositsAndSubmitBatch", depositSubTreeHeight, accountProof)
data, err := b.ContractABI[common.ROLLUP_CONTRACT_KEY].Pack("finaliseDepositsAndSubmitBatch", depositSubTreeHeight, accountProof)
if err != nil {
return err
}

coordinatorProxyAddr := ethCmn.HexToAddress(config.GlobalCfg.CoordinatorProxyAddress)
stakeAmount := big.NewInt(0)
stakeAmount.SetString("32000000000000000000", 10)

// generate call msg
callMsg := ethereum.CallMsg{
To: &coordinatorProxyAddr,
Data: data,
To: &coordinatorProxyAddr,
Data: data,
Value: stakeAmount,
}

auth, err := b.GenerateAuthObj(b.EthClient, callMsg)
Expand Down
1 change: 1 addition & 0 deletions bazooka/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ func (b *Bazooka) GenerateAuthObj(client *ethclient.Client, callMsg ethereum.Cal
if err != nil {
return
}

// fetch nonce
nonce, err := client.PendingNonceAt(context.Background(), fromAddress)
if err != nil {
Expand Down
36 changes: 36 additions & 0 deletions cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,14 @@ package main

import (
"fmt"
"net/http"
"os"
"os/signal"

"github.com/BOPR/common"
"github.com/BOPR/config"
"github.com/BOPR/simulator"
"github.com/gorilla/mux"

"github.com/spf13/cobra"
"github.com/spf13/viper"
Expand Down Expand Up @@ -43,6 +47,7 @@ func main() {
rootCmd.AddCommand(InitCmd())
rootCmd.AddCommand(StartCmd())
rootCmd.AddCommand(ResetCmd())
rootCmd.AddCommand(StartSimulatorCmd())
rootCmd.AddCommand(AddGenesisAcccountsCmd())

rootCmd.AddCommand(SendTransferTx())
Expand Down Expand Up @@ -107,3 +112,34 @@ func AddGenesisAcccountsCmd() *cobra.Command {
},
}
}

// StartSimulatorCmd starts the simulator
func StartSimulatorCmd() *cobra.Command {
return &cobra.Command{
Use: "start-simulating",
Short: "starts a simulator that sends transaction to the rollupchain periodically",
Run: func(cmd *cobra.Command, args []string) {
sim := simulator.NewSimulator()
if err := sim.Start(); err != nil {
panic(err)
}

// go routine to catch signal
catchSignal := make(chan os.Signal, 1)
signal.Notify(catchSignal, os.Interrupt)
go func() {
for range catchSignal {
sim.Stop()
// exit
os.Exit(1)
}
}()

r := mux.NewRouter()
err := http.ListenAndServe(":4000", r)
if err != nil {
panic(err)
}
},
}
}
21 changes: 13 additions & 8 deletions cmd/start.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ func StartCmd() *cobra.Command {
if err != nil {
panic(err)
}
fmt.Println("Server started on port 8080 🎉")
fmt.Println("Server started on port 3000 🎉")
},
}
}
Expand Down Expand Up @@ -140,7 +140,6 @@ func InitGlobalDBInstance() {

// init global DB instance
core.DBInstance = tempDB
fmt.Println("db instance populated", core.DBInstance)
}

func InitGlobalBazooka() {
Expand All @@ -162,15 +161,21 @@ func LoadGenesisData(genesis config.Genesis) {

// convert genesis accounts to user accounts
for _, account := range genesis.GenesisAccounts.Accounts {
// bz, err := core.ABIEncodePubkey(account.PublicKey)
// if err != nil {
// common.PanicIfError(err)
// }
pubkeyHash := core.ZERO_VALUE_LEAF.String()
allAccounts = append(
allAccounts,
core.UserAccount{
AccountID: account.ID,
Balance: account.Balance,
TokenType: account.TokenType,
Nonce: account.Nonce,
Status: account.Status,
PublicKey: account.PublicKey,
AccountID: account.ID,
Balance: account.Balance,
TokenType: account.TokenType,
Nonce: account.Nonce,
Status: account.Status,
PublicKey: account.PublicKey,
PublicKeyHash: pubkeyHash,
},
)
}
Expand Down
2 changes: 1 addition & 1 deletion contracts/coordinatorproxy/coordinatorproxy.abi
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
[
[
{
"inputs": [
{
Expand Down
Loading

0 comments on commit a3df492

Please sign in to comment.