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