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.

388 lines
12 KiB

  1. package common
  2. import (
  3. "encoding/binary"
  4. "errors"
  5. "fmt"
  6. "math/big"
  7. "time"
  8. ethCommon "github.com/ethereum/go-ethereum/common"
  9. "github.com/hermeznetwork/tracerr"
  10. "github.com/iden3/go-iden3-crypto/babyjub"
  11. "github.com/iden3/go-iden3-crypto/poseidon"
  12. )
  13. // EmptyBJJComp contains the 32 byte array of a empty BabyJubJub PublicKey
  14. // Compressed. It is a valid point in the BabyJubJub curve, so does not give
  15. // errors when being decompressed.
  16. var EmptyBJJComp = babyjub.PublicKeyComp([32]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0})
  17. // PoolL2Tx is a struct that represents a L2Tx sent by an account to the
  18. // coordinator that is waiting to be forged
  19. type PoolL2Tx struct {
  20. // Stored in DB: mandatory fileds
  21. // TxID (12 bytes) for L2Tx is:
  22. // bytes: | 1 | 6 | 5 |
  23. // values: | type | FromIdx | Nonce |
  24. TxID TxID `meddler:"tx_id"`
  25. FromIdx Idx `meddler:"from_idx"`
  26. ToIdx Idx `meddler:"to_idx,zeroisnull"`
  27. // AuxToIdx is only used internally at the StateDB to avoid repeated
  28. // computation when processing transactions (from Synchronizer,
  29. // TxSelector, BatchBuilder)
  30. AuxToIdx Idx `meddler:"-"`
  31. ToEthAddr ethCommon.Address `meddler:"to_eth_addr,zeroisnull"`
  32. ToBJJ babyjub.PublicKeyComp `meddler:"to_bjj,zeroisnull"`
  33. TokenID TokenID `meddler:"token_id"`
  34. Amount *big.Int `meddler:"amount,bigint"` // TODO: change to float16
  35. Fee FeeSelector `meddler:"fee"`
  36. Nonce Nonce `meddler:"nonce"` // effective 40 bits used
  37. State PoolL2TxState `meddler:"state"`
  38. // Info contains information about the status & State of the
  39. // transaction. As for example, if the Tx has not been selected in the
  40. // last batch due not enough Balance at the Sender account, this reason
  41. // would appear at this parameter.
  42. Info string `meddler:"info,zeroisnull"`
  43. Signature babyjub.SignatureComp `meddler:"signature"` // tx signature
  44. Timestamp time.Time `meddler:"timestamp,utctime"` // time when added to the tx pool
  45. // Stored in DB: optional fileds, may be uninitialized
  46. RqFromIdx Idx `meddler:"rq_from_idx,zeroisnull"`
  47. RqToIdx Idx `meddler:"rq_to_idx,zeroisnull"`
  48. RqToEthAddr ethCommon.Address `meddler:"rq_to_eth_addr,zeroisnull"`
  49. RqToBJJ babyjub.PublicKeyComp `meddler:"rq_to_bjj,zeroisnull"`
  50. RqTokenID TokenID `meddler:"rq_token_id,zeroisnull"`
  51. RqAmount *big.Int `meddler:"rq_amount,bigintnull"` // TODO: change to float16
  52. RqFee FeeSelector `meddler:"rq_fee,zeroisnull"`
  53. RqNonce Nonce `meddler:"rq_nonce,zeroisnull"` // effective 48 bits used
  54. AbsoluteFee float64 `meddler:"fee_usd,zeroisnull"`
  55. AbsoluteFeeUpdate time.Time `meddler:"usd_update,utctimez"`
  56. Type TxType `meddler:"tx_type"`
  57. // Extra metadata, may be uninitialized
  58. RqTxCompressedData []byte `meddler:"-"` // 253 bits, optional for atomic txs
  59. }
  60. // NewPoolL2Tx returns the given L2Tx with the TxId & Type parameters calculated
  61. // from the L2Tx values
  62. func NewPoolL2Tx(tx *PoolL2Tx) (*PoolL2Tx, error) {
  63. txTypeOld := tx.Type
  64. if err := tx.SetType(); err != nil {
  65. return nil, tracerr.Wrap(err)
  66. }
  67. // If original Type doesn't match the correct one, return error
  68. if txTypeOld != "" && txTypeOld != tx.Type {
  69. return nil, tracerr.Wrap(fmt.Errorf("L2Tx.Type: %s, should be: %s",
  70. tx.Type, txTypeOld))
  71. }
  72. txIDOld := tx.TxID
  73. if err := tx.SetID(); err != nil {
  74. return nil, tracerr.Wrap(err)
  75. }
  76. // If original TxID doesn't match the correct one, return error
  77. if txIDOld != (TxID{}) && txIDOld != tx.TxID {
  78. return tx, tracerr.Wrap(fmt.Errorf("PoolL2Tx.TxID: %s, should be: %s",
  79. tx.TxID.String(), txIDOld.String()))
  80. }
  81. return tx, nil
  82. }
  83. // SetType sets the type of the transaction
  84. func (tx *PoolL2Tx) SetType() error {
  85. if tx.ToIdx >= IdxUserThreshold {
  86. tx.Type = TxTypeTransfer
  87. } else if tx.ToIdx == 1 {
  88. tx.Type = TxTypeExit
  89. } else if tx.ToIdx == 0 {
  90. if tx.ToBJJ != EmptyBJJComp && tx.ToEthAddr == FFAddr {
  91. tx.Type = TxTypeTransferToBJJ
  92. } else if tx.ToEthAddr != FFAddr && tx.ToEthAddr != EmptyAddr {
  93. tx.Type = TxTypeTransferToEthAddr
  94. }
  95. } else {
  96. return tracerr.Wrap(errors.New("malformed transaction"))
  97. }
  98. return nil
  99. }
  100. // SetID sets the ID of the transaction
  101. func (tx *PoolL2Tx) SetID() error {
  102. txID, err := tx.L2Tx().CalculateTxID()
  103. if err != nil {
  104. return tracerr.Wrap(err)
  105. }
  106. tx.TxID = txID
  107. return nil
  108. }
  109. // TxCompressedData spec:
  110. // [ 1 bits ] toBJJSign // 1 byte
  111. // [ 8 bits ] userFee // 1 byte
  112. // [ 40 bits ] nonce // 5 bytes
  113. // [ 32 bits ] tokenID // 4 bytes
  114. // [ 16 bits ] amountFloat16 // 2 bytes
  115. // [ 48 bits ] toIdx // 6 bytes
  116. // [ 48 bits ] fromIdx // 6 bytes
  117. // [ 16 bits ] chainId // 2 bytes
  118. // [ 32 bits ] signatureConstant // 4 bytes
  119. // Total bits compressed data: 241 bits // 31 bytes in *big.Int representation
  120. func (tx *PoolL2Tx) TxCompressedData(chainID uint16) (*big.Int, error) {
  121. amountFloat16, err := NewFloat16(tx.Amount)
  122. if err != nil {
  123. return nil, tracerr.Wrap(err)
  124. }
  125. var b [31]byte
  126. toBJJSign := byte(0)
  127. pkSign, _ := babyjub.UnpackSignY(tx.ToBJJ)
  128. if pkSign {
  129. toBJJSign = byte(1)
  130. }
  131. b[0] = toBJJSign
  132. b[1] = byte(tx.Fee)
  133. nonceBytes, err := tx.Nonce.Bytes()
  134. if err != nil {
  135. return nil, tracerr.Wrap(err)
  136. }
  137. copy(b[2:7], nonceBytes[:])
  138. copy(b[7:11], tx.TokenID.Bytes())
  139. copy(b[11:13], amountFloat16.Bytes())
  140. toIdxBytes, err := tx.ToIdx.Bytes()
  141. if err != nil {
  142. return nil, tracerr.Wrap(err)
  143. }
  144. copy(b[13:19], toIdxBytes[:])
  145. fromIdxBytes, err := tx.FromIdx.Bytes()
  146. if err != nil {
  147. return nil, tracerr.Wrap(err)
  148. }
  149. copy(b[19:25], fromIdxBytes[:])
  150. binary.BigEndian.PutUint16(b[25:27], chainID)
  151. copy(b[27:31], SignatureConstantBytes[:])
  152. bi := new(big.Int).SetBytes(b[:])
  153. return bi, nil
  154. }
  155. // TxCompressedDataEmpty calculates the TxCompressedData of an empty
  156. // transaction
  157. func TxCompressedDataEmpty(chainID uint16) *big.Int {
  158. var b [31]byte
  159. binary.BigEndian.PutUint16(b[25:27], chainID)
  160. copy(b[27:31], SignatureConstantBytes[:])
  161. bi := new(big.Int).SetBytes(b[:])
  162. return bi
  163. }
  164. // TxCompressedDataV2 spec:
  165. // [ 1 bits ] toBJJSign // 1 byte
  166. // [ 8 bits ] userFee // 1 byte
  167. // [ 40 bits ] nonce // 5 bytes
  168. // [ 32 bits ] tokenID // 4 bytes
  169. // [ 16 bits ] amountFloat16 // 2 bytes
  170. // [ 48 bits ] toIdx // 6 bytes
  171. // [ 48 bits ] fromIdx // 6 bytes
  172. // Total bits compressed data: 193 bits // 25 bytes in *big.Int representation
  173. func (tx *PoolL2Tx) TxCompressedDataV2() (*big.Int, error) {
  174. if tx.Amount == nil {
  175. tx.Amount = big.NewInt(0)
  176. }
  177. amountFloat16, err := NewFloat16(tx.Amount)
  178. if err != nil {
  179. return nil, tracerr.Wrap(err)
  180. }
  181. var b [25]byte
  182. toBJJSign := byte(0)
  183. if tx.ToBJJ != EmptyBJJComp {
  184. sign, _ := babyjub.UnpackSignY(tx.ToBJJ)
  185. if sign {
  186. toBJJSign = byte(1)
  187. }
  188. }
  189. b[0] = toBJJSign
  190. b[1] = byte(tx.Fee)
  191. nonceBytes, err := tx.Nonce.Bytes()
  192. if err != nil {
  193. return nil, tracerr.Wrap(err)
  194. }
  195. copy(b[2:7], nonceBytes[:])
  196. copy(b[7:11], tx.TokenID.Bytes())
  197. copy(b[11:13], amountFloat16.Bytes())
  198. toIdxBytes, err := tx.ToIdx.Bytes()
  199. if err != nil {
  200. return nil, tracerr.Wrap(err)
  201. }
  202. copy(b[13:19], toIdxBytes[:])
  203. fromIdxBytes, err := tx.FromIdx.Bytes()
  204. if err != nil {
  205. return nil, tracerr.Wrap(err)
  206. }
  207. copy(b[19:25], fromIdxBytes[:])
  208. bi := new(big.Int).SetBytes(b[:])
  209. return bi, nil
  210. }
  211. // RqTxCompressedDataV2 is like the TxCompressedDataV2 but using the 'Rq'
  212. // parameters. In a future iteration of the hermez-node, the 'Rq' parameters
  213. // can be inside a struct, which contains the 'Rq' transaction grouped inside,
  214. // so then computing the 'RqTxCompressedDataV2' would be just calling
  215. // 'tx.Rq.TxCompressedDataV2()'.
  216. // RqTxCompressedDataV2 spec:
  217. // [ 1 bits ] rqToBJJSign // 1 byte
  218. // [ 8 bits ] rqUserFee // 1 byte
  219. // [ 40 bits ] rqNonce // 5 bytes
  220. // [ 32 bits ] rqTokenID // 4 bytes
  221. // [ 16 bits ] rqAmountFloat16 // 2 bytes
  222. // [ 48 bits ] rqToIdx // 6 bytes
  223. // [ 48 bits ] rqFromIdx // 6 bytes
  224. // Total bits compressed data: 193 bits // 25 bytes in *big.Int representation
  225. func (tx *PoolL2Tx) RqTxCompressedDataV2() (*big.Int, error) {
  226. if tx.RqAmount == nil {
  227. tx.RqAmount = big.NewInt(0)
  228. }
  229. amountFloat16, err := NewFloat16(tx.RqAmount)
  230. if err != nil {
  231. return nil, tracerr.Wrap(err)
  232. }
  233. var b [25]byte
  234. rqToBJJSign := byte(0)
  235. if tx.RqToBJJ != EmptyBJJComp {
  236. sign, _ := babyjub.UnpackSignY(tx.RqToBJJ)
  237. if sign {
  238. rqToBJJSign = byte(1)
  239. }
  240. }
  241. b[0] = rqToBJJSign
  242. b[1] = byte(tx.RqFee)
  243. nonceBytes, err := tx.RqNonce.Bytes()
  244. if err != nil {
  245. return nil, tracerr.Wrap(err)
  246. }
  247. copy(b[2:7], nonceBytes[:])
  248. copy(b[7:11], tx.RqTokenID.Bytes())
  249. copy(b[11:13], amountFloat16.Bytes())
  250. toIdxBytes, err := tx.RqToIdx.Bytes()
  251. if err != nil {
  252. return nil, tracerr.Wrap(err)
  253. }
  254. copy(b[13:19], toIdxBytes[:])
  255. fromIdxBytes, err := tx.RqFromIdx.Bytes()
  256. if err != nil {
  257. return nil, tracerr.Wrap(err)
  258. }
  259. copy(b[19:25], fromIdxBytes[:])
  260. bi := new(big.Int).SetBytes(b[:])
  261. return bi, nil
  262. }
  263. // HashToSign returns the computed Poseidon hash from the *PoolL2Tx that will
  264. // be signed by the sender.
  265. func (tx *PoolL2Tx) HashToSign(chainID uint16) (*big.Int, error) {
  266. toCompressedData, err := tx.TxCompressedData(chainID)
  267. if err != nil {
  268. return nil, tracerr.Wrap(err)
  269. }
  270. toEthAddr := EthAddrToBigInt(tx.ToEthAddr)
  271. rqToEthAddr := EthAddrToBigInt(tx.RqToEthAddr)
  272. _, toBJJY := babyjub.UnpackSignY(tx.ToBJJ)
  273. rqTxCompressedDataV2, err := tx.RqTxCompressedDataV2()
  274. if err != nil {
  275. return nil, tracerr.Wrap(err)
  276. }
  277. _, rqToBJJY := babyjub.UnpackSignY(tx.RqToBJJ)
  278. return poseidon.Hash([]*big.Int{toCompressedData, toEthAddr, toBJJY, rqTxCompressedDataV2, rqToEthAddr, rqToBJJY})
  279. }
  280. // VerifySignature returns true if the signature verification is correct for the given PublicKeyComp
  281. func (tx *PoolL2Tx) VerifySignature(chainID uint16, pkComp babyjub.PublicKeyComp) bool {
  282. h, err := tx.HashToSign(chainID)
  283. if err != nil {
  284. return false
  285. }
  286. s, err := tx.Signature.Decompress()
  287. if err != nil {
  288. return false
  289. }
  290. pk, err := pkComp.Decompress()
  291. if err != nil {
  292. return false
  293. }
  294. return pk.VerifyPoseidon(h, s)
  295. }
  296. // L2Tx returns a *L2Tx from the PoolL2Tx
  297. func (tx PoolL2Tx) L2Tx() L2Tx {
  298. var toIdx Idx
  299. if tx.ToIdx == Idx(0) {
  300. toIdx = tx.AuxToIdx
  301. } else {
  302. toIdx = tx.ToIdx
  303. }
  304. return L2Tx{
  305. TxID: tx.TxID,
  306. FromIdx: tx.FromIdx,
  307. ToIdx: toIdx,
  308. TokenID: tx.TokenID,
  309. Amount: tx.Amount,
  310. Fee: tx.Fee,
  311. Nonce: tx.Nonce,
  312. Type: tx.Type,
  313. }
  314. }
  315. // Tx returns a *Tx from the PoolL2Tx
  316. func (tx PoolL2Tx) Tx() Tx {
  317. return Tx{
  318. TxID: tx.TxID,
  319. FromIdx: tx.FromIdx,
  320. ToIdx: tx.ToIdx,
  321. Amount: tx.Amount,
  322. TokenID: tx.TokenID,
  323. Nonce: &tx.Nonce,
  324. Fee: &tx.Fee,
  325. Type: tx.Type,
  326. }
  327. }
  328. // PoolL2TxsToL2Txs returns an array of []L2Tx from an array of []PoolL2Tx
  329. func PoolL2TxsToL2Txs(txs []PoolL2Tx) ([]L2Tx, error) {
  330. l2Txs := make([]L2Tx, len(txs))
  331. for i, poolTx := range txs {
  332. l2Txs[i] = poolTx.L2Tx()
  333. }
  334. return l2Txs, nil
  335. }
  336. // TxIDsFromPoolL2Txs returns an array of TxID from the []PoolL2Tx
  337. func TxIDsFromPoolL2Txs(txs []PoolL2Tx) []TxID {
  338. txIDs := make([]TxID, len(txs))
  339. for i, tx := range txs {
  340. txIDs[i] = tx.TxID
  341. }
  342. return txIDs
  343. }
  344. // PoolL2TxState is a string that represents the status of a L2 transaction
  345. type PoolL2TxState string
  346. const (
  347. // PoolL2TxStatePending represents a valid L2Tx that hasn't started the
  348. // forging process
  349. PoolL2TxStatePending PoolL2TxState = "pend"
  350. // PoolL2TxStateForging represents a valid L2Tx that has started the
  351. // forging process
  352. PoolL2TxStateForging PoolL2TxState = "fing"
  353. // PoolL2TxStateForged represents a L2Tx that has already been forged
  354. PoolL2TxStateForged PoolL2TxState = "fged"
  355. // PoolL2TxStateInvalid represents a L2Tx that has been invalidated
  356. PoolL2TxStateInvalid PoolL2TxState = "invl"
  357. )