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.

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