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.

437 lines
13 KiB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. package common
  2. import (
  3. "encoding/binary"
  4. "fmt"
  5. "math/big"
  6. ethCommon "github.com/ethereum/go-ethereum/common"
  7. ethCrypto "github.com/ethereum/go-ethereum/crypto"
  8. "github.com/hermeznetwork/tracerr"
  9. "github.com/iden3/go-iden3-crypto/babyjub"
  10. )
  11. // L1Tx is a struct that represents a L1 tx
  12. type L1Tx struct {
  13. // Stored in DB: mandatory fileds
  14. // TxID (32 bytes) for L1Tx is the Keccak256 (ethereum) hash of:
  15. // bytes: | 1 | 8 | 2 | 1 |
  16. // values: | type | ToForgeL1TxsNum | Position | 0 (padding) |
  17. // where type:
  18. // - L1UserTx: 0
  19. // - L1CoordinatorTx: 1
  20. TxID TxID `meddler:"id"`
  21. // ToForgeL1TxsNum indicates in which the tx was forged / will be forged
  22. ToForgeL1TxsNum *int64 `meddler:"to_forge_l1_txs_num"`
  23. Position int `meddler:"position"`
  24. // UserOrigin is set to true if the tx was originated by a user, false if it was
  25. // aoriginated by a coordinator. Note that this differ from the spec for implementation
  26. // simplification purpposes
  27. UserOrigin bool `meddler:"user_origin"`
  28. // FromIdx is used by L1Tx/Deposit to indicate the Idx receiver of the L1Tx.DepositAmount
  29. // (deposit)
  30. FromIdx Idx `meddler:"from_idx,zeroisnull"`
  31. EffectiveFromIdx Idx `meddler:"effective_from_idx,zeroisnull"`
  32. FromEthAddr ethCommon.Address `meddler:"from_eth_addr,zeroisnull"`
  33. FromBJJ babyjub.PublicKeyComp `meddler:"from_bjj,zeroisnull"`
  34. // ToIdx is ignored in L1Tx/Deposit, but used in the L1Tx/DepositAndTransfer
  35. ToIdx Idx `meddler:"to_idx"`
  36. TokenID TokenID `meddler:"token_id"`
  37. Amount *big.Int `meddler:"amount,bigint"`
  38. // EffectiveAmount only applies to L1UserTx.
  39. EffectiveAmount *big.Int `meddler:"effective_amount,bigintnull"`
  40. DepositAmount *big.Int `meddler:"deposit_amount,bigint"`
  41. // EffectiveDepositAmount only applies to L1UserTx.
  42. EffectiveDepositAmount *big.Int `meddler:"effective_deposit_amount,bigintnull"`
  43. // Ethereum Block Number in which this L1Tx was added to the queue
  44. EthBlockNum int64 `meddler:"eth_block_num"`
  45. Type TxType `meddler:"type"`
  46. BatchNum *BatchNum `meddler:"batch_num"`
  47. }
  48. // NewL1Tx returns the given L1Tx with the TxId & Type parameters calculated
  49. // from the L1Tx values
  50. func NewL1Tx(tx *L1Tx) (*L1Tx, error) {
  51. txTypeOld := tx.Type
  52. if err := tx.SetType(); err != nil {
  53. return nil, tracerr.Wrap(err)
  54. }
  55. // If original Type doesn't match the correct one, return error
  56. if txTypeOld != "" && txTypeOld != tx.Type {
  57. return nil, tracerr.Wrap(fmt.Errorf("L1Tx.Type: %s, should be: %s",
  58. tx.Type, txTypeOld))
  59. }
  60. txIDOld := tx.TxID
  61. if err := tx.SetID(); err != nil {
  62. return nil, tracerr.Wrap(err)
  63. }
  64. // If original TxID doesn't match the correct one, return error
  65. if txIDOld != (TxID{}) && txIDOld != tx.TxID {
  66. return tx, tracerr.Wrap(fmt.Errorf("L1Tx.TxID: %s, should be: %s",
  67. tx.TxID.String(), txIDOld.String()))
  68. }
  69. return tx, nil
  70. }
  71. // SetType sets the type of the transaction
  72. func (tx *L1Tx) SetType() error {
  73. if tx.FromIdx == 0 {
  74. if tx.ToIdx == Idx(0) {
  75. tx.Type = TxTypeCreateAccountDeposit
  76. } else if tx.ToIdx >= IdxUserThreshold {
  77. tx.Type = TxTypeCreateAccountDepositTransfer
  78. } else {
  79. return tracerr.Wrap(fmt.Errorf(
  80. "Can not determine type of L1Tx, invalid ToIdx value: %d", tx.ToIdx))
  81. }
  82. } else if tx.FromIdx >= IdxUserThreshold {
  83. if tx.ToIdx == Idx(0) {
  84. tx.Type = TxTypeDeposit
  85. } else if tx.ToIdx == Idx(1) {
  86. tx.Type = TxTypeForceExit
  87. } else if tx.ToIdx >= IdxUserThreshold {
  88. if tx.DepositAmount.Int64() == int64(0) {
  89. tx.Type = TxTypeForceTransfer
  90. } else {
  91. tx.Type = TxTypeDepositTransfer
  92. }
  93. } else {
  94. return tracerr.Wrap(fmt.Errorf(
  95. "Can not determine type of L1Tx, invalid ToIdx value: %d", tx.ToIdx))
  96. }
  97. } else {
  98. return tracerr.Wrap(fmt.Errorf(
  99. "Can not determine type of L1Tx, invalid FromIdx value: %d", tx.FromIdx))
  100. }
  101. return nil
  102. }
  103. // SetID sets the ID of the transaction. For L1UserTx uses (ToForgeL1TxsNum,
  104. // Position), for L1CoordinatorTx uses (BatchNum, Position).
  105. func (tx *L1Tx) SetID() error {
  106. var b []byte
  107. if tx.UserOrigin {
  108. if tx.ToForgeL1TxsNum == nil {
  109. return tracerr.Wrap(fmt.Errorf("L1Tx.UserOrigin == true && L1Tx.ToForgeL1TxsNum == nil"))
  110. }
  111. tx.TxID[0] = TxIDPrefixL1UserTx
  112. var toForgeL1TxsNumBytes [8]byte
  113. binary.BigEndian.PutUint64(toForgeL1TxsNumBytes[:], uint64(*tx.ToForgeL1TxsNum))
  114. b = append(b, toForgeL1TxsNumBytes[:]...)
  115. } else {
  116. if tx.BatchNum == nil {
  117. return tracerr.Wrap(fmt.Errorf("L1Tx.UserOrigin == false && L1Tx.BatchNum == nil"))
  118. }
  119. tx.TxID[0] = TxIDPrefixL1CoordTx
  120. var batchNumBytes [8]byte
  121. binary.BigEndian.PutUint64(batchNumBytes[:], uint64(*tx.BatchNum))
  122. b = append(b, batchNumBytes[:]...)
  123. }
  124. var positionBytes [2]byte
  125. binary.BigEndian.PutUint16(positionBytes[:], uint16(tx.Position))
  126. b = append(b, positionBytes[:]...)
  127. // calculate hash
  128. h := ethCrypto.Keccak256Hash(b).Bytes()
  129. copy(tx.TxID[1:], h)
  130. return nil
  131. }
  132. // Tx returns a *Tx from the L1Tx
  133. func (tx L1Tx) Tx() Tx {
  134. f := new(big.Float).SetInt(tx.EffectiveAmount)
  135. amountFloat, _ := f.Float64()
  136. userOrigin := new(bool)
  137. *userOrigin = tx.UserOrigin
  138. genericTx := Tx{
  139. IsL1: true,
  140. TxID: tx.TxID,
  141. Type: tx.Type,
  142. Position: tx.Position,
  143. FromIdx: tx.FromIdx,
  144. ToIdx: tx.ToIdx,
  145. Amount: tx.EffectiveAmount,
  146. AmountFloat: amountFloat,
  147. TokenID: tx.TokenID,
  148. ToForgeL1TxsNum: tx.ToForgeL1TxsNum,
  149. UserOrigin: userOrigin,
  150. FromEthAddr: tx.FromEthAddr,
  151. FromBJJ: tx.FromBJJ,
  152. DepositAmount: tx.EffectiveDepositAmount,
  153. EthBlockNum: tx.EthBlockNum,
  154. }
  155. if tx.DepositAmount != nil {
  156. lf := new(big.Float).SetInt(tx.DepositAmount)
  157. depositAmountFloat, _ := lf.Float64()
  158. genericTx.DepositAmountFloat = &depositAmountFloat
  159. }
  160. return genericTx
  161. }
  162. // TxCompressedData spec:
  163. // [ 1 bits ] empty (toBJJSign) // 1 byte
  164. // [ 8 bits ] empty (userFee) // 1 byte
  165. // [ 40 bits ] empty (nonce) // 5 bytes
  166. // [ 32 bits ] tokenID // 4 bytes
  167. // [ 48 bits ] toIdx // 6 bytes
  168. // [ 48 bits ] fromIdx // 6 bytes
  169. // [ 16 bits ] chainId // 2 bytes
  170. // [ 32 bits ] empty (signatureConstant) // 4 bytes
  171. // Total bits compressed data: 225 bits // 29 bytes in *big.Int representation
  172. func (tx L1Tx) TxCompressedData(chainID uint16) (*big.Int, error) {
  173. var b [29]byte
  174. // b[0:7] empty: no ToBJJSign, no fee, no nonce
  175. copy(b[7:11], tx.TokenID.Bytes())
  176. toIdxBytes, err := tx.ToIdx.Bytes()
  177. if err != nil {
  178. return nil, tracerr.Wrap(err)
  179. }
  180. copy(b[11:17], toIdxBytes[:])
  181. fromIdxBytes, err := tx.FromIdx.Bytes()
  182. if err != nil {
  183. return nil, tracerr.Wrap(err)
  184. }
  185. copy(b[17:23], fromIdxBytes[:])
  186. binary.BigEndian.PutUint16(b[23:25], chainID)
  187. copy(b[25:29], SignatureConstantBytes[:])
  188. bi := new(big.Int).SetBytes(b[:])
  189. return bi, nil
  190. }
  191. // BytesDataAvailability encodes a L1Tx into []byte for the Data Availability
  192. // [ fromIdx | toIdx | amountFloat40 | Fee ]
  193. func (tx *L1Tx) BytesDataAvailability(nLevels uint32) ([]byte, error) {
  194. idxLen := nLevels / 8 //nolint:gomnd
  195. b := make([]byte, ((nLevels*2)+40+8)/8) //nolint:gomnd
  196. fromIdxBytes, err := tx.FromIdx.Bytes()
  197. if err != nil {
  198. return nil, tracerr.Wrap(err)
  199. }
  200. copy(b[0:idxLen], fromIdxBytes[6-idxLen:])
  201. toIdxBytes, err := tx.ToIdx.Bytes()
  202. if err != nil {
  203. return nil, tracerr.Wrap(err)
  204. }
  205. copy(b[idxLen:idxLen*2], toIdxBytes[6-idxLen:])
  206. if tx.EffectiveAmount != nil {
  207. amountFloat40, err := NewFloat40(tx.EffectiveAmount)
  208. if err != nil {
  209. return nil, tracerr.Wrap(err)
  210. }
  211. amountFloat40Bytes, err := amountFloat40.Bytes()
  212. if err != nil {
  213. return nil, tracerr.Wrap(err)
  214. }
  215. copy(b[idxLen*2:idxLen*2+Float40BytesLength], amountFloat40Bytes)
  216. }
  217. // fee = 0 (as is L1Tx)
  218. return b[:], nil
  219. }
  220. // L1TxFromDataAvailability decodes a L1Tx from []byte (Data Availability)
  221. func L1TxFromDataAvailability(b []byte, nLevels uint32) (*L1Tx, error) {
  222. idxLen := nLevels / 8 //nolint:gomnd
  223. fromIdxBytes := b[0:idxLen]
  224. toIdxBytes := b[idxLen : idxLen*2]
  225. amountBytes := b[idxLen*2 : idxLen*2+Float40BytesLength]
  226. l1tx := L1Tx{}
  227. fromIdx, err := IdxFromBytes(ethCommon.LeftPadBytes(fromIdxBytes, 6))
  228. if err != nil {
  229. return nil, tracerr.Wrap(err)
  230. }
  231. l1tx.FromIdx = fromIdx
  232. toIdx, err := IdxFromBytes(ethCommon.LeftPadBytes(toIdxBytes, 6))
  233. if err != nil {
  234. return nil, tracerr.Wrap(err)
  235. }
  236. l1tx.ToIdx = toIdx
  237. l1tx.EffectiveAmount, err = Float40FromBytes(amountBytes).BigInt()
  238. return &l1tx, tracerr.Wrap(err)
  239. }
  240. // BytesGeneric returns the generic representation of a L1Tx. This method is
  241. // used to compute the []byte representation of a L1UserTx, and also to compute
  242. // the L1TxData for the ZKInputs (at the HashGlobalInputs), using this method
  243. // for L1CoordinatorTxs & L1UserTxs (for the ZKInputs case).
  244. func (tx *L1Tx) BytesGeneric() ([]byte, error) {
  245. var b [RollupConstL1UserTotalBytes]byte
  246. copy(b[0:20], tx.FromEthAddr.Bytes())
  247. if tx.FromBJJ != EmptyBJJComp {
  248. pkCompL := tx.FromBJJ
  249. pkCompB := SwapEndianness(pkCompL[:])
  250. copy(b[20:52], pkCompB[:])
  251. }
  252. fromIdxBytes, err := tx.FromIdx.Bytes()
  253. if err != nil {
  254. return nil, tracerr.Wrap(err)
  255. }
  256. copy(b[52:58], fromIdxBytes[:])
  257. depositAmountFloat40, err := NewFloat40(tx.DepositAmount)
  258. if err != nil {
  259. return nil, tracerr.Wrap(err)
  260. }
  261. depositAmountFloat40Bytes, err := depositAmountFloat40.Bytes()
  262. if err != nil {
  263. return nil, tracerr.Wrap(err)
  264. }
  265. copy(b[58:63], depositAmountFloat40Bytes)
  266. amountFloat40, err := NewFloat40(tx.Amount)
  267. if err != nil {
  268. return nil, tracerr.Wrap(err)
  269. }
  270. amountFloat40Bytes, err := amountFloat40.Bytes()
  271. if err != nil {
  272. return nil, tracerr.Wrap(err)
  273. }
  274. copy(b[63:68], amountFloat40Bytes)
  275. copy(b[68:72], tx.TokenID.Bytes())
  276. toIdxBytes, err := tx.ToIdx.Bytes()
  277. if err != nil {
  278. return nil, tracerr.Wrap(err)
  279. }
  280. copy(b[72:78], toIdxBytes[:])
  281. return b[:], nil
  282. }
  283. // BytesUser encodes a L1UserTx into []byte
  284. func (tx *L1Tx) BytesUser() ([]byte, error) {
  285. if !tx.UserOrigin {
  286. return nil, tracerr.Wrap(fmt.Errorf("Can not calculate BytesUser() for a L1CoordinatorTx"))
  287. }
  288. return tx.BytesGeneric()
  289. }
  290. // BytesCoordinatorTx encodes a L1CoordinatorTx into []byte
  291. func (tx *L1Tx) BytesCoordinatorTx(compressedSignatureBytes []byte) ([]byte, error) {
  292. if tx.UserOrigin {
  293. return nil, tracerr.Wrap(fmt.Errorf("Can not calculate BytesCoordinatorTx() for a L1UserTx"))
  294. }
  295. var b [RollupConstL1CoordinatorTotalBytes]byte
  296. v := compressedSignatureBytes[64]
  297. s := compressedSignatureBytes[32:64]
  298. r := compressedSignatureBytes[0:32]
  299. b[0] = v
  300. copy(b[1:33], s)
  301. copy(b[33:65], r)
  302. pkCompL := tx.FromBJJ
  303. pkCompB := SwapEndianness(pkCompL[:])
  304. copy(b[65:97], pkCompB[:])
  305. copy(b[97:101], tx.TokenID.Bytes())
  306. return b[:], nil
  307. }
  308. // L1UserTxFromBytes decodes a L1Tx from []byte
  309. func L1UserTxFromBytes(b []byte) (*L1Tx, error) {
  310. if len(b) != RollupConstL1UserTotalBytes {
  311. return nil,
  312. tracerr.Wrap(fmt.Errorf("Can not parse L1Tx bytes, expected length %d, current: %d",
  313. 68, len(b)))
  314. }
  315. tx := &L1Tx{
  316. UserOrigin: true,
  317. }
  318. var err error
  319. tx.FromEthAddr = ethCommon.BytesToAddress(b[0:20])
  320. pkCompB := b[20:52]
  321. pkCompL := SwapEndianness(pkCompB)
  322. copy(tx.FromBJJ[:], pkCompL)
  323. fromIdx, err := IdxFromBytes(b[52:58])
  324. if err != nil {
  325. return nil, tracerr.Wrap(err)
  326. }
  327. tx.FromIdx = fromIdx
  328. tx.DepositAmount, err = Float40FromBytes(b[58:63]).BigInt()
  329. if err != nil {
  330. return nil, tracerr.Wrap(err)
  331. }
  332. tx.Amount, err = Float40FromBytes(b[63:68]).BigInt()
  333. if err != nil {
  334. return nil, tracerr.Wrap(err)
  335. }
  336. tx.TokenID, err = TokenIDFromBytes(b[68:72])
  337. if err != nil {
  338. return nil, tracerr.Wrap(err)
  339. }
  340. tx.ToIdx, err = IdxFromBytes(b[72:78])
  341. if err != nil {
  342. return nil, tracerr.Wrap(err)
  343. }
  344. return tx, nil
  345. }
  346. // L1CoordinatorTxFromBytes decodes a L1Tx from []byte
  347. func L1CoordinatorTxFromBytes(b []byte, chainID *big.Int, hermezAddress ethCommon.Address) (*L1Tx,
  348. error) {
  349. if len(b) != RollupConstL1CoordinatorTotalBytes {
  350. return nil, tracerr.Wrap(
  351. fmt.Errorf("Can not parse L1CoordinatorTx bytes, expected length %d, current: %d",
  352. 101, len(b)))
  353. }
  354. tx := &L1Tx{
  355. UserOrigin: false,
  356. }
  357. var err error
  358. v := b[0]
  359. s := b[1:33]
  360. r := b[33:65]
  361. pkCompB := b[65:97]
  362. pkCompL := SwapEndianness(pkCompB)
  363. copy(tx.FromBJJ[:], pkCompL)
  364. tx.TokenID, err = TokenIDFromBytes(b[97:101])
  365. if err != nil {
  366. return nil, tracerr.Wrap(err)
  367. }
  368. tx.Amount = big.NewInt(0)
  369. tx.DepositAmount = big.NewInt(0)
  370. if int(v) > 0 {
  371. // L1CoordinatorTX ETH
  372. // Ethereum adds 27 to v
  373. v = b[0] - byte(27) //nolint:gomnd
  374. var signature []byte
  375. signature = append(signature, r[:]...)
  376. signature = append(signature, s[:]...)
  377. signature = append(signature, v)
  378. accCreationAuth := AccountCreationAuth{
  379. BJJ: tx.FromBJJ,
  380. }
  381. h, err := accCreationAuth.HashToSign(uint16(chainID.Uint64()), hermezAddress)
  382. if err != nil {
  383. return nil, tracerr.Wrap(err)
  384. }
  385. pubKeyBytes, err := ethCrypto.Ecrecover(h, signature)
  386. if err != nil {
  387. return nil, tracerr.Wrap(err)
  388. }
  389. pubKey, err := ethCrypto.UnmarshalPubkey(pubKeyBytes)
  390. if err != nil {
  391. return nil, tracerr.Wrap(err)
  392. }
  393. tx.FromEthAddr = ethCrypto.PubkeyToAddress(*pubKey)
  394. } else {
  395. // L1Coordinator Babyjub
  396. tx.FromEthAddr = RollupConstEthAddressInternalOnly
  397. }
  398. return tx, nil
  399. }