You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

230 lines
5.8 KiB

  1. package common
  2. import (
  3. "crypto/sha256"
  4. "fmt"
  5. "math/big"
  6. "github.com/hermeznetwork/tracerr"
  7. )
  8. // L2Tx is a struct that represents an already forged L2 tx
  9. type L2Tx struct {
  10. // Stored in DB: mandatory fileds
  11. TxID TxID `meddler:"id"`
  12. BatchNum BatchNum `meddler:"batch_num"` // batchNum in which this tx was forged.
  13. Position int `meddler:"position"`
  14. FromIdx Idx `meddler:"from_idx"`
  15. ToIdx Idx `meddler:"to_idx"`
  16. // TokenID is filled by the TxProcessor
  17. TokenID TokenID `meddler:"token_id"`
  18. Amount *big.Int `meddler:"amount,bigint"`
  19. Fee FeeSelector `meddler:"fee"`
  20. // Nonce is filled by the TxProcessor
  21. Nonce Nonce `meddler:"nonce"`
  22. Type TxType `meddler:"type"`
  23. EthBlockNum int64 `meddler:"eth_block_num"` // Ethereum Block Number in which this L2Tx was added to the queue
  24. }
  25. // NewL2Tx returns the given L2Tx with the TxId & Type parameters calculated
  26. // from the L2Tx values
  27. func NewL2Tx(tx *L2Tx) (*L2Tx, error) {
  28. txTypeOld := tx.Type
  29. if err := tx.SetType(); err != nil {
  30. return nil, tracerr.Wrap(err)
  31. }
  32. // If original Type doesn't match the correct one, return error
  33. if txTypeOld != "" && txTypeOld != tx.Type {
  34. return nil, tracerr.Wrap(fmt.Errorf("L2Tx.Type: %s, should be: %s",
  35. tx.Type, txTypeOld))
  36. }
  37. txIDOld := tx.TxID
  38. if err := tx.SetID(); err != nil {
  39. return nil, tracerr.Wrap(err)
  40. }
  41. // If original TxID doesn't match the correct one, return error
  42. if txIDOld != (TxID{}) && txIDOld != tx.TxID {
  43. return tx, tracerr.Wrap(fmt.Errorf("L2Tx.TxID: %s, should be: %s",
  44. tx.TxID.String(), txIDOld.String()))
  45. }
  46. return tx, nil
  47. }
  48. // SetType sets the type of the transaction. Uses (FromIdx, Nonce).
  49. func (tx *L2Tx) SetType() error {
  50. if tx.ToIdx == Idx(1) {
  51. tx.Type = TxTypeExit
  52. } else if tx.ToIdx >= IdxUserThreshold {
  53. tx.Type = TxTypeTransfer
  54. } else {
  55. return tracerr.Wrap(fmt.Errorf(
  56. "cannot determine type of L2Tx, invalid ToIdx value: %d", tx.ToIdx))
  57. }
  58. return nil
  59. }
  60. // SetID sets the ID of the transaction
  61. func (tx *L2Tx) SetID() error {
  62. txID, err := tx.CalculateTxID()
  63. if err != nil {
  64. return err
  65. }
  66. tx.TxID = txID
  67. return nil
  68. }
  69. // CalculateTxID returns the TxID of the transaction. This method is used to
  70. // set the TxID for L2Tx and for PoolL2Tx.
  71. func (tx L2Tx) CalculateTxID() ([TxIDLen]byte, error) {
  72. var txID TxID
  73. var b []byte
  74. // FromIdx
  75. fromIdxBytes, err := tx.FromIdx.Bytes()
  76. if err != nil {
  77. return txID, tracerr.Wrap(err)
  78. }
  79. b = append(b, fromIdxBytes[:]...)
  80. // TokenID
  81. b = append(b, tx.TokenID.Bytes()[:]...)
  82. // Amount
  83. amountFloat16, err := NewFloat16(tx.Amount)
  84. if err != nil {
  85. return txID, tracerr.Wrap(fmt.Errorf("%s: %d", err, tx.Amount))
  86. }
  87. b = append(b, amountFloat16.Bytes()...)
  88. // Nonce
  89. nonceBytes, err := tx.Nonce.Bytes()
  90. if err != nil {
  91. return txID, tracerr.Wrap(err)
  92. }
  93. b = append(b, nonceBytes[:]...)
  94. // Fee
  95. b = append(b, byte(tx.Fee))
  96. // calculate hash
  97. h := sha256.New()
  98. _, err = h.Write(b)
  99. if err != nil {
  100. return txID, tracerr.Wrap(err)
  101. }
  102. r := h.Sum(nil)
  103. txID[0] = TxIDPrefixL2Tx
  104. copy(txID[1:], r)
  105. return txID, nil
  106. }
  107. // Tx returns a *Tx from the L2Tx
  108. func (tx *L2Tx) Tx() *Tx {
  109. batchNum := new(BatchNum)
  110. *batchNum = tx.BatchNum
  111. fee := new(FeeSelector)
  112. *fee = tx.Fee
  113. nonce := new(Nonce)
  114. *nonce = tx.Nonce
  115. return &Tx{
  116. IsL1: false,
  117. TxID: tx.TxID,
  118. Type: tx.Type,
  119. Position: tx.Position,
  120. FromIdx: tx.FromIdx,
  121. ToIdx: tx.ToIdx,
  122. TokenID: tx.TokenID,
  123. Amount: tx.Amount,
  124. BatchNum: batchNum,
  125. EthBlockNum: tx.EthBlockNum,
  126. Fee: fee,
  127. Nonce: nonce,
  128. }
  129. }
  130. // PoolL2Tx returns the data structure of PoolL2Tx with the parameters of a
  131. // L2Tx filled
  132. func (tx L2Tx) PoolL2Tx() *PoolL2Tx {
  133. return &PoolL2Tx{
  134. TxID: tx.TxID,
  135. FromIdx: tx.FromIdx,
  136. ToIdx: tx.ToIdx,
  137. TokenID: tx.TokenID,
  138. Amount: tx.Amount,
  139. Fee: tx.Fee,
  140. Nonce: tx.Nonce,
  141. Type: tx.Type,
  142. }
  143. }
  144. // L2TxsToPoolL2Txs returns an array of []*PoolL2Tx from an array of []*L2Tx,
  145. // where the PoolL2Tx only have the parameters of a L2Tx filled.
  146. func L2TxsToPoolL2Txs(txs []L2Tx) []PoolL2Tx {
  147. var r []PoolL2Tx
  148. for _, tx := range txs {
  149. r = append(r, *tx.PoolL2Tx())
  150. }
  151. return r
  152. }
  153. // TxIDsFromL2Txs returns an array of TxID from the []L2Tx
  154. func TxIDsFromL2Txs(txs []L2Tx) []TxID {
  155. txIDs := make([]TxID, len(txs))
  156. for i, tx := range txs {
  157. txIDs[i] = tx.TxID
  158. }
  159. return txIDs
  160. }
  161. // BytesDataAvailability encodes a L2Tx into []byte for the Data Availability
  162. // [ fromIdx | toIdx | amountFloat16 | Fee ]
  163. func (tx L2Tx) BytesDataAvailability(nLevels uint32) ([]byte, error) {
  164. idxLen := nLevels / 8 //nolint:gomnd
  165. b := make([]byte, ((nLevels*2)+16+8)/8) //nolint:gomnd
  166. fromIdxBytes, err := tx.FromIdx.Bytes()
  167. if err != nil {
  168. return nil, tracerr.Wrap(err)
  169. }
  170. copy(b[0:idxLen], fromIdxBytes[6-idxLen:]) // [6-idxLen:] as is BigEndian
  171. toIdxBytes, err := tx.ToIdx.Bytes()
  172. if err != nil {
  173. return nil, tracerr.Wrap(err)
  174. }
  175. copy(b[idxLen:idxLen*2], toIdxBytes[6-idxLen:])
  176. amountFloat16, err := NewFloat16(tx.Amount)
  177. if err != nil {
  178. return nil, tracerr.Wrap(err)
  179. }
  180. copy(b[idxLen*2:idxLen*2+2], amountFloat16.Bytes())
  181. b[idxLen*2+2] = byte(tx.Fee)
  182. return b[:], nil
  183. }
  184. // L2TxFromBytesDataAvailability decodes a L2Tx from []byte (Data Availability)
  185. func L2TxFromBytesDataAvailability(b []byte, nLevels int) (*L2Tx, error) {
  186. idxLen := nLevels / 8 //nolint:gomnd
  187. tx := &L2Tx{}
  188. var err error
  189. var paddedFromIdxBytes [6]byte
  190. copy(paddedFromIdxBytes[6-idxLen:], b[0:idxLen])
  191. tx.FromIdx, err = IdxFromBytes(paddedFromIdxBytes[:])
  192. if err != nil {
  193. return nil, tracerr.Wrap(err)
  194. }
  195. var paddedToIdxBytes [6]byte
  196. copy(paddedToIdxBytes[6-idxLen:6], b[idxLen:idxLen*2])
  197. tx.ToIdx, err = IdxFromBytes(paddedToIdxBytes[:])
  198. if err != nil {
  199. return nil, tracerr.Wrap(err)
  200. }
  201. tx.Amount = Float16FromBytes(b[idxLen*2 : idxLen*2+2]).BigInt()
  202. tx.Fee = FeeSelector(b[idxLen*2+2])
  203. return tx, nil
  204. }