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