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