hermez-node/db/statedb/txprocessors.go
db/statedb/txprocessors.goRaw
1package statedb
2
3import (
4 "errors"
5 "io/ioutil"
6 "math/big"
7 "os"
8
9 "github.com/hermeznetwork/hermez-node/common"
10 "github.com/hermeznetwork/hermez-node/log"
11 "github.com/iden3/go-iden3-crypto/babyjub"
12 "github.com/iden3/go-merkletree"
13 "github.com/iden3/go-merkletree/db"
14 "github.com/iden3/go-merkletree/db/pebble"
15)
16
17var (
18 // keyidx is used as key in the db to store the current Idx
19 keyidx = []byte("k:idx")
20)
21
22func (s *StateDB) resetZKInputs() {
23 s.zki = nil
24 s.i = 0
25}
26
27type processedExit struct {
28 exit bool
29 newExit bool
30 idx common.Idx
31 acc common.Account
32}
33
34// ProcessTxs process the given L1Txs & L2Txs applying the needed updates to
35// the StateDB depending on the transaction Type. If StateDB
36// type==TypeBatchBuilder, returns the common.ZKInputs to generate the
37// SnarkProof later used by the BatchBuilder. If StateDB
38// type==TypeSynchronizer, assumes that the call is done from the Synchronizer,
39// returns common.ExitTreeLeaf that is later used by the Synchronizer to update
40// the HistoryDB, and adds Nonce & TokenID to the L2Txs.
41func (s *StateDB) ProcessTxs(l1usertxs, l1coordinatortxs []common.L1Tx, l2txs []common.PoolL2Tx) (*common.ZKInputs, []common.ExitInfo, error) {
42 var err error
43 var exitTree *merkletree.MerkleTree
44
45 if s.zki != nil {
46 return nil, nil, errors.New("Expected StateDB.zki==nil, something went wrong and it's not empty")
47 }
48 defer s.resetZKInputs()
49
50 nTx := len(l1usertxs) + len(l1coordinatortxs) + len(l2txs)
51 if nTx == 0 {
52 // TODO return ZKInputs of batch without txs
53 return nil, nil, nil
54 }
55 exits := make([]processedExit, nTx)
56
57 if s.typ == TypeBatchBuilder {
58 s.zki = common.NewZKInputs(nTx, 24, 32) // TODO this values will be parameters of the function, taken from config file/coordinator call
59 s.zki.OldLastIdx = (s.idx - 1).BigInt()
60 s.zki.OldStateRoot = s.mt.Root().BigInt()
61 }
62
63 // TBD if ExitTree is only in memory or stored in disk, for the moment
64 // only needed in memory
65 if s.typ == TypeSynchronizer || s.typ == TypeBatchBuilder {
66 tmpDir, err := ioutil.TempDir("", "hermez-statedb-exittree")
67 if err != nil {
68 return nil, nil, err
69 }
70 defer func() {
71 if err := os.RemoveAll(tmpDir); err != nil {
72 log.Errorw("Deleting statedb temp exit tree", "err", err)
73 }
74 }()
75 sto, err := pebble.NewPebbleStorage(tmpDir, false)
76 if err != nil {
77 return nil, nil, err
78 }
79 exitTree, err = merkletree.NewMerkleTree(sto, s.mt.MaxLevels())
80 if err != nil {
81 return nil, nil, err
82 }
83 }
84
85 // assumption: l1usertx are sorted by L1Tx.Position
86 for i := 0; i < len(l1usertxs); i++ {
87 exitIdx, exitAccount, newExit, err := s.processL1Tx(exitTree, &l1usertxs[i])
88 if err != nil {
89 return nil, nil, err
90 }
91 if s.typ == TypeSynchronizer || s.typ == TypeBatchBuilder {
92 if exitIdx != nil && exitTree != nil {
93 exits[s.i] = processedExit{
94 exit: true,
95 newExit: newExit,
96 idx: *exitIdx,
97 acc: *exitAccount,
98 }
99 }
100 s.i++
101 }
102 }
103 for i := 0; i < len(l1coordinatortxs); i++ {
104 exitIdx, exitAccount, newExit, err := s.processL1Tx(exitTree, &l1coordinatortxs[i])
105 if err != nil {
106 return nil, nil, err
107 }
108 if exitIdx != nil {
109 log.Error("Unexpected Exit in L1CoordinatorTx")
110 }
111 if s.typ == TypeSynchronizer || s.typ == TypeBatchBuilder {
112 if exitIdx != nil && exitTree != nil {
113 exits[s.i] = processedExit{
114 exit: true,
115 newExit: newExit,
116 idx: *exitIdx,
117 acc: *exitAccount,
118 }
119 }
120 s.i++
121 }
122 }
123 for i := 0; i < len(l2txs); i++ {
124 exitIdx, exitAccount, newExit, err := s.processL2Tx(exitTree, &l2txs[i])
125 if err != nil {
126 return nil, nil, err
127 }
128 if s.typ == TypeSynchronizer || s.typ == TypeBatchBuilder {
129 if exitIdx != nil && exitTree != nil {
130 exits[s.i] = processedExit{
131 exit: true,
132 newExit: newExit,
133 idx: *exitIdx,
134 acc: *exitAccount,
135 }
136 }
137 s.i++
138 }
139 }
140
141 if s.typ == TypeTxSelector {
142 return nil, nil, nil
143 }
144
145 // once all txs processed (exitTree root frozen), for each Exit,
146 // generate common.ExitInfo data
147 var exitInfos []common.ExitInfo
148 for i := 0; i < nTx; i++ {
149 if !exits[i].exit {
150 continue
151 }
152 exitIdx := exits[i].idx
153 exitAccount := exits[i].acc
154
155 // 0. generate MerkleProof
156 p, err := exitTree.GenerateCircomVerifierProof(exitIdx.BigInt(), nil)
157 if err != nil {
158 return nil, nil, err
159 }
160 // 1. generate common.ExitInfo
161 ei := common.ExitInfo{
162 AccountIdx: exitIdx,
163 MerkleProof: p,
164 Balance: exitAccount.Balance,
165 }
166 exitInfos = append(exitInfos, ei)
167
168 if s.zki != nil {
169 s.zki.TokenID2[i] = exitAccount.TokenID.BigInt()
170 s.zki.Nonce2[i] = exitAccount.Nonce.BigInt()
171 if babyjub.PointCoordSign(exitAccount.PublicKey.X) {
172 s.zki.Sign2[i] = big.NewInt(1)
173 }
174 s.zki.Ay2[i] = exitAccount.PublicKey.Y
175 s.zki.Balance2[i] = exitAccount.Balance
176 s.zki.EthAddr2[i] = common.EthAddrToBigInt(exitAccount.EthAddr)
177 s.zki.Siblings2[i] = p.Siblings
178 if exits[i].newExit {
179 s.zki.NewExit[i] = big.NewInt(1)
180 }
181 if p.IsOld0 {
182 s.zki.IsOld0_2[i] = big.NewInt(1)
183 }
184 s.zki.OldKey2[i] = p.OldKey.BigInt()
185 s.zki.OldValue2[i] = p.OldValue.BigInt()
186 }
187 }
188 if s.typ == TypeSynchronizer {
189 return nil, exitInfos, nil
190 }
191
192 // compute last ZKInputs parameters
193 s.zki.GlobalChainID = big.NewInt(0) // TODO, 0: ethereum, this will be get from config file
194 // zki.FeeIdxs = ? // TODO, this will be get from the config file
195 tokenIDs, err := s.getTokenIDsBigInt(l1usertxs, l1coordinatortxs, l2txs)
196 if err != nil {
197 return nil, nil, err
198 }
199 s.zki.FeePlanTokens = tokenIDs
200
201 // s.zki.ISInitStateRootFee = s.mt.Root().BigInt()
202
203 // TODO once the Node Config sets the Accounts where to send the Fees
204 // compute fees & update ZKInputs
205
206 // return exitInfos, so Synchronizer will be able to store it into
207 // HistoryDB for the concrete BatchNum
208 return s.zki, exitInfos, nil
209}
210
211// getTokenIDsBigInt returns the list of TokenIDs in *big.Int format
212func (s *StateDB) getTokenIDsBigInt(l1usertxs, l1coordinatortxs []common.L1Tx, l2txs []common.PoolL2Tx) ([]*big.Int, error) {
213 tokenIDs := make(map[common.TokenID]bool)
214 for i := 0; i < len(l1usertxs); i++ {
215 tokenIDs[l1usertxs[i].TokenID] = true
216 }
217 for i := 0; i < len(l1coordinatortxs); i++ {
218 tokenIDs[l1coordinatortxs[i].TokenID] = true
219 }
220 for i := 0; i < len(l2txs); i++ {
221 // as L2Tx does not have parameter TokenID, get it from the
222 // AccountsDB (in the StateDB)
223 acc, err := s.GetAccount(l2txs[i].ToIdx)
224 if err != nil {
225 return nil, err
226 }
227 tokenIDs[acc.TokenID] = true
228 }
229 var tBI []*big.Int
230 for t := range tokenIDs {
231 tBI = append(tBI, t.BigInt())
232 }
233 return tBI, nil
234}
235
236// processL1Tx process the given L1Tx applying the needed updates to the
237// StateDB depending on the transaction Type. It returns the 3 parameters
238// related to the Exit (in case of): Idx, ExitAccount, boolean determining if
239// the Exit created a new Leaf in the ExitTree.
240func (s *StateDB) processL1Tx(exitTree *merkletree.MerkleTree, tx *common.L1Tx) (*common.Idx, *common.Account, bool, error) {
241 // ZKInputs
242 if s.zki != nil {
243 // Txs
244 // s.zki.TxCompressedData[s.i] = tx.TxCompressedData() // uncomment once L1Tx.TxCompressedData is ready
245 s.zki.FromIdx[s.i] = tx.FromIdx.BigInt()
246 s.zki.ToIdx[s.i] = tx.ToIdx.BigInt()
247 s.zki.OnChain[s.i] = big.NewInt(1)
248
249 // L1Txs
250 s.zki.LoadAmountF[s.i] = tx.LoadAmount
251 s.zki.FromEthAddr[s.i] = common.EthAddrToBigInt(tx.FromEthAddr)
252 if tx.FromBJJ != nil {
253 s.zki.FromBJJCompressed[s.i] = BJJCompressedTo256BigInts(tx.FromBJJ.Compress())
254 }
255
256 // Intermediate States
257 s.zki.ISOnChain[s.i] = big.NewInt(1)
258 }
259
260 switch tx.Type {
261 case common.TxTypeForceTransfer, common.TxTypeTransfer:
262 // go to the MT account of sender and receiver, and update balance
263 // & nonce
264 err := s.applyTransfer(tx.Tx(), 0) // 0 for the parameter toIdx, as at L1Tx ToIdx can only be 0 in the Deposit type case.
265 if err != nil {
266 log.Error(err)
267 return nil, nil, false, err
268 }
269 case common.TxTypeCreateAccountDeposit:
270 // add new account to the MT, update balance of the MT account
271 err := s.applyCreateAccount(tx)
272 if err != nil {
273 log.Error(err)
274 return nil, nil, false, err
275 }
276 // TODO applyCreateAccount will return the created account,
277 // which in the case type==TypeSynchronizer will be added to an
278 // array of created accounts that will be returned
279
280 if s.zki != nil {
281 s.zki.AuxFromIdx[s.i] = s.idx.BigInt() // last s.idx is the one used for creating the new account
282 s.zki.NewAccount[s.i] = big.NewInt(1)
283 }
284 case common.TxTypeDeposit:
285 // update balance of the MT account
286 err := s.applyDeposit(tx, false)
287 if err != nil {
288 log.Error(err)
289 return nil, nil, false, err
290 }
291 case common.TxTypeDepositTransfer:
292 // update balance in MT account, update balance & nonce of sender
293 // & receiver
294 err := s.applyDeposit(tx, true)
295 if err != nil {
296 log.Error(err)
297 return nil, nil, false, err
298 }
299 case common.TxTypeCreateAccountDepositTransfer:
300 // add new account to the merkletree, update balance in MT account,
301 // update balance & nonce of sender & receiver
302 err := s.applyCreateAccountDepositTransfer(tx)
303 if err != nil {
304 log.Error(err)
305 return nil, nil, false, err
306 }
307
308 if s.zki != nil {
309 s.zki.AuxFromIdx[s.i] = s.idx.BigInt() // last s.idx is the one used for creating the new account
310 s.zki.NewAccount[s.i] = big.NewInt(1)
311 }
312 case common.TxTypeExit:
313 // execute exit flow
314 exitAccount, newExit, err := s.applyExit(exitTree, tx.Tx())
315 if err != nil {
316 log.Error(err)
317 return nil, nil, false, err
318 }
319 return &tx.FromIdx, exitAccount, newExit, nil
320 default:
321 }
322
323 return nil, nil, false, nil
324}
325
326// processL2Tx process the given L2Tx applying the needed updates to the
327// StateDB depending on the transaction Type. It returns the 3 parameters
328// related to the Exit (in case of): Idx, ExitAccount, boolean determining if
329// the Exit created a new Leaf in the ExitTree.
330func (s *StateDB) processL2Tx(exitTree *merkletree.MerkleTree, tx *common.PoolL2Tx) (*common.Idx, *common.Account, bool, error) {
331 var err error
332 // if tx.ToIdx==0, get toIdx by ToEthAddr or ToBJJ
333 if tx.ToIdx == common.Idx(0) && tx.AuxToIdx == common.Idx(0) {
334 tx.AuxToIdx, err = s.GetIdxByEthAddrBJJ(tx.ToEthAddr, tx.ToBJJ)
335 if err != nil {
336 log.Error(err)
337 return nil, nil, false, err
338 }
339 }
340
341 // ZKInputs
342 if s.zki != nil {
343 // Txs
344 // s.zki.TxCompressedData[s.i] = tx.TxCompressedData() // uncomment once L1Tx.TxCompressedData is ready
345 // s.zki.TxCompressedDataV2[s.i] = tx.TxCompressedDataV2() // uncomment once L2Tx.TxCompressedDataV2 is ready
346 s.zki.FromIdx[s.i] = tx.FromIdx.BigInt()
347 s.zki.ToIdx[s.i] = tx.ToIdx.BigInt()
348
349 // fill AuxToIdx if needed
350 if tx.ToIdx == 0 {
351 // use toIdx that can have been filled by tx.ToIdx or
352 // if tx.Idx==0 (this case), toIdx is filled by the Idx
353 // from db by ToEthAddr&ToBJJ
354 s.zki.AuxToIdx[s.i] = tx.AuxToIdx.BigInt()
355 }
356
357 if tx.ToBJJ != nil {
358 s.zki.ToBJJAy[s.i] = tx.ToBJJ.Y
359 }
360 s.zki.ToEthAddr[s.i] = common.EthAddrToBigInt(tx.ToEthAddr)
361
362 s.zki.OnChain[s.i] = big.NewInt(0)
363 s.zki.NewAccount[s.i] = big.NewInt(0)
364
365 // L2Txs
366 // s.zki.RqOffset[s.i] = // TODO Rq once TxSelector is ready
367 // s.zki.RqTxCompressedDataV2[s.i] = // TODO
368 // s.zki.RqToEthAddr[s.i] = common.EthAddrToBigInt(tx.RqToEthAddr) // TODO
369 // s.zki.RqToBJJAy[s.i] = tx.ToBJJ.Y // TODO
370 signature, err := tx.Signature.Decompress()
371 if err != nil {
372 log.Error(err)
373 return nil, nil, false, err
374 }
375 s.zki.S[s.i] = signature.S
376 s.zki.R8x[s.i] = signature.R8.X
377 s.zki.R8y[s.i] = signature.R8.Y
378 }
379
380 // if StateDB type==TypeSynchronizer, will need to add Nonce
381 if s.typ == TypeSynchronizer {
382 // as type==TypeSynchronizer, always tx.ToIdx!=0
383 acc, err := s.GetAccount(tx.FromIdx)
384 if err != nil {
385 log.Error(err)
386 return nil, nil, false, err
387 }
388 tx.Nonce = acc.Nonce
389 tx.TokenID = acc.TokenID
390 }
391
392 switch tx.Type {
393 case common.TxTypeTransfer:
394 // go to the MT account of sender and receiver, and update
395 // balance & nonce
396 err = s.applyTransfer(tx.Tx(), tx.AuxToIdx)
397 if err != nil {
398 log.Error(err)
399 return nil, nil, false, err
400 }
401 case common.TxTypeExit:
402 // execute exit flow
403 exitAccount, newExit, err := s.applyExit(exitTree, tx.Tx())
404 if err != nil {
405 log.Error(err)
406 return nil, nil, false, err
407 }
408 return &tx.FromIdx, exitAccount, newExit, nil
409 default:
410 }
411 return nil, nil, false, nil
412}
413
414// applyCreateAccount creates a new account in the account of the depositer, it
415// stores the deposit value
416func (s *StateDB) applyCreateAccount(tx *common.L1Tx) error {
417 account := &common.Account{
418 TokenID: tx.TokenID,
419 Nonce: 0,
420 Balance: tx.LoadAmount,
421 PublicKey: tx.FromBJJ,
422 EthAddr: tx.FromEthAddr,
423 }
424
425 p, err := s.CreateAccount(common.Idx(s.idx+1), account)
426 if err != nil {
427 return err
428 }
429 if s.zki != nil {
430 s.zki.TokenID1[s.i] = tx.TokenID.BigInt()
431 s.zki.Nonce1[s.i] = big.NewInt(0)
432 if babyjub.PointCoordSign(tx.FromBJJ.X) {
433 s.zki.Sign1[s.i] = big.NewInt(1)
434 }
435 s.zki.Ay1[s.i] = tx.FromBJJ.Y
436 s.zki.Balance1[s.i] = tx.LoadAmount
437 s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(tx.FromEthAddr)
438 s.zki.Siblings1[s.i] = siblingsToZKInputFormat(p.Siblings)
439 if p.IsOld0 {
440 s.zki.IsOld0_1[s.i] = big.NewInt(1)
441 }
442 s.zki.OldKey1[s.i] = p.OldKey.BigInt()
443 s.zki.OldValue1[s.i] = p.OldValue.BigInt()
444 }
445
446 s.idx = s.idx + 1
447 return s.setIdx(s.idx)
448}
449
450// applyDeposit updates the balance in the account of the depositer, if
451// andTransfer parameter is set to true, the method will also apply the
452// Transfer of the L1Tx/DepositTransfer
453func (s *StateDB) applyDeposit(tx *common.L1Tx, transfer bool) error {
454 // deposit the tx.LoadAmount into the sender account
455 accSender, err := s.GetAccount(tx.FromIdx)
456 if err != nil {
457 return err
458 }
459 accSender.Balance = new(big.Int).Add(accSender.Balance, tx.LoadAmount)
460
461 // in case that the tx is a L1Tx>DepositTransfer
462 var accReceiver *common.Account
463 if transfer {
464 accReceiver, err = s.GetAccount(tx.ToIdx)
465 if err != nil {
466 return err
467 }
468 // subtract amount to the sender
469 accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.Amount)
470 // add amount to the receiver
471 accReceiver.Balance = new(big.Int).Add(accReceiver.Balance, tx.Amount)
472 }
473 // update sender account in localStateDB
474 p, err := s.UpdateAccount(tx.FromIdx, accSender)
475 if err != nil {
476 return err
477 }
478 if s.zki != nil {
479 s.zki.TokenID1[s.i] = accSender.TokenID.BigInt()
480 s.zki.Nonce1[s.i] = accSender.Nonce.BigInt()
481 if babyjub.PointCoordSign(accSender.PublicKey.X) {
482 s.zki.Sign1[s.i] = big.NewInt(1)
483 }
484 s.zki.Ay1[s.i] = accSender.PublicKey.Y
485 s.zki.Balance1[s.i] = accSender.Balance
486 s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(accSender.EthAddr)
487 s.zki.Siblings1[s.i] = siblingsToZKInputFormat(p.Siblings)
488 // IsOld0_1, OldKey1, OldValue1 not needed as this is not an insert
489 }
490
491 // this is done after updating Sender Account (depositer)
492 if transfer {
493 // update receiver account in localStateDB
494 p, err := s.UpdateAccount(tx.ToIdx, accReceiver)
495 if err != nil {
496 return err
497 }
498 if s.zki != nil {
499 s.zki.TokenID2[s.i] = accReceiver.TokenID.BigInt()
500 s.zki.Nonce2[s.i] = accReceiver.Nonce.BigInt()
501 if babyjub.PointCoordSign(accReceiver.PublicKey.X) {
502 s.zki.Sign2[s.i] = big.NewInt(1)
503 }
504 s.zki.Ay2[s.i] = accReceiver.PublicKey.Y
505 s.zki.Balance2[s.i] = accReceiver.Balance
506 s.zki.EthAddr2[s.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
507 s.zki.Siblings2[s.i] = siblingsToZKInputFormat(p.Siblings)
508 // IsOld0_2, OldKey2, OldValue2 not needed as this is not an insert
509 }
510 }
511
512 return nil
513}
514
515// applyTransfer updates the balance & nonce in the account of the sender, and
516// the balance in the account of the receiver.
517// Parameter 'toIdx' should be at 0 if the tx already has tx.ToIdx!=0, if
518// tx.ToIdx==0, then toIdx!=0, and will be used the toIdx parameter as Idx of
519// the receiver. This parameter is used when the tx.ToIdx is not specified and
520// the real ToIdx is found trhrough the ToEthAddr or ToBJJ.
521func (s *StateDB) applyTransfer(tx common.Tx, auxToIdx common.Idx) error {
522 if auxToIdx == common.Idx(0) {
523 auxToIdx = tx.ToIdx
524 }
525 // get sender and receiver accounts from localStateDB
526 accSender, err := s.GetAccount(tx.FromIdx)
527 if err != nil {
528 log.Error(err)
529 return err
530 }
531 accReceiver, err := s.GetAccount(auxToIdx)
532 if err != nil {
533 log.Error(err)
534 return err
535 }
536
537 // increment nonce
538 accSender.Nonce++
539
540 // subtract amount to the sender
541 accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.Amount)
542 // add amount to the receiver
543 accReceiver.Balance = new(big.Int).Add(accReceiver.Balance, tx.Amount)
544
545 // update sender account in localStateDB
546 pSender, err := s.UpdateAccount(tx.FromIdx, accSender)
547 if err != nil {
548 log.Error(err)
549 return err
550 }
551 if s.zki != nil {
552 s.zki.TokenID1[s.i] = accSender.TokenID.BigInt()
553 s.zki.Nonce1[s.i] = accSender.Nonce.BigInt()
554 if babyjub.PointCoordSign(accSender.PublicKey.X) {
555 s.zki.Sign1[s.i] = big.NewInt(1)
556 }
557 s.zki.Ay1[s.i] = accSender.PublicKey.Y
558 s.zki.Balance1[s.i] = accSender.Balance
559 s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(accSender.EthAddr)
560 s.zki.Siblings1[s.i] = siblingsToZKInputFormat(pSender.Siblings)
561 }
562
563 // update receiver account in localStateDB
564 pReceiver, err := s.UpdateAccount(auxToIdx, accReceiver)
565 if err != nil {
566 return err
567 }
568 if s.zki != nil {
569 s.zki.TokenID2[s.i] = accReceiver.TokenID.BigInt()
570 s.zki.Nonce2[s.i] = accReceiver.Nonce.BigInt()
571 if babyjub.PointCoordSign(accReceiver.PublicKey.X) {
572 s.zki.Sign2[s.i] = big.NewInt(1)
573 }
574 s.zki.Ay2[s.i] = accReceiver.PublicKey.Y
575 s.zki.Balance2[s.i] = accReceiver.Balance
576 s.zki.EthAddr2[s.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
577 s.zki.Siblings2[s.i] = siblingsToZKInputFormat(pReceiver.Siblings)
578 }
579
580 return nil
581}
582
583// applyCreateAccountDepositTransfer, in a single tx, creates a new account,
584// makes a deposit, and performs a transfer to another account
585func (s *StateDB) applyCreateAccountDepositTransfer(tx *common.L1Tx) error {
586 accSender := &common.Account{
587 TokenID: tx.TokenID,
588 Nonce: 0,
589 Balance: tx.LoadAmount,
590 PublicKey: tx.FromBJJ,
591 EthAddr: tx.FromEthAddr,
592 }
593 accSender.Balance = new(big.Int).Add(accSender.Balance, tx.LoadAmount)
594 accReceiver, err := s.GetAccount(tx.ToIdx)
595 if err != nil {
596 return err
597 }
598 // subtract amount to the sender
599 accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.Amount)
600 // add amount to the receiver
601 accReceiver.Balance = new(big.Int).Add(accReceiver.Balance, tx.Amount)
602
603 // create Account of the Sender
604 p, err := s.CreateAccount(common.Idx(s.idx+1), accSender)
605 if err != nil {
606 return err
607 }
608 if s.zki != nil {
609 s.zki.TokenID1[s.i] = tx.TokenID.BigInt()
610 s.zki.Nonce1[s.i] = big.NewInt(0)
611 if babyjub.PointCoordSign(tx.FromBJJ.X) {
612 s.zki.Sign1[s.i] = big.NewInt(1)
613 }
614 s.zki.Ay1[s.i] = tx.FromBJJ.Y
615 s.zki.Balance1[s.i] = tx.LoadAmount
616 s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(tx.FromEthAddr)
617 s.zki.Siblings1[s.i] = siblingsToZKInputFormat(p.Siblings)
618 if p.IsOld0 {
619 s.zki.IsOld0_1[s.i] = big.NewInt(1)
620 }
621 s.zki.OldKey1[s.i] = p.OldKey.BigInt()
622 s.zki.OldValue1[s.i] = p.OldValue.BigInt()
623 }
624
625 // update receiver account in localStateDB
626 p, err = s.UpdateAccount(tx.ToIdx, accReceiver)
627 if err != nil {
628 return err
629 }
630 if s.zki != nil {
631 s.zki.TokenID2[s.i] = accReceiver.TokenID.BigInt()
632 s.zki.Nonce2[s.i] = accReceiver.Nonce.BigInt()
633 if babyjub.PointCoordSign(accReceiver.PublicKey.X) {
634 s.zki.Sign2[s.i] = big.NewInt(1)
635 }
636 s.zki.Ay2[s.i] = accReceiver.PublicKey.Y
637 s.zki.Balance2[s.i] = accReceiver.Balance
638 s.zki.EthAddr2[s.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
639 s.zki.Siblings2[s.i] = siblingsToZKInputFormat(p.Siblings)
640 }
641
642 s.idx = s.idx + 1
643 return s.setIdx(s.idx)
644}
645
646// It returns the ExitAccount and a boolean determining if the Exit created a
647// new Leaf in the ExitTree.
648func (s *StateDB) applyExit(exitTree *merkletree.MerkleTree, tx common.Tx) (*common.Account, bool, error) {
649 // 0. subtract tx.Amount from current Account in StateMT
650 // add the tx.Amount into the Account (tx.FromIdx) in the ExitMT
651 acc, err := s.GetAccount(tx.FromIdx)
652 if err != nil {
653 return nil, false, err
654 }
655 acc.Balance = new(big.Int).Sub(acc.Balance, tx.Amount)
656 p, err := s.UpdateAccount(tx.FromIdx, acc)
657 if err != nil {
658 return nil, false, err
659 }
660 if s.zki != nil {
661 s.zki.TokenID1[s.i] = acc.TokenID.BigInt()
662 s.zki.Nonce1[s.i] = acc.Nonce.BigInt()
663 if babyjub.PointCoordSign(acc.PublicKey.X) {
664 s.zki.Sign1[s.i] = big.NewInt(1)
665 }
666 s.zki.Ay1[s.i] = acc.PublicKey.Y
667 s.zki.Balance1[s.i] = acc.Balance
668 s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(acc.EthAddr)
669 s.zki.Siblings1[s.i] = siblingsToZKInputFormat(p.Siblings)
670 }
671
672 if exitTree == nil {
673 return nil, false, nil
674 }
675 exitAccount, err := getAccountInTreeDB(exitTree.DB(), tx.FromIdx)
676 if err == db.ErrNotFound {
677 // 1a. if idx does not exist in exitTree:
678 // add new leaf 'ExitTreeLeaf', where ExitTreeLeaf.Balance = exitAmount (exitAmount=tx.Amount)
679 exitAccount := &common.Account{
680 TokenID: acc.TokenID,
681 Nonce: common.Nonce(1),
682 Balance: tx.Amount,
683 PublicKey: acc.PublicKey,
684 EthAddr: acc.EthAddr,
685 }
686 _, err = createAccountInTreeDB(exitTree.DB(), exitTree, tx.FromIdx, exitAccount)
687 return exitAccount, true, err
688 } else if err != nil {
689 return exitAccount, false, err
690 }
691
692 // 1b. if idx already exist in exitTree:
693 // update account, where account.Balance += exitAmount
694 exitAccount.Balance = new(big.Int).Add(exitAccount.Balance, tx.Amount)
695 _, err = updateAccountInTreeDB(exitTree.DB(), exitTree, tx.FromIdx, exitAccount)
696 return exitAccount, false, err
697}
698
699// getIdx returns the stored Idx from the localStateDB, which is the last Idx
700// used for an Account in the localStateDB.
701func (s *StateDB) getIdx() (common.Idx, error) {
702 idxBytes, err := s.DB().Get(keyidx)
703 if err == db.ErrNotFound {
704 return 0, nil
705 }
706 if err != nil {
707 return 0, err
708 }
709 return common.IdxFromBytes(idxBytes[:4])
710}
711
712// setIdx stores Idx in the localStateDB
713func (s *StateDB) setIdx(idx common.Idx) error {
714 tx, err := s.DB().NewTx()
715 if err != nil {
716 return err
717 }
718 idxBytes, err := idx.Bytes()
719 if err != nil {
720 return err
721 }
722 err = tx.Put(keyidx, idxBytes[:])
723 if err != nil {
724 return err
725 }
726 if err := tx.Commit(); err != nil {
727 return err
728 }
729 return nil
730}