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.

413 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. 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. if tx.UserOrigin {
  105. if tx.ToForgeL1TxsNum == nil {
  106. return tracerr.Wrap(fmt.Errorf("L1Tx.UserOrigin == true && L1Tx.ToForgeL1TxsNum == nil"))
  107. }
  108. tx.TxID[0] = TxIDPrefixL1UserTx
  109. var toForgeL1TxsNumBytes [8]byte
  110. binary.BigEndian.PutUint64(toForgeL1TxsNumBytes[:], uint64(*tx.ToForgeL1TxsNum))
  111. copy(tx.TxID[1:9], toForgeL1TxsNumBytes[:])
  112. } else {
  113. if tx.BatchNum == nil {
  114. return tracerr.Wrap(fmt.Errorf("L1Tx.UserOrigin == false && L1Tx.BatchNum == nil"))
  115. }
  116. tx.TxID[0] = TxIDPrefixL1CoordTx
  117. var batchNumBytes [8]byte
  118. binary.BigEndian.PutUint64(batchNumBytes[:], uint64(*tx.BatchNum))
  119. copy(tx.TxID[1:9], batchNumBytes[:])
  120. }
  121. var positionBytes [2]byte
  122. binary.BigEndian.PutUint16(positionBytes[:], uint16(tx.Position))
  123. copy(tx.TxID[9:11], positionBytes[:])
  124. return nil
  125. }
  126. // Tx returns a *Tx from the L1Tx
  127. func (tx L1Tx) Tx() Tx {
  128. f := new(big.Float).SetInt(tx.EffectiveAmount)
  129. amountFloat, _ := f.Float64()
  130. userOrigin := new(bool)
  131. *userOrigin = tx.UserOrigin
  132. genericTx := Tx{
  133. IsL1: true,
  134. TxID: tx.TxID,
  135. Type: tx.Type,
  136. Position: tx.Position,
  137. FromIdx: tx.FromIdx,
  138. ToIdx: tx.ToIdx,
  139. Amount: tx.EffectiveAmount,
  140. AmountFloat: amountFloat,
  141. TokenID: tx.TokenID,
  142. ToForgeL1TxsNum: tx.ToForgeL1TxsNum,
  143. UserOrigin: userOrigin,
  144. FromEthAddr: tx.FromEthAddr,
  145. FromBJJ: tx.FromBJJ,
  146. DepositAmount: tx.EffectiveDepositAmount,
  147. EthBlockNum: tx.EthBlockNum,
  148. }
  149. if tx.DepositAmount != nil {
  150. lf := new(big.Float).SetInt(tx.DepositAmount)
  151. depositAmountFloat, _ := lf.Float64()
  152. genericTx.DepositAmountFloat = &depositAmountFloat
  153. }
  154. return genericTx
  155. }
  156. // TxCompressedData spec:
  157. // [ 1 bits ] empty (toBJJSign) // 1 byte
  158. // [ 8 bits ] empty (userFee) // 1 byte
  159. // [ 40 bits ] empty (nonce) // 5 bytes
  160. // [ 32 bits ] tokenID // 4 bytes
  161. // [ 16 bits ] amountFloat16 // 2 bytes
  162. // [ 48 bits ] toIdx // 6 bytes
  163. // [ 48 bits ] fromIdx // 6 bytes
  164. // [ 16 bits ] chainId // 2 bytes
  165. // [ 32 bits ] empty (signatureConstant) // 4 bytes
  166. // Total bits compressed data: 241 bits // 31 bytes in *big.Int representation
  167. func (tx L1Tx) TxCompressedData(chainID uint16) (*big.Int, error) {
  168. amountFloat16, err := NewFloat16(tx.Amount)
  169. if err != nil {
  170. return nil, tracerr.Wrap(err)
  171. }
  172. var b [31]byte
  173. // b[0:7] empty: no ToBJJSign, no fee, no nonce
  174. copy(b[7:11], tx.TokenID.Bytes())
  175. copy(b[11:13], amountFloat16.Bytes())
  176. toIdxBytes, err := tx.ToIdx.Bytes()
  177. if err != nil {
  178. return nil, tracerr.Wrap(err)
  179. }
  180. copy(b[13:19], toIdxBytes[:])
  181. fromIdxBytes, err := tx.FromIdx.Bytes()
  182. if err != nil {
  183. return nil, tracerr.Wrap(err)
  184. }
  185. copy(b[19:25], fromIdxBytes[:])
  186. binary.BigEndian.PutUint16(b[25:27], chainID)
  187. copy(b[27:31], 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. func (tx *L1Tx) BytesDataAvailability(nLevels uint32) ([]byte, error) {
  193. idxLen := nLevels / 8 //nolint:gomnd
  194. b := make([]byte, ((nLevels*2)+16+8)/8) //nolint:gomnd
  195. fromIdxBytes, err := tx.FromIdx.Bytes()
  196. if err != nil {
  197. return nil, tracerr.Wrap(err)
  198. }
  199. copy(b[0:idxLen], fromIdxBytes[6-idxLen:])
  200. toIdxBytes, err := tx.ToIdx.Bytes()
  201. if err != nil {
  202. return nil, tracerr.Wrap(err)
  203. }
  204. copy(b[idxLen:idxLen*2], toIdxBytes[6-idxLen:])
  205. if tx.EffectiveAmount != nil {
  206. amountFloat16, err := NewFloat16(tx.EffectiveAmount)
  207. if err != nil {
  208. return nil, tracerr.Wrap(err)
  209. }
  210. copy(b[idxLen*2:idxLen*2+2], amountFloat16.Bytes())
  211. }
  212. // fee = 0 (as is L1Tx) b[10:11]
  213. return b[:], nil
  214. }
  215. // L1TxFromDataAvailability decodes a L1Tx from []byte (Data Availability)
  216. func L1TxFromDataAvailability(b []byte, nLevels uint32) (*L1Tx, error) {
  217. idxLen := nLevels / 8 //nolint:gomnd
  218. fromIdxBytes := b[0:idxLen]
  219. toIdxBytes := b[idxLen : idxLen*2]
  220. amountBytes := b[idxLen*2 : idxLen*2+2]
  221. l1tx := L1Tx{}
  222. fromIdx, err := IdxFromBytes(ethCommon.LeftPadBytes(fromIdxBytes, 6))
  223. if err != nil {
  224. return nil, tracerr.Wrap(err)
  225. }
  226. l1tx.FromIdx = fromIdx
  227. toIdx, err := IdxFromBytes(ethCommon.LeftPadBytes(toIdxBytes, 6))
  228. if err != nil {
  229. return nil, tracerr.Wrap(err)
  230. }
  231. l1tx.ToIdx = toIdx
  232. l1tx.EffectiveAmount = Float16FromBytes(amountBytes).BigInt()
  233. return &l1tx, nil
  234. }
  235. // BytesGeneric returns the generic representation of a L1Tx. This method is
  236. // used to compute the []byte representation of a L1UserTx, and also to compute
  237. // the L1TxData for the ZKInputs (at the HashGlobalInputs), using this method
  238. // for L1CoordinatorTxs & L1UserTxs (for the ZKInputs case).
  239. func (tx *L1Tx) BytesGeneric() ([]byte, error) {
  240. var b [L1UserTxBytesLen]byte
  241. copy(b[0:20], tx.FromEthAddr.Bytes())
  242. if tx.FromBJJ != EmptyBJJComp {
  243. pkCompL := tx.FromBJJ
  244. pkCompB := SwapEndianness(pkCompL[:])
  245. copy(b[20:52], pkCompB[:])
  246. }
  247. fromIdxBytes, err := tx.FromIdx.Bytes()
  248. if err != nil {
  249. return nil, tracerr.Wrap(err)
  250. }
  251. copy(b[52:58], fromIdxBytes[:])
  252. depositAmountFloat16, err := NewFloat16(tx.DepositAmount)
  253. if err != nil {
  254. return nil, tracerr.Wrap(err)
  255. }
  256. copy(b[58:60], depositAmountFloat16.Bytes())
  257. amountFloat16, err := NewFloat16(tx.Amount)
  258. if err != nil {
  259. return nil, tracerr.Wrap(err)
  260. }
  261. copy(b[60:62], amountFloat16.Bytes())
  262. copy(b[62:66], tx.TokenID.Bytes())
  263. toIdxBytes, err := tx.ToIdx.Bytes()
  264. if err != nil {
  265. return nil, tracerr.Wrap(err)
  266. }
  267. copy(b[66:72], toIdxBytes[:])
  268. return b[:], nil
  269. }
  270. // BytesUser encodes a L1UserTx into []byte
  271. func (tx *L1Tx) BytesUser() ([]byte, error) {
  272. if !tx.UserOrigin {
  273. return nil, tracerr.Wrap(fmt.Errorf("Can not calculate BytesUser() for a L1CoordinatorTx"))
  274. }
  275. return tx.BytesGeneric()
  276. }
  277. // BytesCoordinatorTx encodes a L1CoordinatorTx into []byte
  278. func (tx *L1Tx) BytesCoordinatorTx(compressedSignatureBytes []byte) ([]byte, error) {
  279. if tx.UserOrigin {
  280. return nil, tracerr.Wrap(fmt.Errorf("Can not calculate BytesCoordinatorTx() for a L1UserTx"))
  281. }
  282. var b [L1CoordinatorTxBytesLen]byte
  283. v := compressedSignatureBytes[64]
  284. s := compressedSignatureBytes[32:64]
  285. r := compressedSignatureBytes[0:32]
  286. b[0] = v
  287. copy(b[1:33], s)
  288. copy(b[33:65], r)
  289. pkCompL := tx.FromBJJ
  290. pkCompB := SwapEndianness(pkCompL[:])
  291. copy(b[65:97], pkCompB[:])
  292. copy(b[97:101], tx.TokenID.Bytes())
  293. return b[:], nil
  294. }
  295. // L1UserTxFromBytes decodes a L1Tx from []byte
  296. func L1UserTxFromBytes(b []byte) (*L1Tx, error) {
  297. if len(b) != L1UserTxBytesLen {
  298. return nil, tracerr.Wrap(fmt.Errorf("Can not parse L1Tx bytes, expected length %d, current: %d", 68, len(b)))
  299. }
  300. tx := &L1Tx{
  301. UserOrigin: true,
  302. }
  303. var err error
  304. tx.FromEthAddr = ethCommon.BytesToAddress(b[0:20])
  305. pkCompB := b[20:52]
  306. pkCompL := SwapEndianness(pkCompB)
  307. copy(tx.FromBJJ[:], pkCompL)
  308. fromIdx, err := IdxFromBytes(b[52:58])
  309. if err != nil {
  310. return nil, tracerr.Wrap(err)
  311. }
  312. tx.FromIdx = fromIdx
  313. tx.DepositAmount = Float16FromBytes(b[58:60]).BigInt()
  314. tx.Amount = Float16FromBytes(b[60:62]).BigInt()
  315. tx.TokenID, err = TokenIDFromBytes(b[62:66])
  316. if err != nil {
  317. return nil, tracerr.Wrap(err)
  318. }
  319. tx.ToIdx, err = IdxFromBytes(b[66:72])
  320. if err != nil {
  321. return nil, tracerr.Wrap(err)
  322. }
  323. return tx, nil
  324. }
  325. func signHash(data []byte) []byte {
  326. msg := fmt.Sprintf("\x19Ethereum Signed Message:\n%d%s", len(data), data)
  327. return crypto.Keccak256([]byte(msg))
  328. }
  329. // L1CoordinatorTxFromBytes decodes a L1Tx from []byte
  330. func L1CoordinatorTxFromBytes(b []byte, chainID *big.Int, hermezAddress ethCommon.Address) (*L1Tx, error) {
  331. if len(b) != L1CoordinatorTxBytesLen {
  332. return nil, tracerr.Wrap(fmt.Errorf("Can not parse L1CoordinatorTx bytes, expected length %d, current: %d", 101, len(b)))
  333. }
  334. bytesMessage := []byte("I authorize this babyjubjub key for hermez rollup account creation")
  335. tx := &L1Tx{
  336. UserOrigin: false,
  337. }
  338. var err error
  339. v := b[0]
  340. s := b[1:33]
  341. r := b[33:65]
  342. pkCompB := b[65:97]
  343. pkCompL := SwapEndianness(pkCompB)
  344. copy(tx.FromBJJ[:], pkCompL)
  345. tx.TokenID, err = TokenIDFromBytes(b[97:101])
  346. if err != nil {
  347. return nil, tracerr.Wrap(err)
  348. }
  349. tx.Amount = big.NewInt(0)
  350. tx.DepositAmount = big.NewInt(0)
  351. if int(v) > 0 {
  352. // L1CoordinatorTX ETH
  353. // Ethereum adds 27 to v
  354. v = b[0] - byte(27) //nolint:gomnd
  355. chainIDBytes := ethCommon.LeftPadBytes(chainID.Bytes(), 2)
  356. var data []byte
  357. data = append(data, bytesMessage...)
  358. data = append(data, pkCompB...)
  359. data = append(data, chainIDBytes[:]...)
  360. data = append(data, hermezAddress.Bytes()...)
  361. var signature []byte
  362. signature = append(signature, r[:]...)
  363. signature = append(signature, s[:]...)
  364. signature = append(signature, v)
  365. hash := signHash(data)
  366. pubKeyBytes, err := crypto.Ecrecover(hash, signature)
  367. if err != nil {
  368. return nil, tracerr.Wrap(err)
  369. }
  370. pubKey, err := crypto.UnmarshalPubkey(pubKeyBytes)
  371. if err != nil {
  372. return nil, tracerr.Wrap(err)
  373. }
  374. tx.FromEthAddr = crypto.PubkeyToAddress(*pubKey)
  375. } else {
  376. // L1Coordinator Babyjub
  377. tx.FromEthAddr = RollupConstEthAddressInternalOnly
  378. }
  379. return tx, nil
  380. }