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.

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