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.

422 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
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. const (
  12. // L1UserTxBytesLen is the length of the byte array that represents the L1Tx
  13. L1UserTxBytesLen = 72
  14. // L1CoordinatorTxBytesLen is the length of the byte array that represents the L1CoordinatorTx
  15. L1CoordinatorTxBytesLen = 101
  16. )
  17. // L1Tx is a struct that represents a L1 tx
  18. type L1Tx struct {
  19. // Stored in DB: mandatory fileds
  20. // TxID (12 bytes) for L1Tx is:
  21. // bytes: | 1 | 8 | 2 | 1 |
  22. // values: | type | ToForgeL1TxsNum | Position | 0 (padding) |
  23. // where type:
  24. // - L1UserTx: 0
  25. // - L1CoordinatorTx: 1
  26. TxID TxID `meddler:"id"`
  27. ToForgeL1TxsNum *int64 `meddler:"to_forge_l1_txs_num"` // toForgeL1TxsNum in which the tx was forged / will be forged
  28. Position int `meddler:"position"`
  29. 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
  30. FromIdx Idx `meddler:"from_idx,zeroisnull"` // FromIdx is used by L1Tx/Deposit to indicate the Idx receiver of the L1Tx.DepositAmount (deposit)
  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 Idx `meddler:"to_idx"` // ToIdx is ignored in L1Tx/Deposit, but used in the L1Tx/DepositAndTransfer
  35. TokenID TokenID `meddler:"token_id"`
  36. Amount *big.Int `meddler:"amount,bigint"`
  37. // EffectiveAmount only applies to L1UserTx.
  38. EffectiveAmount *big.Int `meddler:"effective_amount,bigintnull"`
  39. DepositAmount *big.Int `meddler:"deposit_amount,bigint"`
  40. // EffectiveDepositAmount only applies to L1UserTx.
  41. EffectiveDepositAmount *big.Int `meddler:"effective_deposit_amount,bigintnull"`
  42. EthBlockNum int64 `meddler:"eth_block_num"` // Ethereum Block Number in which this L1Tx was added to the queue
  43. Type TxType `meddler:"type"`
  44. BatchNum *BatchNum `meddler:"batch_num"`
  45. }
  46. // NewL1Tx returns the given L1Tx with the TxId & Type parameters calculated
  47. // from the L1Tx values
  48. func NewL1Tx(tx *L1Tx) (*L1Tx, error) {
  49. txTypeOld := tx.Type
  50. if err := tx.SetType(); err != nil {
  51. return nil, tracerr.Wrap(err)
  52. }
  53. // If original Type doesn't match the correct one, return error
  54. if txTypeOld != "" && txTypeOld != tx.Type {
  55. return nil, tracerr.Wrap(fmt.Errorf("L1Tx.Type: %s, should be: %s",
  56. tx.Type, txTypeOld))
  57. }
  58. txIDOld := tx.TxID
  59. if err := tx.SetID(); err != nil {
  60. return nil, tracerr.Wrap(err)
  61. }
  62. // If original TxID doesn't match the correct one, return error
  63. if txIDOld != (TxID{}) && txIDOld != tx.TxID {
  64. return tx, tracerr.Wrap(fmt.Errorf("L1Tx.TxID: %s, should be: %s",
  65. tx.TxID.String(), txIDOld.String()))
  66. }
  67. return tx, nil
  68. }
  69. // SetType sets the type of the transaction
  70. func (tx *L1Tx) SetType() error {
  71. if tx.FromIdx == 0 {
  72. if tx.ToIdx == Idx(0) {
  73. tx.Type = TxTypeCreateAccountDeposit
  74. } else if tx.ToIdx >= IdxUserThreshold {
  75. tx.Type = TxTypeCreateAccountDepositTransfer
  76. } else {
  77. return tracerr.Wrap(fmt.Errorf(
  78. "Can not determine type of L1Tx, invalid ToIdx value: %d", tx.ToIdx))
  79. }
  80. } else if tx.FromIdx >= IdxUserThreshold {
  81. if tx.ToIdx == Idx(0) {
  82. tx.Type = TxTypeDeposit
  83. } else if tx.ToIdx == Idx(1) {
  84. tx.Type = TxTypeForceExit
  85. } else if tx.ToIdx >= IdxUserThreshold {
  86. if tx.DepositAmount.Int64() == int64(0) {
  87. tx.Type = TxTypeForceTransfer
  88. } else {
  89. tx.Type = TxTypeDepositTransfer
  90. }
  91. } else {
  92. return tracerr.Wrap(fmt.Errorf(
  93. "Can not determine type of L1Tx, invalid ToIdx value: %d", tx.ToIdx))
  94. }
  95. } else {
  96. return tracerr.Wrap(fmt.Errorf(
  97. "Can not determine type of L1Tx, invalid FromIdx value: %d", tx.FromIdx))
  98. }
  99. return nil
  100. }
  101. // SetID sets the ID of the transaction. For L1UserTx uses (ToForgeL1TxsNum,
  102. // Position), for L1CoordinatorTx uses (BatchNum, Position).
  103. func (tx *L1Tx) SetID() error {
  104. var b []byte
  105. if tx.UserOrigin {
  106. if tx.ToForgeL1TxsNum == nil {
  107. return tracerr.Wrap(fmt.Errorf("L1Tx.UserOrigin == true && L1Tx.ToForgeL1TxsNum == nil"))
  108. }
  109. tx.TxID[0] = TxIDPrefixL1UserTx
  110. var toForgeL1TxsNumBytes [8]byte
  111. binary.BigEndian.PutUint64(toForgeL1TxsNumBytes[:], uint64(*tx.ToForgeL1TxsNum))
  112. b = append(b, toForgeL1TxsNumBytes[:]...)
  113. } else {
  114. if tx.BatchNum == nil {
  115. return tracerr.Wrap(fmt.Errorf("L1Tx.UserOrigin == false && L1Tx.BatchNum == nil"))
  116. }
  117. tx.TxID[0] = TxIDPrefixL1CoordTx
  118. var batchNumBytes [8]byte
  119. binary.BigEndian.PutUint64(batchNumBytes[:], uint64(*tx.BatchNum))
  120. b = append(b, batchNumBytes[:]...)
  121. }
  122. var positionBytes [2]byte
  123. binary.BigEndian.PutUint16(positionBytes[:], uint16(tx.Position))
  124. b = append(b, positionBytes[:]...)
  125. // calculate hash
  126. h := ethCrypto.Keccak256Hash(b).Bytes()
  127. copy(tx.TxID[1:], h)
  128. return nil
  129. }
  130. // Tx returns a *Tx from the L1Tx
  131. func (tx L1Tx) Tx() Tx {
  132. f := new(big.Float).SetInt(tx.EffectiveAmount)
  133. amountFloat, _ := f.Float64()
  134. userOrigin := new(bool)
  135. *userOrigin = tx.UserOrigin
  136. genericTx := Tx{
  137. IsL1: true,
  138. TxID: tx.TxID,
  139. Type: tx.Type,
  140. Position: tx.Position,
  141. FromIdx: tx.FromIdx,
  142. ToIdx: tx.ToIdx,
  143. Amount: tx.EffectiveAmount,
  144. AmountFloat: amountFloat,
  145. TokenID: tx.TokenID,
  146. ToForgeL1TxsNum: tx.ToForgeL1TxsNum,
  147. UserOrigin: userOrigin,
  148. FromEthAddr: tx.FromEthAddr,
  149. FromBJJ: tx.FromBJJ,
  150. DepositAmount: tx.EffectiveDepositAmount,
  151. EthBlockNum: tx.EthBlockNum,
  152. }
  153. if tx.DepositAmount != nil {
  154. lf := new(big.Float).SetInt(tx.DepositAmount)
  155. depositAmountFloat, _ := lf.Float64()
  156. genericTx.DepositAmountFloat = &depositAmountFloat
  157. }
  158. return genericTx
  159. }
  160. // TxCompressedData spec:
  161. // [ 1 bits ] empty (toBJJSign) // 1 byte
  162. // [ 8 bits ] empty (userFee) // 1 byte
  163. // [ 40 bits ] empty (nonce) // 5 bytes
  164. // [ 32 bits ] tokenID // 4 bytes
  165. // [ 16 bits ] amountFloat16 // 2 bytes
  166. // [ 48 bits ] toIdx // 6 bytes
  167. // [ 48 bits ] fromIdx // 6 bytes
  168. // [ 16 bits ] chainId // 2 bytes
  169. // [ 32 bits ] empty (signatureConstant) // 4 bytes
  170. // Total bits compressed data: 241 bits // 31 bytes in *big.Int representation
  171. func (tx L1Tx) TxCompressedData(chainID uint16) (*big.Int, error) {
  172. amountFloat16, err := NewFloat16(tx.Amount)
  173. if err != nil {
  174. return nil, tracerr.Wrap(err)
  175. }
  176. var b [31]byte
  177. // b[0:7] empty: no ToBJJSign, no fee, no nonce
  178. copy(b[7:11], tx.TokenID.Bytes())
  179. copy(b[11:13], amountFloat16.Bytes())
  180. toIdxBytes, err := tx.ToIdx.Bytes()
  181. if err != nil {
  182. return nil, tracerr.Wrap(err)
  183. }
  184. copy(b[13:19], toIdxBytes[:])
  185. fromIdxBytes, err := tx.FromIdx.Bytes()
  186. if err != nil {
  187. return nil, tracerr.Wrap(err)
  188. }
  189. copy(b[19:25], fromIdxBytes[:])
  190. binary.BigEndian.PutUint16(b[25:27], chainID)
  191. copy(b[27:31], SignatureConstantBytes[:])
  192. bi := new(big.Int).SetBytes(b[:])
  193. return bi, nil
  194. }
  195. // BytesDataAvailability encodes a L1Tx into []byte for the Data Availability
  196. // [ fromIdx | toIdx | amountFloat16 | Fee ]
  197. func (tx *L1Tx) BytesDataAvailability(nLevels uint32) ([]byte, error) {
  198. idxLen := nLevels / 8 //nolint:gomnd
  199. b := make([]byte, ((nLevels*2)+16+8)/8) //nolint:gomnd
  200. fromIdxBytes, err := tx.FromIdx.Bytes()
  201. if err != nil {
  202. return nil, tracerr.Wrap(err)
  203. }
  204. copy(b[0:idxLen], fromIdxBytes[6-idxLen:])
  205. toIdxBytes, err := tx.ToIdx.Bytes()
  206. if err != nil {
  207. return nil, tracerr.Wrap(err)
  208. }
  209. copy(b[idxLen:idxLen*2], toIdxBytes[6-idxLen:])
  210. if tx.EffectiveAmount != nil {
  211. amountFloat16, err := NewFloat16(tx.EffectiveAmount)
  212. if err != nil {
  213. return nil, tracerr.Wrap(err)
  214. }
  215. copy(b[idxLen*2:idxLen*2+2], amountFloat16.Bytes())
  216. }
  217. // fee = 0 (as is L1Tx) b[10:11]
  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+2]
  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 = Float16FromBytes(amountBytes).BigInt()
  238. return &l1tx, nil
  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 [L1UserTxBytesLen]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. depositAmountFloat16, err := NewFloat16(tx.DepositAmount)
  258. if err != nil {
  259. return nil, tracerr.Wrap(err)
  260. }
  261. copy(b[58:60], depositAmountFloat16.Bytes())
  262. amountFloat16, err := NewFloat16(tx.Amount)
  263. if err != nil {
  264. return nil, tracerr.Wrap(err)
  265. }
  266. copy(b[60:62], amountFloat16.Bytes())
  267. copy(b[62:66], tx.TokenID.Bytes())
  268. toIdxBytes, err := tx.ToIdx.Bytes()
  269. if err != nil {
  270. return nil, tracerr.Wrap(err)
  271. }
  272. copy(b[66:72], 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 [L1CoordinatorTxBytesLen]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) != L1UserTxBytesLen {
  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 = Float16FromBytes(b[58:60]).BigInt()
  319. tx.Amount = Float16FromBytes(b[60:62]).BigInt()
  320. tx.TokenID, err = TokenIDFromBytes(b[62:66])
  321. if err != nil {
  322. return nil, tracerr.Wrap(err)
  323. }
  324. tx.ToIdx, err = IdxFromBytes(b[66:72])
  325. if err != nil {
  326. return nil, tracerr.Wrap(err)
  327. }
  328. return tx, nil
  329. }
  330. func signHash(data []byte) []byte {
  331. msg := fmt.Sprintf("\x19Ethereum Signed Message:\n%d%s", len(data), data)
  332. return ethCrypto.Keccak256([]byte(msg))
  333. }
  334. // L1CoordinatorTxFromBytes decodes a L1Tx from []byte
  335. func L1CoordinatorTxFromBytes(b []byte, chainID *big.Int, hermezAddress ethCommon.Address) (*L1Tx, error) {
  336. if len(b) != L1CoordinatorTxBytesLen {
  337. return nil, tracerr.Wrap(fmt.Errorf("Can not parse L1CoordinatorTx bytes, expected length %d, current: %d", 101, len(b)))
  338. }
  339. bytesMessage := []byte("I authorize this babyjubjub key for hermez rollup account creation")
  340. tx := &L1Tx{
  341. UserOrigin: false,
  342. }
  343. var err error
  344. v := b[0]
  345. s := b[1:33]
  346. r := b[33:65]
  347. pkCompB := b[65:97]
  348. pkCompL := SwapEndianness(pkCompB)
  349. copy(tx.FromBJJ[:], pkCompL)
  350. tx.TokenID, err = TokenIDFromBytes(b[97:101])
  351. if err != nil {
  352. return nil, tracerr.Wrap(err)
  353. }
  354. tx.Amount = big.NewInt(0)
  355. tx.DepositAmount = big.NewInt(0)
  356. if int(v) > 0 {
  357. // L1CoordinatorTX ETH
  358. // Ethereum adds 27 to v
  359. v = b[0] - byte(27) //nolint:gomnd
  360. chainIDBytes := ethCommon.LeftPadBytes(chainID.Bytes(), 2)
  361. var data []byte
  362. data = append(data, bytesMessage...)
  363. data = append(data, pkCompB...)
  364. data = append(data, chainIDBytes[:]...)
  365. data = append(data, hermezAddress.Bytes()...)
  366. var signature []byte
  367. signature = append(signature, r[:]...)
  368. signature = append(signature, s[:]...)
  369. signature = append(signature, v)
  370. hash := signHash(data)
  371. pubKeyBytes, err := ethCrypto.Ecrecover(hash, signature)
  372. if err != nil {
  373. return nil, tracerr.Wrap(err)
  374. }
  375. pubKey, err := ethCrypto.UnmarshalPubkey(pubKeyBytes)
  376. if err != nil {
  377. return nil, tracerr.Wrap(err)
  378. }
  379. tx.FromEthAddr = ethCrypto.PubkeyToAddress(*pubKey)
  380. } else {
  381. // L1Coordinator Babyjub
  382. tx.FromEthAddr = RollupConstEthAddressInternalOnly
  383. }
  384. return tx, nil
  385. }