mirror of
https://github.com/arnaucube/hermez-node.git
synced 2026-02-07 03:16:45 +01:00
Rename Transakcio to Til for a easier usage
Rename Transakcio to Til for a easier usage, also change til.TestContext to til.Context, and til.NewTestContext to til.NewContext.
This commit is contained in:
115
test/til/README.md
Normal file
115
test/til/README.md
Normal file
@@ -0,0 +1,115 @@
|
||||
# Til (Test instructions language)
|
||||
Language to define sets of instructions to simulate Hermez transactions (L1 & L2) with real data.
|
||||
|
||||
## Syntax
|
||||
### Global
|
||||
- Set type definition
|
||||
- Blockchain: generate the transactions that would come from the Hermez smart contract on the blockchain.
|
||||
```
|
||||
Type: Blockchain
|
||||
```
|
||||
- PoolL2: generate the transactions that would come from the Pool of L2Txs
|
||||
```
|
||||
Type: PoolL2
|
||||
```
|
||||
|
||||
### Blockchain set of instructions
|
||||
Available instructions:
|
||||
```go
|
||||
Type: Blockchain
|
||||
|
||||
// register the TokenID:
|
||||
RegisterToken(1)
|
||||
|
||||
// deposit of TokenID=1, on the account of tokenID=1 for the user A, of an
|
||||
// amount of 50 units
|
||||
CreateAccountDeposit(1) A: 50
|
||||
|
||||
// create the account of TokenID=1 for the user B, deposit of TokenID=1, on the
|
||||
// account of tokenID=1 for the user B, of an amount of 40 units and atomically
|
||||
// transfer 10 units to account of tokenID=1 for the user A, paying a fee of 2
|
||||
CreateAccountDepositTransfer(1) B-A: 40, 10 (2)
|
||||
|
||||
// transaction generated by the Coordinator, create account for user User0 for
|
||||
// the TokenID=2, with a deposit of 0
|
||||
CreateAccountDepositCoordinator(2) User0
|
||||
|
||||
|
||||
// deposit of TokenID=1, at the account A, of 6 units
|
||||
Deposit(1) A: 6
|
||||
|
||||
// deposit of TokenID=1, on the account of tokenID=1 for the user B, of an
|
||||
// amount of 6 units and atomically transfer 10 units to account of tokenID=1 for
|
||||
// the user A, paying a fee of 2
|
||||
DepositTransfer(1) B-A: 6, 4 (2)
|
||||
|
||||
// transfer of TokenID=1, from the account A to B (for that token), of 6 units,
|
||||
// paying a fee of 3. Transaction will be a L2Tx
|
||||
Transfer(1) A-B: 6 (3)
|
||||
|
||||
// exit of TokenID=1, from the account A (for that token), of 5 units.
|
||||
// Transaction will be a L2Tx
|
||||
Exit(1) A: 5
|
||||
|
||||
// force-transfer of TokenID=1, from the account A to B (for that token), of 6
|
||||
// units, paying a fee of 3. Transaction will be L1UserTx of ForceTransfer type
|
||||
ForceTransfer(1) A-B: 6 (3)
|
||||
|
||||
// force-exit of TokenID=1, from the account A (for that token), of 5 units.
|
||||
// Transaction will be L1UserTx of ForceExit type
|
||||
ForceExit(1) A: 5
|
||||
|
||||
// advance one batch, forging without L1UserTxs, only can contain L2Txs and
|
||||
// L1CoordinatorTxs
|
||||
> batch
|
||||
|
||||
// advance one batch, forging with L1UserTxs (and L2Txs and L1CoordinatorTxs)
|
||||
> batchL1
|
||||
|
||||
// advance an ethereum block
|
||||
> block
|
||||
```
|
||||
|
||||
### PoolL2 set of instructions
|
||||
Available instructions:
|
||||
```go
|
||||
Type: PoolL2
|
||||
|
||||
// transfer of TokenID=1, from the account A to B (for that token), of 6 units,
|
||||
// paying a fee of 4
|
||||
PoolTransfer(1) A-B: 6 (4)
|
||||
|
||||
// exit of TokenID=1, from the account A (for that token), of 3 units
|
||||
PoolExit(1) A: 3
|
||||
```
|
||||
|
||||
## Usage
|
||||
```go
|
||||
// create a new til.Context
|
||||
tc := til.NewContext(eth.RollupConstMaxL1UserTx)
|
||||
|
||||
// generate Blockchain blocks data from the common.SetBlockcahin0 instructions set
|
||||
blocks, err = tc.GenerateBlocks(common.SetBlockchain0)
|
||||
assert.Nil(t, err)
|
||||
|
||||
// generate PoolL2 transactions data from the common.SetPool0 instructions set
|
||||
poolL2Txs, err = tc.GenerateBlocks(common.SetPool0)
|
||||
assert.Nil(t, err)
|
||||
```
|
||||
|
||||
Where `blocks` will contain:
|
||||
```go
|
||||
// BatchData contains the information of a Batch
|
||||
type BatchData struct {
|
||||
L1CoordinatorTxs []common.L1Tx
|
||||
L2Txs []common.L2Tx
|
||||
CreatedAccounts []common.Account
|
||||
}
|
||||
|
||||
// BlockData contains the information of a Block
|
||||
type BlockData struct {
|
||||
L1UserTxs []common.L1Tx
|
||||
Batches []BatchData
|
||||
RegisteredTokens []common.Token
|
||||
}
|
||||
```
|
||||
545
test/til/lang.go
Normal file
545
test/til/lang.go
Normal file
@@ -0,0 +1,545 @@
|
||||
package til
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"sort"
|
||||
"strconv"
|
||||
|
||||
"github.com/hermeznetwork/hermez-node/common"
|
||||
"github.com/hermeznetwork/hermez-node/log"
|
||||
)
|
||||
|
||||
var eof = rune(0)
|
||||
var errof = fmt.Errorf("eof in parseline")
|
||||
var commentLine = fmt.Errorf("comment in parseline") //nolint:golint
|
||||
var newEventLine = fmt.Errorf("newEventLine") //nolint:golint
|
||||
var setTypeLine = fmt.Errorf("setTypeLine") //nolint:golint
|
||||
|
||||
// setType defines the type of the set
|
||||
type setType string
|
||||
|
||||
// setTypeBlockchain defines the type 'Blockchain' of the set
|
||||
var setTypeBlockchain = setType("Blockchain")
|
||||
|
||||
// setTypePoolL2 defines the type 'PoolL2' of the set
|
||||
var setTypePoolL2 = setType("PoolL2")
|
||||
|
||||
// typeNewBatch is used for testing purposes only, and represents the
|
||||
// common.TxType of a new batch
|
||||
var typeNewBatch common.TxType = "InstrTypeNewBatch"
|
||||
|
||||
// typeNewBatchL1 is used for testing purposes only, and represents the
|
||||
// common.TxType of a new batch
|
||||
var typeNewBatchL1 common.TxType = "InstrTypeNewBatchL1"
|
||||
|
||||
// typeNewBlock is used for testing purposes only, and represents the
|
||||
// common.TxType of a new ethereum block
|
||||
var typeNewBlock common.TxType = "InstrTypeNewBlock"
|
||||
|
||||
// typeRegisterToken is used for testing purposes only, and represents the
|
||||
// common.TxType of a new Token regsitration
|
||||
// It has 'nolint:gosec' as the string 'Token' triggers gosec as a potential leaked Token (which is not the case)
|
||||
var typeRegisterToken common.TxType = "InstrTypeRegisterToken" //nolint:gosec
|
||||
|
||||
var txTypeCreateAccountDepositCoordinator common.TxType = "TypeCreateAccountDepositCoordinator"
|
||||
|
||||
//nolint
|
||||
const (
|
||||
ILLEGAL token = iota
|
||||
WS
|
||||
EOF
|
||||
|
||||
IDENT // val
|
||||
)
|
||||
|
||||
// instruction is the data structure that represents one line of code
|
||||
type instruction struct {
|
||||
lineNum int
|
||||
literal string
|
||||
from string
|
||||
to string
|
||||
amount uint64
|
||||
loadAmount uint64
|
||||
fee uint8
|
||||
tokenID common.TokenID
|
||||
typ common.TxType // D: Deposit, T: Transfer, E: ForceExit
|
||||
}
|
||||
|
||||
// parsedSet contains the full Set of Instructions representing a full code
|
||||
type parsedSet struct {
|
||||
// type string
|
||||
instructions []instruction
|
||||
accounts []string
|
||||
}
|
||||
|
||||
func (i instruction) String() string {
|
||||
buf := bytes.NewBufferString("")
|
||||
fmt.Fprintf(buf, "Type: %s, ", i.typ)
|
||||
fmt.Fprintf(buf, "From: %s, ", i.from)
|
||||
if i.typ == common.TxTypeTransfer ||
|
||||
i.typ == common.TxTypeDepositTransfer ||
|
||||
i.typ == common.TxTypeCreateAccountDepositTransfer {
|
||||
fmt.Fprintf(buf, "To: %s, ", i.to)
|
||||
}
|
||||
|
||||
if i.typ == common.TxTypeDeposit ||
|
||||
i.typ == common.TxTypeDepositTransfer ||
|
||||
i.typ == common.TxTypeCreateAccountDepositTransfer {
|
||||
fmt.Fprintf(buf, "LoadAmount: %d, ", i.loadAmount)
|
||||
}
|
||||
if i.typ != common.TxTypeDeposit {
|
||||
fmt.Fprintf(buf, "Amount: %d, ", i.amount)
|
||||
}
|
||||
if i.typ == common.TxTypeTransfer ||
|
||||
i.typ == common.TxTypeDepositTransfer ||
|
||||
i.typ == common.TxTypeCreateAccountDepositTransfer {
|
||||
fmt.Fprintf(buf, "Fee: %d, ", i.fee)
|
||||
}
|
||||
fmt.Fprintf(buf, "TokenID: %d\n", i.tokenID)
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
// Raw returns a string with the raw representation of the Instruction
|
||||
func (i instruction) raw() string {
|
||||
buf := bytes.NewBufferString("")
|
||||
fmt.Fprintf(buf, "%s", i.typ)
|
||||
fmt.Fprintf(buf, "(%d)", i.tokenID)
|
||||
fmt.Fprintf(buf, "%s", i.from)
|
||||
if i.typ == common.TxTypeTransfer ||
|
||||
i.typ == common.TxTypeDepositTransfer ||
|
||||
i.typ == common.TxTypeCreateAccountDepositTransfer {
|
||||
fmt.Fprintf(buf, "-%s", i.to)
|
||||
}
|
||||
fmt.Fprintf(buf, ":")
|
||||
if i.typ == common.TxTypeDeposit ||
|
||||
i.typ == common.TxTypeDepositTransfer ||
|
||||
i.typ == common.TxTypeCreateAccountDepositTransfer {
|
||||
fmt.Fprintf(buf, "%d", i.loadAmount)
|
||||
}
|
||||
if i.typ != common.TxTypeDeposit {
|
||||
fmt.Fprintf(buf, "%d", i.amount)
|
||||
}
|
||||
if i.typ == common.TxTypeTransfer {
|
||||
fmt.Fprintf(buf, "(%d)", i.fee)
|
||||
}
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
type token int
|
||||
|
||||
type scanner struct {
|
||||
r *bufio.Reader
|
||||
}
|
||||
|
||||
func isWhitespace(ch rune) bool {
|
||||
return ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r' || ch == '\v' || ch == '\f'
|
||||
}
|
||||
|
||||
func isLetter(ch rune) bool {
|
||||
return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')
|
||||
}
|
||||
|
||||
func isComment(ch rune) bool {
|
||||
return ch == '/'
|
||||
}
|
||||
|
||||
func isDigit(ch rune) bool {
|
||||
return (ch >= '0' && ch <= '9')
|
||||
}
|
||||
|
||||
// newScanner creates a new scanner with the given io.Reader
|
||||
func newScanner(r io.Reader) *scanner {
|
||||
return &scanner{r: bufio.NewReader(r)}
|
||||
}
|
||||
|
||||
func (s *scanner) read() rune {
|
||||
ch, _, err := s.r.ReadRune()
|
||||
if err != nil {
|
||||
return eof
|
||||
}
|
||||
return ch
|
||||
}
|
||||
|
||||
func (s *scanner) unread() {
|
||||
_ = s.r.UnreadRune()
|
||||
}
|
||||
|
||||
// scan returns the token and literal string of the current value
|
||||
func (s *scanner) scan() (tok token, lit string) {
|
||||
ch := s.read()
|
||||
|
||||
if isWhitespace(ch) {
|
||||
// space
|
||||
s.unread()
|
||||
return s.scanWhitespace()
|
||||
} else if isLetter(ch) || isDigit(ch) {
|
||||
// letter/digit
|
||||
s.unread()
|
||||
return s.scanIndent()
|
||||
} else if isComment(ch) {
|
||||
// comment
|
||||
s.unread()
|
||||
return s.scanIndent()
|
||||
}
|
||||
|
||||
if ch == eof {
|
||||
return EOF, ""
|
||||
}
|
||||
|
||||
return ILLEGAL, string(ch)
|
||||
}
|
||||
|
||||
func (s *scanner) scanWhitespace() (token token, lit string) {
|
||||
var buf bytes.Buffer
|
||||
buf.WriteRune(s.read())
|
||||
|
||||
for {
|
||||
if ch := s.read(); ch == eof {
|
||||
break
|
||||
} else if !isWhitespace(ch) {
|
||||
s.unread()
|
||||
break
|
||||
} else {
|
||||
_, _ = buf.WriteRune(ch)
|
||||
}
|
||||
}
|
||||
return WS, buf.String()
|
||||
}
|
||||
|
||||
func (s *scanner) scanIndent() (tok token, lit string) {
|
||||
var buf bytes.Buffer
|
||||
buf.WriteRune(s.read())
|
||||
|
||||
for {
|
||||
if ch := s.read(); ch == eof {
|
||||
break
|
||||
} else if !isLetter(ch) && !isDigit(ch) {
|
||||
s.unread()
|
||||
break
|
||||
} else {
|
||||
_, _ = buf.WriteRune(ch)
|
||||
}
|
||||
}
|
||||
|
||||
if len(buf.String()) == 1 {
|
||||
return token(rune(buf.String()[0])), buf.String()
|
||||
}
|
||||
return IDENT, buf.String()
|
||||
}
|
||||
|
||||
// parser defines the parser
|
||||
type parser struct {
|
||||
s *scanner
|
||||
buf struct {
|
||||
tok token
|
||||
lit string
|
||||
n int
|
||||
}
|
||||
}
|
||||
|
||||
// newParser creates a new parser from a io.Reader
|
||||
func newParser(r io.Reader) *parser {
|
||||
return &parser{s: newScanner(r)}
|
||||
}
|
||||
|
||||
func (p *parser) scan() (tok token, lit string) {
|
||||
// if there is a token in the buffer return it
|
||||
if p.buf.n != 0 {
|
||||
p.buf.n = 0
|
||||
return p.buf.tok, p.buf.lit
|
||||
}
|
||||
tok, lit = p.s.scan()
|
||||
|
||||
p.buf.tok, p.buf.lit = tok, lit
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func (p *parser) scanIgnoreWhitespace() (tok token, lit string) {
|
||||
tok, lit = p.scan()
|
||||
if tok == WS {
|
||||
tok, lit = p.scan()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// parseLine parses the current line
|
||||
func (p *parser) parseLine(setType setType) (*instruction, error) {
|
||||
c := &instruction{}
|
||||
tok, lit := p.scanIgnoreWhitespace()
|
||||
if tok == EOF {
|
||||
return nil, errof
|
||||
}
|
||||
c.literal += lit
|
||||
if lit == "/" {
|
||||
_, _ = p.s.r.ReadString('\n')
|
||||
return nil, commentLine
|
||||
} else if lit == ">" {
|
||||
if setType == setTypePoolL2 {
|
||||
return c, fmt.Errorf("Unexpected '>' at PoolL2Txs set")
|
||||
}
|
||||
_, lit = p.scanIgnoreWhitespace()
|
||||
if lit == "batch" {
|
||||
_, _ = p.s.r.ReadString('\n')
|
||||
return &instruction{typ: typeNewBatch}, newEventLine
|
||||
} else if lit == "batchL1" {
|
||||
_, _ = p.s.r.ReadString('\n')
|
||||
return &instruction{typ: typeNewBatchL1}, newEventLine
|
||||
} else if lit == "block" {
|
||||
_, _ = p.s.r.ReadString('\n')
|
||||
return &instruction{typ: typeNewBlock}, newEventLine
|
||||
} else {
|
||||
return c, fmt.Errorf("Unexpected '> %s', expected '> batch' or '> block'", lit)
|
||||
}
|
||||
} else if lit == "Type" {
|
||||
if err := p.expectChar(c, ":"); err != nil {
|
||||
return c, err
|
||||
}
|
||||
_, lit = p.scanIgnoreWhitespace()
|
||||
if lit == "Blockchain" {
|
||||
return &instruction{typ: "Blockchain"}, setTypeLine
|
||||
} else if lit == "PoolL2" {
|
||||
return &instruction{typ: "PoolL2"}, setTypeLine
|
||||
} else {
|
||||
return c, fmt.Errorf("Invalid set type: '%s'. Valid set types: 'Blockchain', 'PoolL2'", lit)
|
||||
}
|
||||
} else if lit == "RegisterToken" {
|
||||
if err := p.expectChar(c, "("); err != nil {
|
||||
return c, err
|
||||
}
|
||||
_, lit = p.scanIgnoreWhitespace()
|
||||
c.literal += lit
|
||||
tidI, err := strconv.Atoi(lit)
|
||||
if err != nil {
|
||||
line, _ := p.s.r.ReadString('\n')
|
||||
c.literal += line
|
||||
return c, err
|
||||
}
|
||||
c.tokenID = common.TokenID(tidI)
|
||||
if err := p.expectChar(c, ")"); err != nil {
|
||||
return c, err
|
||||
}
|
||||
c.typ = typeRegisterToken
|
||||
line, _ := p.s.r.ReadString('\n')
|
||||
c.literal += line
|
||||
return c, newEventLine
|
||||
}
|
||||
|
||||
if setType == "" {
|
||||
return c, fmt.Errorf("Set type not defined")
|
||||
}
|
||||
transferring := false
|
||||
|
||||
if setType == setTypeBlockchain {
|
||||
switch lit {
|
||||
case "Deposit":
|
||||
c.typ = common.TxTypeDeposit
|
||||
case "Exit":
|
||||
c.typ = common.TxTypeExit
|
||||
case "Transfer":
|
||||
c.typ = common.TxTypeTransfer
|
||||
transferring = true
|
||||
case "CreateAccountDeposit":
|
||||
c.typ = common.TxTypeCreateAccountDeposit
|
||||
case "CreateAccountDepositTransfer":
|
||||
c.typ = common.TxTypeCreateAccountDepositTransfer
|
||||
transferring = true
|
||||
case "CreateAccountDepositCoordinator":
|
||||
c.typ = txTypeCreateAccountDepositCoordinator
|
||||
// transferring is false, as the Coordinator tx transfer will be 0
|
||||
case "DepositTransfer":
|
||||
c.typ = common.TxTypeDepositTransfer
|
||||
transferring = true
|
||||
case "ForceTransfer":
|
||||
c.typ = common.TxTypeForceTransfer
|
||||
case "ForceExit":
|
||||
c.typ = common.TxTypeForceExit
|
||||
default:
|
||||
return c, fmt.Errorf("Unexpected Blockchain tx type: %s", lit)
|
||||
}
|
||||
} else if setType == setTypePoolL2 {
|
||||
switch lit {
|
||||
case "PoolTransfer":
|
||||
c.typ = common.TxTypeTransfer
|
||||
transferring = true
|
||||
case "PoolExit":
|
||||
c.typ = common.TxTypeExit
|
||||
default:
|
||||
return c, fmt.Errorf("Unexpected PoolL2 tx type: %s", lit)
|
||||
}
|
||||
} else {
|
||||
return c, fmt.Errorf("Invalid set type: '%s'. Valid set types: 'Blockchain', 'PoolL2'", setType)
|
||||
}
|
||||
|
||||
if err := p.expectChar(c, "("); err != nil {
|
||||
return c, err
|
||||
}
|
||||
_, lit = p.scanIgnoreWhitespace()
|
||||
c.literal += lit
|
||||
tidI, err := strconv.Atoi(lit)
|
||||
if err != nil {
|
||||
line, _ := p.s.r.ReadString('\n')
|
||||
c.literal += line
|
||||
return c, err
|
||||
}
|
||||
c.tokenID = common.TokenID(tidI)
|
||||
if err := p.expectChar(c, ")"); err != nil {
|
||||
return c, err
|
||||
}
|
||||
_, lit = p.scanIgnoreWhitespace()
|
||||
c.literal += lit
|
||||
c.from = lit
|
||||
if c.typ == txTypeCreateAccountDepositCoordinator {
|
||||
line, _ := p.s.r.ReadString('\n')
|
||||
c.literal += line
|
||||
return c, nil
|
||||
}
|
||||
_, lit = p.scanIgnoreWhitespace()
|
||||
c.literal += lit
|
||||
if transferring {
|
||||
if lit != "-" {
|
||||
return c, fmt.Errorf("Expected '-', found '%s'", lit)
|
||||
}
|
||||
_, lit = p.scanIgnoreWhitespace()
|
||||
c.literal += lit
|
||||
c.to = lit
|
||||
_, lit = p.scanIgnoreWhitespace()
|
||||
c.literal += lit
|
||||
}
|
||||
if lit != ":" {
|
||||
line, _ := p.s.r.ReadString('\n')
|
||||
c.literal += line
|
||||
return c, fmt.Errorf("Expected ':', found '%s'", lit)
|
||||
}
|
||||
if c.typ == common.TxTypeDepositTransfer ||
|
||||
c.typ == common.TxTypeCreateAccountDepositTransfer {
|
||||
// deposit case
|
||||
_, lit = p.scanIgnoreWhitespace()
|
||||
c.literal += lit
|
||||
loadAmount, err := strconv.Atoi(lit)
|
||||
if err != nil {
|
||||
line, _ := p.s.r.ReadString('\n')
|
||||
c.literal += line
|
||||
return c, err
|
||||
}
|
||||
c.loadAmount = uint64(loadAmount)
|
||||
if err := p.expectChar(c, ","); err != nil {
|
||||
return c, err
|
||||
}
|
||||
}
|
||||
_, lit = p.scanIgnoreWhitespace()
|
||||
c.literal += lit
|
||||
amount, err := strconv.Atoi(lit)
|
||||
if err != nil {
|
||||
line, _ := p.s.r.ReadString('\n')
|
||||
c.literal += line
|
||||
return c, err
|
||||
}
|
||||
if c.typ == common.TxTypeDeposit ||
|
||||
c.typ == common.TxTypeCreateAccountDeposit {
|
||||
c.loadAmount = uint64(amount)
|
||||
} else {
|
||||
c.amount = uint64(amount)
|
||||
}
|
||||
if transferring {
|
||||
if err := p.expectChar(c, "("); err != nil {
|
||||
return c, err
|
||||
}
|
||||
_, lit = p.scanIgnoreWhitespace()
|
||||
c.literal += lit
|
||||
fee, err := strconv.Atoi(lit)
|
||||
if err != nil {
|
||||
line, _ := p.s.r.ReadString('\n')
|
||||
c.literal += line
|
||||
return c, err
|
||||
}
|
||||
if fee > common.MaxFeePlan-1 {
|
||||
line, _ := p.s.r.ReadString('\n')
|
||||
c.literal += line
|
||||
return c, fmt.Errorf("Fee %d can not be bigger than 255", fee)
|
||||
}
|
||||
c.fee = uint8(fee)
|
||||
|
||||
if err := p.expectChar(c, ")"); err != nil {
|
||||
return c, err
|
||||
}
|
||||
}
|
||||
|
||||
if tok == EOF {
|
||||
return nil, errof
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (p *parser) expectChar(c *instruction, ch string) error {
|
||||
_, lit := p.scanIgnoreWhitespace()
|
||||
c.literal += lit
|
||||
if lit != ch {
|
||||
line, _ := p.s.r.ReadString('\n')
|
||||
c.literal += line
|
||||
return fmt.Errorf("Expected '%s', found '%s'", ch, lit)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func idxTokenIDToString(idx string, tid common.TokenID) string {
|
||||
return idx + strconv.Itoa(int(tid))
|
||||
}
|
||||
|
||||
// parse parses through reader
|
||||
func (p *parser) parse() (*parsedSet, error) {
|
||||
ps := &parsedSet{}
|
||||
i := 0 // lines will start counting at line 1
|
||||
accounts := make(map[string]bool)
|
||||
var setTypeOfSet setType
|
||||
for {
|
||||
i++
|
||||
instruction, err := p.parseLine(setTypeOfSet)
|
||||
if err == errof {
|
||||
break
|
||||
}
|
||||
if err == setTypeLine {
|
||||
if setTypeOfSet != "" {
|
||||
return ps, fmt.Errorf("Line %d: Instruction of 'Type: %s' when there is already a previous instruction 'Type: %s' defined", i, instruction.typ, setTypeOfSet)
|
||||
}
|
||||
if instruction.typ == "PoolL2" {
|
||||
setTypeOfSet = setTypePoolL2
|
||||
} else if instruction.typ == "Blockchain" {
|
||||
setTypeOfSet = setTypeBlockchain
|
||||
} else {
|
||||
log.Fatalf("Line %d: Invalid set type: '%s'. Valid set types: 'Blockchain', 'PoolL2'", i, instruction.typ)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if err == commentLine {
|
||||
continue
|
||||
}
|
||||
instruction.lineNum = i
|
||||
if err == newEventLine {
|
||||
if instruction.typ == typeRegisterToken && instruction.tokenID == common.TokenID(0) {
|
||||
return ps, fmt.Errorf("Line %d: RegisterToken can not register TokenID 0", i)
|
||||
}
|
||||
ps.instructions = append(ps.instructions, *instruction)
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
return ps, fmt.Errorf("Line %d: %s, err: %s", i, instruction.literal, err.Error())
|
||||
}
|
||||
if setTypeOfSet == "" {
|
||||
return ps, fmt.Errorf("Line %d: Set type not defined", i)
|
||||
}
|
||||
ps.instructions = append(ps.instructions, *instruction)
|
||||
accounts[instruction.from] = true
|
||||
if instruction.typ == common.TxTypeTransfer { // type: Transfer
|
||||
accounts[instruction.to] = true
|
||||
}
|
||||
}
|
||||
for a := range accounts {
|
||||
ps.accounts = append(ps.accounts, a)
|
||||
}
|
||||
sort.Strings(ps.accounts)
|
||||
return ps, nil
|
||||
}
|
||||
215
test/til/lang_test.go
Normal file
215
test/til/lang_test.go
Normal file
@@ -0,0 +1,215 @@
|
||||
package til
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
var debug = false
|
||||
|
||||
func TestParseBlockchainTxs(t *testing.T) {
|
||||
s := `
|
||||
Type: Blockchain
|
||||
|
||||
// token registrations
|
||||
RegisterToken(1)
|
||||
RegisterToken(2)
|
||||
|
||||
// deposits
|
||||
Deposit(1) A: 10
|
||||
Deposit(2) A: 20
|
||||
Deposit(1) B: 5
|
||||
CreateAccountDeposit(1) C: 5
|
||||
CreateAccountDepositTransfer(1) D-A: 15, 10 (3)
|
||||
CreateAccountDepositCoordinator(1) E
|
||||
|
||||
// L2 transactions
|
||||
Transfer(1) A-B: 6 (1)
|
||||
Transfer(1) B-D: 3 (1)
|
||||
Transfer(1) A-E: 1 (1)
|
||||
|
||||
// set new batch
|
||||
> batch
|
||||
RegisterToken(3)
|
||||
|
||||
DepositTransfer(1) A-B: 15, 10 (1)
|
||||
Transfer(1) C-A : 3 (1)
|
||||
Transfer(2) A-B: 15 (1)
|
||||
|
||||
Deposit(1) User0: 20
|
||||
Deposit(3) User1: 20
|
||||
Transfer(1) User0-User1: 15 (1)
|
||||
Transfer(3) User1-User0: 15 (1)
|
||||
|
||||
> batch
|
||||
|
||||
Transfer(1) User1-User0: 1 (1)
|
||||
|
||||
> batch
|
||||
> block
|
||||
|
||||
// Exits
|
||||
Exit(1) A: 5
|
||||
`
|
||||
|
||||
parser := newParser(strings.NewReader(s))
|
||||
instructions, err := parser.parse()
|
||||
require.Nil(t, err)
|
||||
assert.Equal(t, 25, len(instructions.instructions))
|
||||
assert.Equal(t, 7, len(instructions.accounts))
|
||||
|
||||
if debug {
|
||||
fmt.Println(instructions)
|
||||
for _, instruction := range instructions.instructions {
|
||||
fmt.Println(instruction.raw())
|
||||
}
|
||||
}
|
||||
|
||||
assert.Equal(t, txTypeCreateAccountDepositCoordinator, instructions.instructions[7].typ)
|
||||
assert.Equal(t, typeNewBatch, instructions.instructions[11].typ)
|
||||
assert.Equal(t, "Deposit(1)User0:20", instructions.instructions[16].raw())
|
||||
assert.Equal(t, "Type: DepositTransfer, From: A, To: B, LoadAmount: 15, Amount: 10, Fee: 1, TokenID: 1\n", instructions.instructions[13].String())
|
||||
assert.Equal(t, "Type: Transfer, From: User1, To: User0, Amount: 15, Fee: 1, TokenID: 3\n", instructions.instructions[19].String())
|
||||
assert.Equal(t, "Transfer(2)A-B:15(1)", instructions.instructions[15].raw())
|
||||
assert.Equal(t, "Type: Transfer, From: A, To: B, Amount: 15, Fee: 1, TokenID: 2\n", instructions.instructions[15].String())
|
||||
assert.Equal(t, "Exit(1)A:5", instructions.instructions[24].raw())
|
||||
assert.Equal(t, "Type: Exit, From: A, Amount: 5, TokenID: 1\n", instructions.instructions[24].String())
|
||||
}
|
||||
|
||||
func TestParsePoolTxs(t *testing.T) {
|
||||
s := `
|
||||
Type: PoolL2
|
||||
PoolTransfer(1) A-B: 6 (1)
|
||||
PoolTransfer(2) A-B: 3 (3)
|
||||
PoolTransfer(1) B-D: 3 (1)
|
||||
PoolTransfer(1) C-D: 3 (1)
|
||||
PoolExit(1) A: 5
|
||||
`
|
||||
|
||||
parser := newParser(strings.NewReader(s))
|
||||
instructions, err := parser.parse()
|
||||
require.Nil(t, err)
|
||||
assert.Equal(t, 5, len(instructions.instructions))
|
||||
assert.Equal(t, 4, len(instructions.accounts))
|
||||
|
||||
if debug {
|
||||
fmt.Println(instructions)
|
||||
for _, instruction := range instructions.instructions {
|
||||
fmt.Println(instruction.raw())
|
||||
}
|
||||
}
|
||||
|
||||
assert.Equal(t, "Transfer(1)A-B:6(1)", instructions.instructions[0].raw())
|
||||
assert.Equal(t, "Transfer(2)A-B:3(3)", instructions.instructions[1].raw())
|
||||
assert.Equal(t, "Transfer(1)B-D:3(1)", instructions.instructions[2].raw())
|
||||
assert.Equal(t, "Transfer(1)C-D:3(1)", instructions.instructions[3].raw())
|
||||
assert.Equal(t, "Exit(1)A:5", instructions.instructions[4].raw())
|
||||
}
|
||||
|
||||
func TestParseErrors(t *testing.T) {
|
||||
s := `
|
||||
Type: Blockchain
|
||||
Deposit(1) A:: 10
|
||||
`
|
||||
parser := newParser(strings.NewReader(s))
|
||||
_, err := parser.parse()
|
||||
assert.Equal(t, "Line 2: Deposit(1)A:: 10\n, err: strconv.Atoi: parsing \":\": invalid syntax", err.Error())
|
||||
|
||||
s = `
|
||||
Type: Blockchain
|
||||
RegisterToken(1)
|
||||
Deposit(1) A: 10 20
|
||||
`
|
||||
parser = newParser(strings.NewReader(s))
|
||||
_, err = parser.parse()
|
||||
assert.Equal(t, "Line 4: 20, err: Unexpected Blockchain tx type: 20", err.Error())
|
||||
|
||||
s = `
|
||||
Type: Blockchain
|
||||
Transfer(1) A: 10
|
||||
`
|
||||
parser = newParser(strings.NewReader(s))
|
||||
_, err = parser.parse()
|
||||
assert.Equal(t, "Line 2: Transfer(1)A:, err: Expected '-', found ':'", err.Error())
|
||||
|
||||
s = `
|
||||
Type: Blockchain
|
||||
Transfer(1) A B: 10
|
||||
`
|
||||
parser = newParser(strings.NewReader(s))
|
||||
_, err = parser.parse()
|
||||
assert.Equal(t, "Line 2: Transfer(1)AB, err: Expected '-', found 'B'", err.Error())
|
||||
|
||||
s = `
|
||||
Type: Blockchain
|
||||
RegisterToken(1)
|
||||
Transfer(1) A-B: 10 (255)
|
||||
`
|
||||
parser = newParser(strings.NewReader(s))
|
||||
_, err = parser.parse()
|
||||
assert.Nil(t, err)
|
||||
s = `
|
||||
Type: Blockchain
|
||||
Transfer(1) A-B: 10 (256)
|
||||
`
|
||||
parser = newParser(strings.NewReader(s))
|
||||
_, err = parser.parse()
|
||||
assert.Equal(t, "Line 2: Transfer(1)A-B:10(256)\n, err: Fee 256 can not be bigger than 255", err.Error())
|
||||
|
||||
// check that the PoolTransfer & Transfer are only accepted in the
|
||||
// correct case case (PoolTxs/BlockchainTxs)
|
||||
s = `
|
||||
Type: PoolL2
|
||||
Transfer(1) A-B: 10 (1)
|
||||
`
|
||||
parser = newParser(strings.NewReader(s))
|
||||
_, err = parser.parse()
|
||||
assert.Equal(t, "Line 2: Transfer, err: Unexpected PoolL2 tx type: Transfer", err.Error())
|
||||
s = `
|
||||
Type: Blockchain
|
||||
PoolTransfer(1) A-B: 10 (1)
|
||||
`
|
||||
parser = newParser(strings.NewReader(s))
|
||||
_, err = parser.parse()
|
||||
assert.Equal(t, "Line 2: PoolTransfer, err: Unexpected Blockchain tx type: PoolTransfer", err.Error())
|
||||
|
||||
s = `
|
||||
Type: Blockchain
|
||||
> btch
|
||||
`
|
||||
parser = newParser(strings.NewReader(s))
|
||||
_, err = parser.parse()
|
||||
assert.Equal(t, "Line 2: >, err: Unexpected '> btch', expected '> batch' or '> block'", err.Error())
|
||||
|
||||
// check definition of set Type
|
||||
s = `PoolTransfer(1) A-B: 10 (1)`
|
||||
parser = newParser(strings.NewReader(s))
|
||||
_, err = parser.parse()
|
||||
assert.Equal(t, "Line 1: PoolTransfer, err: Set type not defined", err.Error())
|
||||
s = `Type: PoolL1`
|
||||
parser = newParser(strings.NewReader(s))
|
||||
_, err = parser.parse()
|
||||
assert.Equal(t, "Line 1: Type:, err: Invalid set type: 'PoolL1'. Valid set types: 'Blockchain', 'PoolL2'", err.Error())
|
||||
s = `Type: PoolL1
|
||||
Type: Blockchain`
|
||||
parser = newParser(strings.NewReader(s))
|
||||
_, err = parser.parse()
|
||||
assert.Equal(t, "Line 1: Type:, err: Invalid set type: 'PoolL1'. Valid set types: 'Blockchain', 'PoolL2'", err.Error())
|
||||
s = `Type: PoolL2
|
||||
Type: Blockchain`
|
||||
parser = newParser(strings.NewReader(s))
|
||||
_, err = parser.parse()
|
||||
assert.Equal(t, "Line 2: Instruction of 'Type: Blockchain' when there is already a previous instruction 'Type: PoolL2' defined", err.Error())
|
||||
|
||||
s = `Type: Blockchain
|
||||
RegisterToken(1)
|
||||
RegisterToken(0)
|
||||
`
|
||||
parser = newParser(strings.NewReader(s))
|
||||
_, err = parser.parse()
|
||||
assert.Equal(t, "Line 3: RegisterToken can not register TokenID 0", err.Error())
|
||||
}
|
||||
179
test/til/sets.go
Normal file
179
test/til/sets.go
Normal file
@@ -0,0 +1,179 @@
|
||||
package til
|
||||
|
||||
// sets of instructions to be used in tests of other packages
|
||||
|
||||
// SetBlockchain0 contains a set of transactions simulated to be from the smart contract
|
||||
var SetBlockchain0 = `
|
||||
// Set containing Blockchain transactions
|
||||
Type: Blockchain
|
||||
RegisterToken(1)
|
||||
RegisterToken(2)
|
||||
RegisterToken(3)
|
||||
|
||||
// deposits TokenID: 1
|
||||
CreateAccountDeposit(1) A: 50
|
||||
CreateAccountDeposit(1) B: 5
|
||||
CreateAccountDeposit(1) C: 20
|
||||
CreateAccountDeposit(1) D: 25
|
||||
CreateAccountDeposit(1) E: 25
|
||||
CreateAccountDeposit(1) F: 25
|
||||
CreateAccountDeposit(1) G: 25
|
||||
CreateAccountDeposit(1) H: 25
|
||||
CreateAccountDeposit(1) I: 25
|
||||
CreateAccountDeposit(1) J: 25
|
||||
CreateAccountDeposit(1) K: 25
|
||||
CreateAccountDeposit(1) L: 25
|
||||
CreateAccountDeposit(1) M: 25
|
||||
CreateAccountDeposit(1) N: 25
|
||||
CreateAccountDeposit(1) O: 25
|
||||
CreateAccountDeposit(1) P: 25
|
||||
CreateAccountDeposit(1) Q: 25
|
||||
CreateAccountDeposit(1) R: 25
|
||||
CreateAccountDeposit(1) S: 25
|
||||
CreateAccountDeposit(1) T: 25
|
||||
CreateAccountDeposit(1) U: 25
|
||||
CreateAccountDeposit(1) V: 25
|
||||
CreateAccountDeposit(1) W: 25
|
||||
CreateAccountDeposit(1) X: 25
|
||||
CreateAccountDeposit(1) Y: 25
|
||||
CreateAccountDeposit(1) Z: 25
|
||||
// deposits TokenID: 2
|
||||
CreateAccountDeposit(2) B: 5
|
||||
CreateAccountDeposit(2) A: 20
|
||||
// deposits TokenID: 3
|
||||
CreateAccountDeposit(3) B: 100
|
||||
|
||||
> batchL1
|
||||
|
||||
// transactions TokenID: 1
|
||||
Transfer(1) A-B: 5 (1)
|
||||
Transfer(1) A-L: 10 (1)
|
||||
Transfer(1) A-M: 5 (1)
|
||||
Transfer(1) A-N: 5 (1)
|
||||
Transfer(1) A-O: 5 (1)
|
||||
Transfer(1) B-C: 3 (1)
|
||||
Transfer(1) C-A: 3 (255)
|
||||
Transfer(1) D-A: 5 (1)
|
||||
Transfer(1) D-Z: 5 (1)
|
||||
Transfer(1) D-Y: 5 (1)
|
||||
Transfer(1) D-X: 5 (1)
|
||||
Transfer(1) E-Z: 5 (2)
|
||||
Transfer(1) E-Y: 5 (1)
|
||||
Transfer(1) E-X: 5 (1)
|
||||
Transfer(1) F-Z: 5 (1)
|
||||
Transfer(1) G-K: 3 (1)
|
||||
Transfer(1) G-K: 3 (1)
|
||||
Transfer(1) G-K: 3 (1)
|
||||
Transfer(1) H-K: 3 (2)
|
||||
Transfer(1) H-K: 3 (1)
|
||||
Transfer(1) H-K: 3 (1)
|
||||
|
||||
> batchL1
|
||||
> block
|
||||
// A (3) still does not exist, coordinator should create new L1Tx to create the account
|
||||
CreateAccountDepositCoordinator(3) A
|
||||
|
||||
Transfer(3) B-A: 5 (1)
|
||||
Transfer(2) A-B: 5 (1)
|
||||
Transfer(1) I-K: 3 (1)
|
||||
Transfer(1) I-K: 3 (1)
|
||||
Transfer(1) I-K: 3 (1)
|
||||
Transfer(1) J-K: 3 (1)
|
||||
Transfer(1) J-K: 3 (1)
|
||||
Transfer(1) J-K: 3 (1)
|
||||
Transfer(1) K-J: 3 (1)
|
||||
Transfer(1) L-A: 5 (1)
|
||||
Transfer(1) L-Z: 5 (1)
|
||||
Transfer(1) L-Y: 5 (1)
|
||||
Transfer(1) L-X: 5 (1)
|
||||
Transfer(1) M-A: 5 (1)
|
||||
Transfer(1) M-Z: 5 (1)
|
||||
Transfer(1) M-Y: 5 (1)
|
||||
Transfer(1) N-A: 5 (1)
|
||||
Transfer(1) N-Z: 5 (2)
|
||||
Transfer(1) N-Y: 5 (1)
|
||||
Transfer(1) O-T: 3 (1)
|
||||
Transfer(1) O-U: 3 (1)
|
||||
Transfer(1) O-V: 3 (1)
|
||||
Transfer(1) P-T: 3 (1)
|
||||
Transfer(1) P-U: 3 (1)
|
||||
Transfer(1) P-V: 3 (5)
|
||||
Transfer(1) Q-O: 3 (1)
|
||||
Transfer(1) Q-P: 3 (1)
|
||||
Transfer(1) R-O: 3 (1)
|
||||
Transfer(1) R-P: 3 (1)
|
||||
Transfer(1) R-Q: 3 (1)
|
||||
Transfer(1) S-O: 3 (1)
|
||||
Transfer(1) S-P: 3 (1)
|
||||
Transfer(1) S-Q: 3 (1)
|
||||
Transfer(1) T-O: 3 (1)
|
||||
Transfer(1) T-P: 3 (1)
|
||||
Transfer(1) T-Q: 3 (1)
|
||||
Transfer(1) U-Z: 5 (3)
|
||||
Transfer(1) U-Y: 5 (1)
|
||||
Transfer(1) U-T: 3 (1)
|
||||
Transfer(1) V-Z: 5 (0)
|
||||
Transfer(1) V-Y: 6 (1)
|
||||
Transfer(1) V-T: 3 (1)
|
||||
Transfer(1) W-K: 3 (1)
|
||||
Transfer(1) W-J: 3 (1)
|
||||
Transfer(1) W-A: 5 (1)
|
||||
Transfer(1) W-Z: 5 (1)
|
||||
Transfer(1) X-B: 5 (1)
|
||||
Transfer(1) X-C: 5 (50)
|
||||
Transfer(1) X-D: 5 (1)
|
||||
Transfer(1) X-E: 5 (1)
|
||||
Transfer(1) Y-B: 5 (1)
|
||||
Transfer(1) Y-C: 5 (1)
|
||||
Transfer(1) Y-D: 5 (1)
|
||||
Transfer(1) Y-E: 5 (1)
|
||||
Transfer(1) Z-A: 5 (1)
|
||||
// exits
|
||||
ForceExit(1) A: 5
|
||||
Exit(1) K: 5
|
||||
Exit(1) X: 5
|
||||
Exit(1) Y: 5
|
||||
Exit(1) Z: 5
|
||||
|
||||
> batch
|
||||
|
||||
Deposit(1) A: 50
|
||||
Deposit(1) B: 5
|
||||
Deposit(1) C: 20
|
||||
Deposit(1) D: 25
|
||||
Deposit(1) E: 25
|
||||
Deposit(1) F: 25
|
||||
Deposit(1) G: 25
|
||||
Deposit(1) H: 25
|
||||
Deposit(1) I: 25
|
||||
Transfer(1) A-B: 5 (1)
|
||||
Transfer(1) A-L: 10 (1)
|
||||
Transfer(1) A-M: 5 (1)
|
||||
Transfer(1) B-N: 5 (1)
|
||||
Transfer(1) C-O: 5 (1)
|
||||
Transfer(1) H-O: 5 (1)
|
||||
Transfer(1) I-H: 5 (1)
|
||||
Exit(1) A: 5
|
||||
|
||||
// create CoordinatorTx CreateAccount for D, TokenId 2, used at SetPool0 for 'PoolTransfer(2) B-D: 3 (1)'
|
||||
CreateAccountDepositCoordinator(2) D
|
||||
|
||||
> batchL1
|
||||
> batchL1
|
||||
> block
|
||||
`
|
||||
|
||||
// SetPool0 contains a set of transactions from the PoolL2
|
||||
var SetPool0 = `
|
||||
Type: PoolL2
|
||||
PoolTransfer(1) A-B: 6 (1)
|
||||
PoolTransfer(1) B-C: 3 (1)
|
||||
PoolTransfer(1) C-A: 3 (1)
|
||||
PoolTransfer(1) A-B: 1 (1)
|
||||
PoolTransfer(2) A-B: 15 (1)
|
||||
PoolTransfer(2) B-D: 3 (1)
|
||||
PoolExit(1) A: 3
|
||||
PoolTransfer(1) A-B: 6 (1)
|
||||
PoolTransfer(1) B-C: 3 (1)
|
||||
PoolTransfer(1) A-C: 3 (1)
|
||||
`
|
||||
24
test/til/sets_test.go
Normal file
24
test/til/sets_test.go
Normal file
@@ -0,0 +1,24 @@
|
||||
package til
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/hermeznetwork/hermez-node/eth"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestCompileSets(t *testing.T) {
|
||||
parser := newParser(strings.NewReader(SetBlockchain0))
|
||||
_, err := parser.parse()
|
||||
assert.Nil(t, err)
|
||||
parser = newParser(strings.NewReader(SetPool0))
|
||||
_, err = parser.parse()
|
||||
assert.Nil(t, err)
|
||||
|
||||
tc := NewContext(eth.RollupConstMaxL1UserTx)
|
||||
_, err = tc.GenerateBlocks(SetBlockchain0)
|
||||
assert.Nil(t, err)
|
||||
_, err = tc.GenerateBlocks(SetPool0)
|
||||
assert.Nil(t, err)
|
||||
}
|
||||
519
test/til/txs.go
Normal file
519
test/til/txs.go
Normal file
@@ -0,0 +1,519 @@
|
||||
package til
|
||||
|
||||
import (
|
||||
"crypto/ecdsa"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
ethCommon "github.com/ethereum/go-ethereum/common"
|
||||
ethCrypto "github.com/ethereum/go-ethereum/crypto"
|
||||
"github.com/hermeznetwork/hermez-node/common"
|
||||
"github.com/hermeznetwork/hermez-node/log"
|
||||
"github.com/iden3/go-iden3-crypto/babyjub"
|
||||
)
|
||||
|
||||
// Context contains the data of the test
|
||||
type Context struct {
|
||||
Instructions []instruction
|
||||
accountsNames []string
|
||||
Users map[string]*User
|
||||
lastRegisteredTokenID common.TokenID
|
||||
l1CreatedAccounts map[string]*Account
|
||||
|
||||
// rollupConstMaxL1UserTx Maximum L1-user transactions allowed to be queued in a batch
|
||||
rollupConstMaxL1UserTx int
|
||||
|
||||
idx int
|
||||
currBlock BlockData
|
||||
currBatch BatchData
|
||||
currBatchNum int
|
||||
queues [][]L1Tx
|
||||
toForgeNum int
|
||||
openToForge int
|
||||
}
|
||||
|
||||
// NewContext returns a new Context
|
||||
func NewContext(rollupConstMaxL1UserTx int) *Context {
|
||||
return &Context{
|
||||
Users: make(map[string]*User),
|
||||
l1CreatedAccounts: make(map[string]*Account),
|
||||
lastRegisteredTokenID: 0,
|
||||
|
||||
rollupConstMaxL1UserTx: rollupConstMaxL1UserTx,
|
||||
idx: common.UserThreshold,
|
||||
currBatchNum: 0,
|
||||
// start with 2 queues, one for toForge, and the other for openToForge
|
||||
queues: make([][]L1Tx, 2),
|
||||
toForgeNum: 0,
|
||||
openToForge: 1,
|
||||
}
|
||||
}
|
||||
|
||||
// Account contains the data related to the account for a specific TokenID of a User
|
||||
type Account struct {
|
||||
Idx common.Idx
|
||||
Nonce common.Nonce
|
||||
}
|
||||
|
||||
// User contains the data related to a testing user
|
||||
type User struct {
|
||||
BJJ *babyjub.PrivateKey
|
||||
Addr ethCommon.Address
|
||||
Accounts map[common.TokenID]*Account
|
||||
}
|
||||
|
||||
// BlockData contains the information of a Block
|
||||
type BlockData struct {
|
||||
// block *common.Block // ethereum block
|
||||
// L1UserTxs that were accepted in the block
|
||||
L1UserTxs []common.L1Tx
|
||||
Batches []BatchData
|
||||
RegisteredTokens []common.Token
|
||||
}
|
||||
|
||||
// BatchData contains the information of a Batch
|
||||
type BatchData struct {
|
||||
L1Batch bool // TODO: Remove once Batch.ForgeL1TxsNum is a pointer
|
||||
L1CoordinatorTxs []common.L1Tx
|
||||
testL1CoordinatorTxs []L1Tx
|
||||
L2Txs []common.L2Tx
|
||||
// testL2Tx are L2Txs without the Idx&EthAddr&BJJ setted, but with the
|
||||
// string that represents the account
|
||||
testL2Txs []L2Tx
|
||||
}
|
||||
|
||||
// L1Tx is the data structure used internally for transaction test generation,
|
||||
// which contains a common.L1Tx data plus some intermediate data for the
|
||||
// transaction generation.
|
||||
type L1Tx struct {
|
||||
lineNum int
|
||||
fromIdxName string
|
||||
toIdxName string
|
||||
|
||||
L1Tx common.L1Tx
|
||||
}
|
||||
|
||||
// L2Tx is the data structure used internally for transaction test generation,
|
||||
// which contains a common.L2Tx data plus some intermediate data for the
|
||||
// transaction generation.
|
||||
type L2Tx struct {
|
||||
lineNum int
|
||||
fromIdxName string
|
||||
toIdxName string
|
||||
tokenID common.TokenID
|
||||
L2Tx common.L2Tx
|
||||
}
|
||||
|
||||
// GenerateBlocks returns an array of BlockData for a given set. It uses the
|
||||
// accounts (keys & nonces) of the Context.
|
||||
func (tc *Context) GenerateBlocks(set string) ([]BlockData, error) {
|
||||
parser := newParser(strings.NewReader(set))
|
||||
parsedSet, err := parser.parse()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
tc.Instructions = parsedSet.instructions
|
||||
tc.accountsNames = parsedSet.accounts
|
||||
|
||||
tc.generateKeys(tc.accountsNames)
|
||||
|
||||
var blocks []BlockData
|
||||
for _, inst := range parsedSet.instructions {
|
||||
switch inst.typ {
|
||||
case txTypeCreateAccountDepositCoordinator:
|
||||
if err := tc.checkIfTokenIsRegistered(inst); err != nil {
|
||||
log.Error(err)
|
||||
return nil, fmt.Errorf("Line %d: %s", inst.lineNum, err.Error())
|
||||
}
|
||||
tx := common.L1Tx{
|
||||
FromEthAddr: tc.Users[inst.from].Addr,
|
||||
FromBJJ: tc.Users[inst.from].BJJ.Public(),
|
||||
TokenID: inst.tokenID,
|
||||
LoadAmount: big.NewInt(int64(inst.loadAmount)),
|
||||
Type: common.TxTypeCreateAccountDeposit, // as txTypeCreateAccountDepositCoordinator is not valid oustide Til package
|
||||
}
|
||||
testTx := L1Tx{
|
||||
lineNum: inst.lineNum,
|
||||
fromIdxName: inst.from,
|
||||
L1Tx: tx,
|
||||
}
|
||||
tc.currBatch.testL1CoordinatorTxs = append(tc.currBatch.testL1CoordinatorTxs, testTx)
|
||||
case common.TxTypeCreateAccountDeposit, common.TxTypeCreateAccountDepositTransfer:
|
||||
if err := tc.checkIfTokenIsRegistered(inst); err != nil {
|
||||
log.Error(err)
|
||||
return nil, fmt.Errorf("Line %d: %s", inst.lineNum, err.Error())
|
||||
}
|
||||
tx := common.L1Tx{
|
||||
FromEthAddr: tc.Users[inst.from].Addr,
|
||||
FromBJJ: tc.Users[inst.from].BJJ.Public(),
|
||||
TokenID: inst.tokenID,
|
||||
LoadAmount: big.NewInt(int64(inst.loadAmount)),
|
||||
Type: inst.typ,
|
||||
}
|
||||
if inst.typ == common.TxTypeCreateAccountDepositTransfer {
|
||||
tx.Amount = big.NewInt(int64(inst.amount))
|
||||
}
|
||||
testTx := L1Tx{
|
||||
lineNum: inst.lineNum,
|
||||
fromIdxName: inst.from,
|
||||
toIdxName: inst.to,
|
||||
L1Tx: tx,
|
||||
}
|
||||
tc.addToL1Queue(testTx)
|
||||
case common.TxTypeDeposit, common.TxTypeDepositTransfer:
|
||||
if err := tc.checkIfTokenIsRegistered(inst); err != nil {
|
||||
log.Error(err)
|
||||
return nil, fmt.Errorf("Line %d: %s", inst.lineNum, err.Error())
|
||||
}
|
||||
if err := tc.checkIfAccountExists(inst.from, inst); err != nil {
|
||||
log.Error(err)
|
||||
return nil, fmt.Errorf("Line %d: %s", inst.lineNum, err.Error())
|
||||
}
|
||||
tx := common.L1Tx{
|
||||
TokenID: inst.tokenID,
|
||||
LoadAmount: big.NewInt(int64(inst.loadAmount)),
|
||||
Type: inst.typ,
|
||||
}
|
||||
if inst.typ == common.TxTypeDepositTransfer {
|
||||
tx.Amount = big.NewInt(int64(inst.amount))
|
||||
}
|
||||
testTx := L1Tx{
|
||||
lineNum: inst.lineNum,
|
||||
fromIdxName: inst.from,
|
||||
toIdxName: inst.to,
|
||||
L1Tx: tx,
|
||||
}
|
||||
tc.addToL1Queue(testTx)
|
||||
case common.TxTypeTransfer:
|
||||
if err := tc.checkIfTokenIsRegistered(inst); err != nil {
|
||||
log.Error(err)
|
||||
return nil, fmt.Errorf("Line %d: %s", inst.lineNum, err.Error())
|
||||
}
|
||||
tx := common.L2Tx{
|
||||
Amount: big.NewInt(int64(inst.amount)),
|
||||
Fee: common.FeeSelector(inst.fee),
|
||||
Type: common.TxTypeTransfer,
|
||||
}
|
||||
nTx, err := common.NewPoolL2Tx(tx.PoolL2Tx())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Line %d: %s", inst.lineNum, err.Error())
|
||||
}
|
||||
tx = nTx.L2Tx()
|
||||
tx.BatchNum = common.BatchNum(tc.currBatchNum) // when converted to PoolL2Tx BatchNum parameter is lost
|
||||
testTx := L2Tx{
|
||||
lineNum: inst.lineNum,
|
||||
fromIdxName: inst.from,
|
||||
toIdxName: inst.to,
|
||||
tokenID: inst.tokenID,
|
||||
L2Tx: tx,
|
||||
}
|
||||
tc.currBatch.testL2Txs = append(tc.currBatch.testL2Txs, testTx)
|
||||
case common.TxTypeExit:
|
||||
if err := tc.checkIfTokenIsRegistered(inst); err != nil {
|
||||
log.Error(err)
|
||||
return nil, fmt.Errorf("Line %d: %s", inst.lineNum, err.Error())
|
||||
}
|
||||
tx := common.L2Tx{
|
||||
ToIdx: common.Idx(1), // as is an Exit
|
||||
Amount: big.NewInt(int64(inst.amount)),
|
||||
Type: common.TxTypeExit,
|
||||
}
|
||||
tx.BatchNum = common.BatchNum(tc.currBatchNum) // when converted to PoolL2Tx BatchNum parameter is lost
|
||||
testTx := L2Tx{
|
||||
lineNum: inst.lineNum,
|
||||
fromIdxName: inst.from,
|
||||
toIdxName: inst.to,
|
||||
tokenID: inst.tokenID,
|
||||
L2Tx: tx,
|
||||
}
|
||||
tc.currBatch.testL2Txs = append(tc.currBatch.testL2Txs, testTx)
|
||||
case common.TxTypeForceExit:
|
||||
if err := tc.checkIfTokenIsRegistered(inst); err != nil {
|
||||
log.Error(err)
|
||||
return nil, fmt.Errorf("Line %d: %s", inst.lineNum, err.Error())
|
||||
}
|
||||
tx := common.L1Tx{
|
||||
ToIdx: common.Idx(1), // as is an Exit
|
||||
TokenID: inst.tokenID,
|
||||
Amount: big.NewInt(int64(inst.amount)),
|
||||
Type: common.TxTypeExit,
|
||||
}
|
||||
testTx := L1Tx{
|
||||
lineNum: inst.lineNum,
|
||||
fromIdxName: inst.from,
|
||||
toIdxName: inst.to,
|
||||
L1Tx: tx,
|
||||
}
|
||||
tc.addToL1Queue(testTx)
|
||||
case typeNewBatch:
|
||||
if err = tc.calculateIdxForL1Txs(true, tc.currBatch.testL1CoordinatorTxs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = tc.setIdxs(); err != nil {
|
||||
log.Error(err)
|
||||
return nil, err
|
||||
}
|
||||
case typeNewBatchL1:
|
||||
// for each L1UserTx of the queues[ToForgeNum], calculate the Idx
|
||||
if err = tc.calculateIdxForL1Txs(false, tc.queues[tc.toForgeNum]); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = tc.calculateIdxForL1Txs(true, tc.currBatch.testL1CoordinatorTxs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// once Idxs are calculated, update transactions to use the real Idxs
|
||||
for i := 0; i < len(tc.queues[tc.toForgeNum]); i++ {
|
||||
testTx := &tc.queues[tc.toForgeNum][i]
|
||||
if testTx.L1Tx.Type != common.TxTypeCreateAccountDeposit && testTx.L1Tx.Type != common.TxTypeCreateAccountDepositTransfer {
|
||||
testTx.L1Tx.FromIdx = tc.Users[testTx.fromIdxName].Accounts[testTx.L1Tx.TokenID].Idx
|
||||
}
|
||||
testTx.L1Tx.FromEthAddr = tc.Users[testTx.fromIdxName].Addr
|
||||
testTx.L1Tx.FromBJJ = tc.Users[testTx.fromIdxName].BJJ.Public()
|
||||
if testTx.toIdxName == "" {
|
||||
testTx.L1Tx.ToIdx = common.Idx(0)
|
||||
} else {
|
||||
testTx.L1Tx.ToIdx = tc.Users[testTx.toIdxName].Accounts[testTx.L1Tx.TokenID].Idx
|
||||
}
|
||||
if testTx.L1Tx.Type == common.TxTypeExit {
|
||||
testTx.L1Tx.ToIdx = common.Idx(1)
|
||||
}
|
||||
bn := common.BatchNum(tc.currBatchNum)
|
||||
testTx.L1Tx.BatchNum = &bn
|
||||
nTx, err := common.NewL1Tx(&testTx.L1Tx)
|
||||
if err != nil {
|
||||
fmt.Println(testTx)
|
||||
return nil, fmt.Errorf("Line %d: %s", testTx.lineNum, err.Error())
|
||||
}
|
||||
testTx.L1Tx = *nTx
|
||||
|
||||
tc.currBlock.L1UserTxs = append(tc.currBlock.L1UserTxs, testTx.L1Tx)
|
||||
}
|
||||
if err = tc.setIdxs(); err != nil {
|
||||
log.Error(err)
|
||||
return nil, err
|
||||
}
|
||||
// advance batch
|
||||
tc.toForgeNum++
|
||||
if tc.toForgeNum == tc.openToForge {
|
||||
tc.openToForge++
|
||||
newQueue := []L1Tx{}
|
||||
tc.queues = append(tc.queues, newQueue)
|
||||
}
|
||||
case typeNewBlock:
|
||||
blocks = append(blocks, tc.currBlock)
|
||||
tc.currBlock = BlockData{}
|
||||
case typeRegisterToken:
|
||||
newToken := common.Token{
|
||||
TokenID: inst.tokenID,
|
||||
EthBlockNum: int64(len(blocks)),
|
||||
}
|
||||
if inst.tokenID != tc.lastRegisteredTokenID+1 {
|
||||
return nil, fmt.Errorf("Line %d: RegisterToken TokenID should be sequential, expected TokenID: %d, defined TokenID: %d", inst.lineNum, tc.lastRegisteredTokenID+1, inst.tokenID)
|
||||
}
|
||||
tc.lastRegisteredTokenID++
|
||||
tc.currBlock.RegisteredTokens = append(tc.currBlock.RegisteredTokens, newToken)
|
||||
default:
|
||||
return nil, fmt.Errorf("Line %d: Unexpected type: %s", inst.lineNum, inst.typ)
|
||||
}
|
||||
}
|
||||
|
||||
return blocks, nil
|
||||
}
|
||||
|
||||
// calculateIdxsForL1Txs calculates new Idx for new created accounts. If
|
||||
// 'isCoordinatorTxs==true', adds the tx to tc.currBatch.L1CoordinatorTxs.
|
||||
func (tc *Context) calculateIdxForL1Txs(isCoordinatorTxs bool, txs []L1Tx) error {
|
||||
// for each batch.L1CoordinatorTxs of the queues[ToForgeNum], calculate the Idx
|
||||
for i := 0; i < len(txs); i++ {
|
||||
tx := txs[i]
|
||||
if tx.L1Tx.Type == common.TxTypeCreateAccountDeposit || tx.L1Tx.Type == common.TxTypeCreateAccountDepositTransfer {
|
||||
if tc.Users[tx.fromIdxName].Accounts[tx.L1Tx.TokenID] != nil { // if account already exists, return error
|
||||
return fmt.Errorf("Can not create same account twice (same User & same TokenID) (this is a design property of Til)")
|
||||
}
|
||||
tc.Users[tx.fromIdxName].Accounts[tx.L1Tx.TokenID] = &Account{
|
||||
Idx: common.Idx(tc.idx),
|
||||
Nonce: common.Nonce(0),
|
||||
}
|
||||
tc.l1CreatedAccounts[idxTokenIDToString(tx.fromIdxName, tx.L1Tx.TokenID)] = tc.Users[tx.fromIdxName].Accounts[tx.L1Tx.TokenID]
|
||||
tc.idx++
|
||||
}
|
||||
if isCoordinatorTxs {
|
||||
tc.currBatch.L1CoordinatorTxs = append(tc.currBatch.L1CoordinatorTxs, tx.L1Tx)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// setIdxs sets the Idxs to the transactions of the tc.currBatch
|
||||
func (tc *Context) setIdxs() error {
|
||||
// once Idxs are calculated, update transactions to use the new Idxs
|
||||
for i := 0; i < len(tc.currBatch.testL2Txs); i++ {
|
||||
testTx := &tc.currBatch.testL2Txs[i]
|
||||
|
||||
if tc.Users[testTx.fromIdxName].Accounts[testTx.tokenID] == nil {
|
||||
return fmt.Errorf("Line %d: %s from User %s for TokenID %d while account not created yet", testTx.lineNum, testTx.L2Tx.Type, testTx.fromIdxName, testTx.tokenID)
|
||||
}
|
||||
if testTx.L2Tx.Type == common.TxTypeTransfer {
|
||||
if _, ok := tc.l1CreatedAccounts[idxTokenIDToString(testTx.toIdxName, testTx.tokenID)]; !ok {
|
||||
return fmt.Errorf("Line %d: Can not create Transfer for a non existing account. Batch %d, ToIdx name: %s, TokenID: %d", testTx.lineNum, tc.currBatchNum, testTx.toIdxName, testTx.tokenID)
|
||||
}
|
||||
}
|
||||
tc.Users[testTx.fromIdxName].Accounts[testTx.tokenID].Nonce++
|
||||
testTx.L2Tx.Nonce = tc.Users[testTx.fromIdxName].Accounts[testTx.tokenID].Nonce
|
||||
|
||||
// set real Idx
|
||||
testTx.L2Tx.FromIdx = tc.Users[testTx.fromIdxName].Accounts[testTx.tokenID].Idx
|
||||
if testTx.L2Tx.Type == common.TxTypeTransfer {
|
||||
testTx.L2Tx.ToIdx = tc.Users[testTx.toIdxName].Accounts[testTx.tokenID].Idx
|
||||
}
|
||||
nTx, err := common.NewL2Tx(&testTx.L2Tx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Line %d: %s", testTx.lineNum, err.Error())
|
||||
}
|
||||
testTx.L2Tx = *nTx
|
||||
|
||||
tc.currBatch.L2Txs = append(tc.currBatch.L2Txs, testTx.L2Tx)
|
||||
}
|
||||
|
||||
tc.currBlock.Batches = append(tc.currBlock.Batches, tc.currBatch)
|
||||
tc.currBatchNum++
|
||||
tc.currBatch = BatchData{}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// addToL1Queue adds the L1Tx into the queue that is open and has space
|
||||
func (tc *Context) addToL1Queue(tx L1Tx) {
|
||||
if len(tc.queues[tc.openToForge]) >= tc.rollupConstMaxL1UserTx {
|
||||
// if current OpenToForge queue reached its Max, move into a
|
||||
// new queue
|
||||
tc.openToForge++
|
||||
newQueue := []L1Tx{}
|
||||
tc.queues = append(tc.queues, newQueue)
|
||||
}
|
||||
tc.queues[tc.openToForge] = append(tc.queues[tc.openToForge], tx)
|
||||
}
|
||||
|
||||
func (tc *Context) checkIfAccountExists(tf string, inst instruction) error {
|
||||
if tc.Users[tf].Accounts[inst.tokenID] == nil {
|
||||
return fmt.Errorf("%s at User: %s, for TokenID: %d, while account not created yet", inst.typ, tf, inst.tokenID)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (tc *Context) checkIfTokenIsRegistered(inst instruction) error {
|
||||
if inst.tokenID > tc.lastRegisteredTokenID {
|
||||
return fmt.Errorf("Can not process %s: TokenID %d not registered, last registered TokenID: %d", inst.typ, inst.tokenID, tc.lastRegisteredTokenID)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GeneratePoolL2Txs returns an array of common.PoolL2Tx from a given set. It
|
||||
// uses the accounts (keys & nonces) of the Context.
|
||||
func (tc *Context) GeneratePoolL2Txs(set string) ([]common.PoolL2Tx, error) {
|
||||
parser := newParser(strings.NewReader(set))
|
||||
parsedSet, err := parser.parse()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
tc.Instructions = parsedSet.instructions
|
||||
tc.accountsNames = parsedSet.accounts
|
||||
|
||||
tc.generateKeys(tc.accountsNames)
|
||||
|
||||
txs := []common.PoolL2Tx{}
|
||||
for _, inst := range tc.Instructions {
|
||||
switch inst.typ {
|
||||
case common.TxTypeTransfer:
|
||||
if err := tc.checkIfAccountExists(inst.from, inst); err != nil {
|
||||
log.Error(err)
|
||||
return nil, fmt.Errorf("Line %d: %s", inst.lineNum, err.Error())
|
||||
}
|
||||
if err := tc.checkIfAccountExists(inst.to, inst); err != nil {
|
||||
log.Error(err)
|
||||
return nil, fmt.Errorf("Line %d: %s", inst.lineNum, err.Error())
|
||||
}
|
||||
tc.Users[inst.from].Accounts[inst.tokenID].Nonce++
|
||||
// if account of receiver does not exist, don't use
|
||||
// ToIdx, and use only ToEthAddr & ToBJJ
|
||||
tx := common.PoolL2Tx{
|
||||
FromIdx: tc.Users[inst.from].Accounts[inst.tokenID].Idx,
|
||||
ToIdx: tc.Users[inst.to].Accounts[inst.tokenID].Idx,
|
||||
ToEthAddr: tc.Users[inst.to].Addr,
|
||||
ToBJJ: tc.Users[inst.to].BJJ.Public(),
|
||||
TokenID: inst.tokenID,
|
||||
Amount: big.NewInt(int64(inst.amount)),
|
||||
Fee: common.FeeSelector(inst.fee),
|
||||
Nonce: tc.Users[inst.from].Accounts[inst.tokenID].Nonce,
|
||||
State: common.PoolL2TxStatePending,
|
||||
Timestamp: time.Now(),
|
||||
RqToEthAddr: common.EmptyAddr,
|
||||
RqToBJJ: nil,
|
||||
Type: common.TxTypeTransfer,
|
||||
}
|
||||
nTx, err := common.NewPoolL2Tx(&tx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Line %d: %s", inst.lineNum, err.Error())
|
||||
}
|
||||
tx = *nTx
|
||||
// perform signature and set it to tx.Signature
|
||||
toSign, err := tx.HashToSign()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Line %d: %s", inst.lineNum, err.Error())
|
||||
}
|
||||
sig := tc.Users[inst.to].BJJ.SignPoseidon(toSign)
|
||||
tx.Signature = sig
|
||||
|
||||
txs = append(txs, tx)
|
||||
case common.TxTypeExit:
|
||||
tc.Users[inst.from].Accounts[inst.tokenID].Nonce++
|
||||
tx := common.PoolL2Tx{
|
||||
FromIdx: tc.Users[inst.from].Accounts[inst.tokenID].Idx,
|
||||
ToIdx: common.Idx(1), // as is an Exit
|
||||
TokenID: inst.tokenID,
|
||||
Amount: big.NewInt(int64(inst.amount)),
|
||||
Nonce: tc.Users[inst.from].Accounts[inst.tokenID].Nonce,
|
||||
Type: common.TxTypeExit,
|
||||
}
|
||||
txs = append(txs, tx)
|
||||
default:
|
||||
return nil, fmt.Errorf("Line %d: instruction type unrecognized: %s", inst.lineNum, inst.typ)
|
||||
}
|
||||
}
|
||||
|
||||
return txs, nil
|
||||
}
|
||||
|
||||
// generateKeys generates BabyJubJub & Address keys for the given list of
|
||||
// account names in a deterministic way. This means, that for the same given
|
||||
// 'accNames' in a certain order, the keys will be always the same.
|
||||
func (tc *Context) generateKeys(accNames []string) {
|
||||
for i := 1; i < len(accNames)+1; i++ {
|
||||
if _, ok := tc.Users[accNames[i-1]]; ok {
|
||||
// account already created
|
||||
continue
|
||||
}
|
||||
// babyjubjub key
|
||||
var sk babyjub.PrivateKey
|
||||
copy(sk[:], []byte(strconv.Itoa(i))) // only for testing
|
||||
|
||||
// eth address
|
||||
var key ecdsa.PrivateKey
|
||||
key.D = big.NewInt(int64(i)) // only for testing
|
||||
key.PublicKey.X, key.PublicKey.Y = ethCrypto.S256().ScalarBaseMult(key.D.Bytes())
|
||||
key.Curve = ethCrypto.S256()
|
||||
addr := ethCrypto.PubkeyToAddress(key.PublicKey)
|
||||
|
||||
u := User{
|
||||
BJJ: &sk,
|
||||
Addr: addr,
|
||||
Accounts: make(map[common.TokenID]*Account),
|
||||
}
|
||||
tc.Users[accNames[i-1]] = &u
|
||||
}
|
||||
}
|
||||
301
test/til/txs_test.go
Normal file
301
test/til/txs_test.go
Normal file
@@ -0,0 +1,301 @@
|
||||
package til
|
||||
|
||||
import (
|
||||
"math/big"
|
||||
"testing"
|
||||
|
||||
"github.com/hermeznetwork/hermez-node/common"
|
||||
"github.com/hermeznetwork/hermez-node/eth"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestGenerateBlocks(t *testing.T) {
|
||||
set := `
|
||||
Type: Blockchain
|
||||
RegisterToken(1)
|
||||
RegisterToken(2)
|
||||
RegisterToken(3)
|
||||
|
||||
CreateAccountDeposit(1) A: 10
|
||||
CreateAccountDeposit(2) A: 20
|
||||
CreateAccountDeposit(1) B: 5
|
||||
CreateAccountDeposit(1) C: 5
|
||||
CreateAccountDepositTransfer(1) D-A: 15, 10 (3)
|
||||
|
||||
> batchL1
|
||||
> batchL1
|
||||
|
||||
Transfer(1) A-B: 6 (1)
|
||||
Transfer(1) B-D: 3 (1)
|
||||
Transfer(1) A-D: 1 (1)
|
||||
|
||||
// set new batch
|
||||
> batch
|
||||
CreateAccountDepositCoordinator(1) E
|
||||
CreateAccountDepositCoordinator(2) B
|
||||
|
||||
DepositTransfer(1) A-B: 15, 10 (1)
|
||||
Transfer(1) C-A : 3 (1)
|
||||
Transfer(2) A-B: 15 (1)
|
||||
Transfer(1) A-E: 1 (1)
|
||||
|
||||
CreateAccountDeposit(1) User0: 20
|
||||
CreateAccountDeposit(3) User1: 20
|
||||
CreateAccountDepositCoordinator(1) User1
|
||||
CreateAccountDepositCoordinator(3) User0
|
||||
> batchL1
|
||||
Transfer(1) User0-User1: 15 (1)
|
||||
Transfer(3) User1-User0: 15 (1)
|
||||
Transfer(1) A-C: 1 (1)
|
||||
|
||||
> batchL1
|
||||
|
||||
Transfer(1) User1-User0: 1 (1)
|
||||
|
||||
> block
|
||||
|
||||
// Exits
|
||||
Transfer(1) A-B: 1 (1)
|
||||
Exit(1) A: 5
|
||||
|
||||
> batch
|
||||
> block
|
||||
|
||||
// this transaction should not be generated, as it's after last
|
||||
// batch and last block
|
||||
Transfer(1) User1-User0: 1 (1)
|
||||
`
|
||||
tc := NewContext(eth.RollupConstMaxL1UserTx)
|
||||
blocks, err := tc.GenerateBlocks(set)
|
||||
require.Nil(t, err)
|
||||
assert.Equal(t, 2, len(blocks))
|
||||
assert.Equal(t, 5, len(blocks[0].Batches))
|
||||
assert.Equal(t, 1, len(blocks[1].Batches))
|
||||
assert.Equal(t, 8, len(blocks[0].L1UserTxs))
|
||||
assert.Equal(t, 4, len(blocks[0].Batches[3].L1CoordinatorTxs))
|
||||
assert.Equal(t, 0, len(blocks[1].L1UserTxs))
|
||||
|
||||
// Check expected values generated by each line
|
||||
// #0: Deposit(1) A: 10
|
||||
tc.checkL1TxParams(t, blocks[0].L1UserTxs[0], common.TxTypeCreateAccountDeposit, 1, "A", "", big.NewInt(10), nil)
|
||||
// #1: Deposit(2) A: 20
|
||||
tc.checkL1TxParams(t, blocks[0].L1UserTxs[1], common.TxTypeCreateAccountDeposit, 2, "A", "", big.NewInt(20), nil)
|
||||
// // #2: Deposit(1) A: 20
|
||||
tc.checkL1TxParams(t, blocks[0].L1UserTxs[2], common.TxTypeCreateAccountDeposit, 1, "B", "", big.NewInt(5), nil)
|
||||
// // #3: CreateAccountDeposit(1) C: 5
|
||||
tc.checkL1TxParams(t, blocks[0].L1UserTxs[3], common.TxTypeCreateAccountDeposit, 1, "C", "", big.NewInt(5), nil)
|
||||
// // #4: CreateAccountDepositTransfer(1) D-A: 15, 10 (3)
|
||||
tc.checkL1TxParams(t, blocks[0].L1UserTxs[4], common.TxTypeCreateAccountDepositTransfer, 1, "D", "A", big.NewInt(15), big.NewInt(10))
|
||||
// #5: Transfer(1) A-B: 6 (1)
|
||||
tc.checkL2TxParams(t, blocks[0].Batches[2].L2Txs[0], common.TxTypeTransfer, 1, "A", "B", big.NewInt(6), common.BatchNum(2), common.Nonce(1))
|
||||
// #6: Transfer(1) B-D: 3 (1)
|
||||
tc.checkL2TxParams(t, blocks[0].Batches[2].L2Txs[1], common.TxTypeTransfer, 1, "B", "D", big.NewInt(3), common.BatchNum(2), common.Nonce(1))
|
||||
// #7: Transfer(1) A-D: 1 (1)
|
||||
tc.checkL2TxParams(t, blocks[0].Batches[2].L2Txs[2], common.TxTypeTransfer, 1, "A", "D", big.NewInt(1), common.BatchNum(2), common.Nonce(2))
|
||||
// change of Batch
|
||||
// #8: DepositTransfer(1) A-B: 15, 10 (1)
|
||||
tc.checkL1TxParams(t, blocks[0].L1UserTxs[5], common.TxTypeDepositTransfer, 1, "A", "B", big.NewInt(15), big.NewInt(10))
|
||||
// #10: Transfer(1) C-A : 3 (1)
|
||||
tc.checkL2TxParams(t, blocks[0].Batches[3].L2Txs[0], common.TxTypeTransfer, 1, "C", "A", big.NewInt(3), common.BatchNum(3), common.Nonce(1))
|
||||
// #11: Transfer(2) A-B: 15 (1)
|
||||
tc.checkL2TxParams(t, blocks[0].Batches[3].L2Txs[1], common.TxTypeTransfer, 2, "A", "B", big.NewInt(15), common.BatchNum(3), common.Nonce(1))
|
||||
// #12: Deposit(1) User0: 20
|
||||
tc.checkL1TxParams(t, blocks[0].L1UserTxs[6], common.TxTypeCreateAccountDeposit, 1, "User0", "", big.NewInt(20), nil)
|
||||
// // #13: Deposit(3) User1: 20
|
||||
tc.checkL1TxParams(t, blocks[0].L1UserTxs[7], common.TxTypeCreateAccountDeposit, 3, "User1", "", big.NewInt(20), nil)
|
||||
// #14: Transfer(1) User0-User1: 15 (1)
|
||||
tc.checkL2TxParams(t, blocks[0].Batches[4].L2Txs[0], common.TxTypeTransfer, 1, "User0", "User1", big.NewInt(15), common.BatchNum(4), common.Nonce(1))
|
||||
// #15: Transfer(3) User1-User0: 15 (1)
|
||||
tc.checkL2TxParams(t, blocks[0].Batches[4].L2Txs[1], common.TxTypeTransfer, 3, "User1", "User0", big.NewInt(15), common.BatchNum(4), common.Nonce(1))
|
||||
// #16: Transfer(1) A-C: 1 (1)
|
||||
tc.checkL2TxParams(t, blocks[0].Batches[4].L2Txs[2], common.TxTypeTransfer, 1, "A", "C", big.NewInt(1), common.BatchNum(4), common.Nonce(4))
|
||||
// change of Batch
|
||||
// #17: Transfer(1) User1-User0: 1 (1)
|
||||
tc.checkL2TxParams(t, blocks[1].Batches[0].L2Txs[0], common.TxTypeTransfer, 1, "User1", "User0", big.NewInt(1), common.BatchNum(5), common.Nonce(1))
|
||||
// change of Block (implies also a change of batch)
|
||||
// #18: Transfer(1) A-B: 1 (1)
|
||||
tc.checkL2TxParams(t, blocks[1].Batches[0].L2Txs[1], common.TxTypeTransfer, 1, "A", "B", big.NewInt(1), common.BatchNum(5), common.Nonce(5))
|
||||
}
|
||||
|
||||
func (tc *Context) checkL1TxParams(t *testing.T, tx common.L1Tx, typ common.TxType, tokenID common.TokenID, from, to string, loadAmount, amount *big.Int) {
|
||||
assert.Equal(t, typ, tx.Type)
|
||||
if tx.FromIdx != common.Idx(0) {
|
||||
assert.Equal(t, tc.Users[from].Accounts[tokenID].Idx, tx.FromIdx)
|
||||
}
|
||||
assert.Equal(t, tc.Users[from].Addr.Hex(), tx.FromEthAddr.Hex())
|
||||
assert.Equal(t, tc.Users[from].BJJ.Public(), tx.FromBJJ)
|
||||
if tx.ToIdx != common.Idx(0) {
|
||||
assert.Equal(t, tc.Users[to].Accounts[tokenID].Idx, tx.ToIdx)
|
||||
}
|
||||
if loadAmount != nil {
|
||||
assert.Equal(t, loadAmount, tx.LoadAmount)
|
||||
}
|
||||
if amount != nil {
|
||||
assert.Equal(t, amount, tx.Amount)
|
||||
}
|
||||
}
|
||||
func (tc *Context) checkL2TxParams(t *testing.T, tx common.L2Tx, typ common.TxType, tokenID common.TokenID, from, to string, amount *big.Int, batchNum common.BatchNum, nonce common.Nonce) {
|
||||
assert.Equal(t, typ, tx.Type)
|
||||
assert.Equal(t, tc.Users[from].Accounts[tokenID].Idx, tx.FromIdx)
|
||||
if tx.Type != common.TxTypeExit {
|
||||
assert.Equal(t, tc.Users[to].Accounts[tokenID].Idx, tx.ToIdx)
|
||||
}
|
||||
if amount != nil {
|
||||
assert.Equal(t, amount, tx.Amount)
|
||||
}
|
||||
assert.Equal(t, batchNum, tx.BatchNum)
|
||||
assert.Equal(t, nonce, tx.Nonce)
|
||||
}
|
||||
|
||||
func TestGeneratePoolL2Txs(t *testing.T) {
|
||||
set := `
|
||||
Type: Blockchain
|
||||
RegisterToken(1)
|
||||
RegisterToken(2)
|
||||
RegisterToken(3)
|
||||
|
||||
CreateAccountDeposit(1) A: 10
|
||||
CreateAccountDeposit(2) A: 20
|
||||
CreateAccountDeposit(1) B: 5
|
||||
CreateAccountDeposit(1) C: 5
|
||||
CreateAccountDeposit(1) User0: 5
|
||||
CreateAccountDeposit(1) User1: 0
|
||||
CreateAccountDeposit(3) User0: 0
|
||||
CreateAccountDeposit(3) User1: 5
|
||||
CreateAccountDeposit(2) B: 5
|
||||
CreateAccountDeposit(2) D: 0
|
||||
> batchL1
|
||||
> batchL1
|
||||
`
|
||||
tc := NewContext(eth.RollupConstMaxL1UserTx)
|
||||
_, err := tc.GenerateBlocks(set)
|
||||
require.Nil(t, err)
|
||||
set = `
|
||||
Type: PoolL2
|
||||
PoolTransfer(1) A-B: 6 (1)
|
||||
PoolTransfer(1) B-C: 3 (1)
|
||||
PoolTransfer(1) C-A: 3 (1)
|
||||
PoolTransfer(1) A-B: 1 (1)
|
||||
PoolTransfer(2) A-B: 15 (1)
|
||||
PoolTransfer(1) User0-User1: 15 (1)
|
||||
PoolTransfer(3) User1-User0: 15 (1)
|
||||
PoolTransfer(2) B-D: 3 (1)
|
||||
PoolExit(1) A: 3
|
||||
`
|
||||
poolL2Txs, err := tc.GeneratePoolL2Txs(set)
|
||||
require.Nil(t, err)
|
||||
assert.Equal(t, 9, len(poolL2Txs))
|
||||
assert.Equal(t, common.TxTypeTransfer, poolL2Txs[0].Type)
|
||||
assert.Equal(t, common.TxTypeExit, poolL2Txs[8].Type)
|
||||
assert.Equal(t, tc.Users["B"].Addr.Hex(), poolL2Txs[0].ToEthAddr.Hex())
|
||||
assert.Equal(t, tc.Users["B"].BJJ.Public().String(), poolL2Txs[0].ToBJJ.String())
|
||||
assert.Equal(t, tc.Users["User1"].Addr.Hex(), poolL2Txs[5].ToEthAddr.Hex())
|
||||
assert.Equal(t, tc.Users["User1"].BJJ.Public().String(), poolL2Txs[5].ToBJJ.String())
|
||||
|
||||
assert.Equal(t, common.Nonce(1), poolL2Txs[0].Nonce)
|
||||
assert.Equal(t, common.Nonce(2), poolL2Txs[3].Nonce)
|
||||
assert.Equal(t, common.Nonce(3), poolL2Txs[8].Nonce)
|
||||
|
||||
// load another set in the same Context
|
||||
set = `
|
||||
Type: PoolL2
|
||||
PoolTransfer(1) A-B: 6 (1)
|
||||
PoolTransfer(1) B-C: 3 (1)
|
||||
PoolTransfer(1) A-C: 3 (1)
|
||||
`
|
||||
poolL2Txs, err = tc.GeneratePoolL2Txs(set)
|
||||
require.Nil(t, err)
|
||||
assert.Equal(t, common.Nonce(4), poolL2Txs[0].Nonce)
|
||||
assert.Equal(t, common.Nonce(2), poolL2Txs[1].Nonce)
|
||||
assert.Equal(t, common.Nonce(5), poolL2Txs[2].Nonce)
|
||||
}
|
||||
|
||||
func TestGenerateErrors(t *testing.T) {
|
||||
// unregistered token
|
||||
set := `Type: Blockchain
|
||||
CreateAccountDeposit(1) A: 5
|
||||
> batchL1
|
||||
`
|
||||
tc := NewContext(eth.RollupConstMaxL1UserTx)
|
||||
_, err := tc.GenerateBlocks(set)
|
||||
assert.Equal(t, "Line 2: Can not process CreateAccountDeposit: TokenID 1 not registered, last registered TokenID: 0", err.Error())
|
||||
|
||||
// ensure RegisterToken sequentiality and not using 0
|
||||
set = `
|
||||
Type: Blockchain
|
||||
RegisterToken(0)
|
||||
`
|
||||
tc = NewContext(eth.RollupConstMaxL1UserTx)
|
||||
_, err = tc.GenerateBlocks(set)
|
||||
require.Equal(t, "Line 2: RegisterToken can not register TokenID 0", err.Error())
|
||||
|
||||
set = `
|
||||
Type: Blockchain
|
||||
RegisterToken(2)
|
||||
`
|
||||
tc = NewContext(eth.RollupConstMaxL1UserTx)
|
||||
_, err = tc.GenerateBlocks(set)
|
||||
require.Equal(t, "Line 2: RegisterToken TokenID should be sequential, expected TokenID: 1, defined TokenID: 2", err.Error())
|
||||
|
||||
set = `
|
||||
Type: Blockchain
|
||||
RegisterToken(1)
|
||||
RegisterToken(2)
|
||||
RegisterToken(3)
|
||||
RegisterToken(5)
|
||||
`
|
||||
tc = NewContext(eth.RollupConstMaxL1UserTx)
|
||||
_, err = tc.GenerateBlocks(set)
|
||||
require.Equal(t, "Line 5: RegisterToken TokenID should be sequential, expected TokenID: 4, defined TokenID: 5", err.Error())
|
||||
|
||||
// check transactions when account is not created yet
|
||||
set = `
|
||||
Type: Blockchain
|
||||
RegisterToken(1)
|
||||
CreateAccountDeposit(1) A: 10
|
||||
> batchL1
|
||||
CreateAccountDeposit(1) B
|
||||
Transfer(1) A-B: 6 (1)
|
||||
> batch
|
||||
`
|
||||
tc = NewContext(eth.RollupConstMaxL1UserTx)
|
||||
_, err = tc.GenerateBlocks(set)
|
||||
require.Equal(t, "Line 5: CreateAccountDeposit(1)BTransfer(1) A-B: 6 (1)\n, err: Expected ':', found 'Transfer'", err.Error())
|
||||
set = `
|
||||
Type: Blockchain
|
||||
RegisterToken(1)
|
||||
CreateAccountDeposit(1) A: 10
|
||||
> batchL1
|
||||
CreateAccountDepositCoordinator(1) B
|
||||
> batchL1
|
||||
> batch
|
||||
Transfer(1) A-B: 6 (1)
|
||||
> batch
|
||||
`
|
||||
tc = NewContext(eth.RollupConstMaxL1UserTx)
|
||||
_, err = tc.GenerateBlocks(set)
|
||||
require.Nil(t, err)
|
||||
|
||||
// check nonces
|
||||
set = `
|
||||
Type: Blockchain
|
||||
RegisterToken(1)
|
||||
CreateAccountDeposit(1) A: 10
|
||||
> batchL1
|
||||
CreateAccountDepositCoordinator(1) B
|
||||
> batchL1
|
||||
Transfer(1) A-B: 6 (1)
|
||||
Transfer(1) A-B: 6 (1) // on purpose this is moving more money that what it has in the account, Til should not fail
|
||||
Transfer(1) B-A: 6 (1)
|
||||
Exit(1) A: 3
|
||||
> batch
|
||||
`
|
||||
tc = NewContext(eth.RollupConstMaxL1UserTx)
|
||||
_, err = tc.GenerateBlocks(set)
|
||||
require.Nil(t, err)
|
||||
assert.Equal(t, common.Nonce(3), tc.Users["A"].Accounts[common.TokenID(1)].Nonce)
|
||||
assert.Equal(t, common.Idx(256), tc.Users["A"].Accounts[common.TokenID(1)].Idx)
|
||||
assert.Equal(t, common.Nonce(1), tc.Users["B"].Accounts[common.TokenID(1)].Nonce)
|
||||
assert.Equal(t, common.Idx(257), tc.Users["B"].Accounts[common.TokenID(1)].Idx)
|
||||
}
|
||||
Reference in New Issue
Block a user