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.

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