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.

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