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	// L1TxBytesLen is the length of the byte array that represents the L1Tx
 15	L1TxBytesLen = 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
 31	ToForgeL1TxsNum *int64 // toForgeL1TxsNum in which the tx was forged / will be forged
 32	Position        int
 33	UserOrigin      bool // 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 // FromIdx is used by L1Tx/Deposit to indicate the Idx receiver of the L1Tx.LoadAmount (deposit)
 35	FromEthAddr     ethCommon.Address
 36	FromBJJ         *babyjub.PublicKey
 37	ToIdx           Idx // ToIdx is ignored in L1Tx/Deposit, but used in the L1Tx/DepositAndTransfer
 38	TokenID         TokenID
 39	Amount          *big.Int
 40	LoadAmount      *big.Int
 41	EthBlockNum     int64 // Ethereum Block Number in which this L1Tx was added to the queue
 42	Type            TxType
 43	BatchNum        *BatchNum
 44	USD             *float64
 45	LoadAmountUSD   *float64
 46}
 47
 48// NewL1Tx returns the given L1Tx with the TxId & Type parameters calculated
 49// from the L1Tx values
 50func NewL1Tx(l1Tx *L1Tx) (*L1Tx, error) {
 51	// calculate TxType
 52	var txType TxType
 53	if l1Tx.FromIdx == nil {
 54		if l1Tx.ToIdx == Idx(0) {
 55			txType = TxTypeCreateAccountDeposit
 56		} else if l1Tx.ToIdx >= IdxUserThreshold {
 57			txType = TxTypeCreateAccountDepositTransfer
 58		} else {
 59			return l1Tx, fmt.Errorf("Can not determine type of L1Tx, invalid ToIdx value: %d", l1Tx.ToIdx)
 60		}
 61	} else if *l1Tx.FromIdx >= IdxUserThreshold {
 62		if l1Tx.ToIdx == Idx(0) {
 63			txType = TxTypeDeposit
 64		} else if l1Tx.ToIdx == Idx(1) {
 65			txType = TxTypeExit
 66		} else if l1Tx.ToIdx >= IdxUserThreshold {
 67			if l1Tx.LoadAmount.Int64() == int64(0) {
 68				txType = TxTypeForceTransfer
 69			} else {
 70				txType = TxTypeDepositTransfer
 71			}
 72		} else {
 73			return l1Tx, fmt.Errorf("Can not determine type of L1Tx, invalid ToIdx value: %d", l1Tx.ToIdx)
 74		}
 75	} else {
 76		return l1Tx, fmt.Errorf("Can not determine type of L1Tx, invalid FromIdx value: %d", l1Tx.FromIdx)
 77	}
 78
 79	if l1Tx.Type != "" && l1Tx.Type != txType {
 80		return l1Tx, fmt.Errorf("L1Tx.Type: %s, should be: %s", l1Tx.Type, txType)
 81	}
 82	l1Tx.Type = txType
 83
 84	txID, err := l1Tx.CalcTxID()
 85	if err != nil {
 86		return nil, err
 87	}
 88	l1Tx.TxID = *txID
 89
 90	return l1Tx, nil
 91}
 92
 93// CalcTxID calculates the TxId of the L1Tx
 94func (tx *L1Tx) CalcTxID() (*TxID, error) {
 95	var txID TxID
 96	if tx.UserOrigin {
 97		if tx.ToForgeL1TxsNum == nil {
 98			return nil, fmt.Errorf("L1Tx.UserOrigin == true && L1Tx.ToForgeL1TxsNum == nil")
 99		}
100		txID[0] = TxIDPrefixL1UserTx
101		var toForgeL1TxsNumBytes [8]byte
102		binary.BigEndian.PutUint64(toForgeL1TxsNumBytes[:], uint64(*tx.ToForgeL1TxsNum))
103		copy(txID[1:9], toForgeL1TxsNumBytes[:])
104	} else {
105		if tx.BatchNum == nil {
106			return nil, fmt.Errorf("L1Tx.UserOrigin == false && L1Tx.BatchNum == nil")
107		}
108		txID[0] = TxIDPrefixL1CoordTx
109		var batchNumBytes [8]byte
110		binary.BigEndian.PutUint64(batchNumBytes[:], uint64(*tx.BatchNum))
111		copy(txID[1:9], batchNumBytes[:])
112	}
113	var positionBytes [2]byte
114	binary.BigEndian.PutUint16(positionBytes[:], uint16(tx.Position))
115	copy(txID[9:11], positionBytes[:])
116
117	return &txID, nil
118}
119
120// Tx returns a *Tx from the L1Tx
121func (tx *L1Tx) Tx() *Tx {
122	f := new(big.Float).SetInt(tx.Amount)
123	amountFloat, _ := f.Float64()
124	userOrigin := new(bool)
125	*userOrigin = tx.UserOrigin
126	fromEthAddr := new(ethCommon.Address)
127	*fromEthAddr = tx.FromEthAddr
128	toIdx := new(Idx)
129	*toIdx = tx.ToIdx
130	genericTx := &Tx{
131		IsL1:            true,
132		TxID:            tx.TxID,
133		Type:            tx.Type,
134		Position:        tx.Position,
135		FromIdx:         tx.FromIdx,
136		ToIdx:           toIdx,
137		Amount:          tx.Amount,
138		AmountFloat:     amountFloat,
139		TokenID:         tx.TokenID,
140		ToForgeL1TxsNum: tx.ToForgeL1TxsNum,
141		UserOrigin:      userOrigin,
142		FromEthAddr:     fromEthAddr,
143		FromBJJ:         tx.FromBJJ,
144		LoadAmount:      tx.LoadAmount,
145		EthBlockNum:     tx.EthBlockNum,
146		USD:             tx.USD,
147		LoadAmountUSD:   tx.LoadAmountUSD,
148	}
149	if tx.LoadAmount != nil {
150		lf := new(big.Float).SetInt(tx.LoadAmount)
151		loadAmountFloat, _ := lf.Float64()
152		genericTx.LoadAmountFloat = &loadAmountFloat
153	}
154	return genericTx
155}
156
157// Bytes encodes a L1Tx into []byte
158func (tx *L1Tx) Bytes() ([]byte, error) {
159	var b [L1TxBytesLen]byte
160	copy(b[0:20], tx.FromEthAddr.Bytes())
161	pkComp := tx.FromBJJ.Compress()
162	copy(b[20:52], pkComp[:])
163	fromIdxBytes, err := tx.FromIdx.Bytes()
164	if err != nil {
165		return nil, err
166	}
167	copy(b[52:58], fromIdxBytes[:])
168	loadAmountFloat16, err := NewFloat16(tx.LoadAmount)
169	if err != nil {
170		return nil, err
171	}
172	copy(b[58:60], loadAmountFloat16.Bytes())
173	amountFloat16, err := NewFloat16(tx.Amount)
174	if err != nil {
175		return nil, err
176	}
177	copy(b[60:62], amountFloat16.Bytes())
178	copy(b[62:66], tx.TokenID.Bytes())
179	toIdxBytes, err := tx.ToIdx.Bytes()
180	if err != nil {
181		return nil, err
182	}
183	copy(b[66:72], toIdxBytes[:])
184	return b[:], nil
185}
186
187// BytesCoordinatorTx encodes a L1CoordinatorTx into []byte
188func (tx *L1Tx) BytesCoordinatorTx(compressedSignatureBytes []byte) ([]byte, error) {
189	var b [L1CoordinatorTxBytesLen]byte
190	v := compressedSignatureBytes[64]
191	s := compressedSignatureBytes[32:64]
192	r := compressedSignatureBytes[0:32]
193	b[0] = v
194	copy(b[1:33], s)
195	copy(b[33:65], r)
196	pkComp := tx.FromBJJ.Compress()
197	copy(b[65:97], pkComp[:])
198	copy(b[97:101], tx.TokenID.Bytes())
199	return b[:], nil
200}
201
202// L1TxFromBytes decodes a L1Tx from []byte
203func L1TxFromBytes(b []byte) (*L1Tx, error) {
204	if len(b) != L1TxBytesLen {
205		return nil, fmt.Errorf("Can not parse L1Tx bytes, expected length %d, current: %d", 68, len(b))
206	}
207
208	tx := &L1Tx{}
209	var err error
210	tx.FromEthAddr = ethCommon.BytesToAddress(b[0:20])
211	pkCompB := b[20:52]
212	var pkComp babyjub.PublicKeyComp
213	copy(pkComp[:], pkCompB)
214	tx.FromBJJ, err = pkComp.Decompress()
215	if err != nil {
216		return nil, err
217	}
218	fromIdx, err := IdxFromBytes(b[52:58])
219	if err != nil {
220		return nil, err
221	}
222	if fromIdx != 0 {
223		tx.FromIdx = new(Idx)
224		*tx.FromIdx = fromIdx
225	}
226	tx.LoadAmount = Float16FromBytes(b[58:60]).BigInt()
227	tx.Amount = Float16FromBytes(b[60:62]).BigInt()
228	tx.TokenID, err = TokenIDFromBytes(b[62:66])
229	if err != nil {
230		return nil, err
231	}
232	tx.ToIdx, err = IdxFromBytes(b[66:72])
233	if err != nil {
234		return nil, err
235	}
236
237	return tx, nil
238}
239
240// L1TxFromCoordinatorBytes decodes a L1Tx from []byte
241func L1TxFromCoordinatorBytes(b []byte) (*L1Tx, error) {
242	if len(b) != L1CoordinatorTxBytesLen {
243		return nil, fmt.Errorf("Can not parse L1CoordinatorTx bytes, expected length %d, current: %d", 101, len(b))
244	}
245
246	bytesMessage1 := []byte("\x19Ethereum Signed Message:\n98")
247	bytesMessage2 := []byte("I authorize this babyjubjub key for hermez rollup account creation")
248
249	tx := &L1Tx{}
250	var err error
251	// Ethereum adds 27 to v
252	v := b[0] - byte(27) //nolint:gomnd
253	s := b[1:33]
254	r := b[33:65]
255
256	pkCompB := b[65:97]
257	var pkComp babyjub.PublicKeyComp
258	copy(pkComp[:], pkCompB)
259	tx.FromBJJ, err = pkComp.Decompress()
260	if err != nil {
261		return nil, err
262	}
263	tx.TokenID, err = TokenIDFromBytes(b[97:101])
264	if err != nil {
265		return nil, err
266	}
267
268	var data []byte
269	data = append(data, bytesMessage1...)
270	data = append(data, bytesMessage2...)
271	data = append(data, pkCompB...)
272	var signature []byte
273	signature = append(signature, r[:]...)
274	signature = append(signature, s[:]...)
275	signature = append(signature, v)
276	hash := crypto.Keccak256(data)
277	pubKeyBytes, err := crypto.Ecrecover(hash, signature)
278	if err != nil {
279		return nil, err
280	}
281	pubKey, err := crypto.UnmarshalPubkey(pubKeyBytes)
282	if err != nil {
283		return nil, err
284	}
285	tx.FromEthAddr = crypto.PubkeyToAddress(*pubKey)
286	return tx, nil
287}