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.

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