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
 93func (l1Tx *L1Tx) CalcTxID() (*TxID, error) {
 94	var txID TxID
 95	if l1Tx.UserOrigin {
 96		if l1Tx.ToForgeL1TxsNum == nil {
 97			return nil, fmt.Errorf("L1Tx.UserOrigin == true && L1Tx.ToForgeL1TxsNum == nil")
 98		}
 99		txID[0] = TxIDPrefixL1UserTx
100		var toForgeL1TxsNumBytes [8]byte
101		binary.BigEndian.PutUint64(toForgeL1TxsNumBytes[:], uint64(*l1Tx.ToForgeL1TxsNum))
102		copy(txID[1:9], toForgeL1TxsNumBytes[:])
103	} else {
104		if l1Tx.BatchNum == nil {
105			return nil, fmt.Errorf("L1Tx.UserOrigin == false && L1Tx.BatchNum == nil")
106		}
107		txID[0] = TxIDPrefixL1CoordTx
108		var batchNumBytes [8]byte
109		binary.BigEndian.PutUint64(batchNumBytes[:], uint64(*l1Tx.BatchNum))
110		copy(txID[1:9], batchNumBytes[:])
111	}
112	var positionBytes [2]byte
113	binary.BigEndian.PutUint16(positionBytes[:], uint16(l1Tx.Position))
114	copy(txID[9:11], positionBytes[:])
115
116	return &txID, nil
117}
118
119// Tx returns a *Tx from the L1Tx
120func (tx *L1Tx) Tx() *Tx {
121	f := new(big.Float).SetInt(tx.Amount)
122	amountFloat, _ := f.Float64()
123	userOrigin := new(bool)
124	*userOrigin = tx.UserOrigin
125	fromEthAddr := new(ethCommon.Address)
126	*fromEthAddr = tx.FromEthAddr
127	toIdx := new(Idx)
128	*toIdx = tx.ToIdx
129	genericTx := &Tx{
130		IsL1:            true,
131		TxID:            tx.TxID,
132		Type:            tx.Type,
133		Position:        tx.Position,
134		FromIdx:         tx.FromIdx,
135		ToIdx:           toIdx,
136		Amount:          tx.Amount,
137		AmountFloat:     amountFloat,
138		TokenID:         tx.TokenID,
139		ToForgeL1TxsNum: tx.ToForgeL1TxsNum,
140		UserOrigin:      userOrigin,
141		FromEthAddr:     fromEthAddr,
142		FromBJJ:         tx.FromBJJ,
143		LoadAmount:      tx.LoadAmount,
144		EthBlockNum:     tx.EthBlockNum,
145		USD:             tx.USD,
146		LoadAmountUSD:   tx.LoadAmountUSD,
147	}
148	if tx.LoadAmount != nil {
149		lf := new(big.Float).SetInt(tx.LoadAmount)
150		loadAmountFloat, _ := lf.Float64()
151		genericTx.LoadAmountFloat = &loadAmountFloat
152	}
153	return genericTx
154}
155
156// Bytes encodes a L1Tx into []byte
157func (tx *L1Tx) Bytes() ([]byte, error) {
158	var b [L1TxBytesLen]byte
159	copy(b[0:20], tx.FromEthAddr.Bytes())
160	pkComp := tx.FromBJJ.Compress()
161	copy(b[20:52], pkComp[:])
162	fromIdxBytes, err := tx.FromIdx.Bytes()
163	if err != nil {
164		return nil, err
165	}
166	copy(b[52:58], fromIdxBytes[:])
167	loadAmountFloat16, err := NewFloat16(tx.LoadAmount)
168	if err != nil {
169		return nil, err
170	}
171	copy(b[58:60], loadAmountFloat16.Bytes())
172	amountFloat16, err := NewFloat16(tx.Amount)
173	if err != nil {
174		return nil, err
175	}
176	copy(b[60:62], amountFloat16.Bytes())
177	copy(b[62:66], tx.TokenID.Bytes())
178	toIdxBytes, err := tx.ToIdx.Bytes()
179	if err != nil {
180		return nil, err
181	}
182	copy(b[66:72], toIdxBytes[:])
183	return b[:], nil
184}
185
186// BytesCoordinatorTx encodes a L1CoordinatorTx into []byte
187func (tx *L1Tx) BytesCoordinatorTx(compressedSignatureBytes []byte) ([]byte, error) {
188	var b [L1CoordinatorTxBytesLen]byte
189	v := compressedSignatureBytes[64]
190	s := compressedSignatureBytes[32:64]
191	r := compressedSignatureBytes[0:32]
192	b[0] = v
193	copy(b[1:33], s)
194	copy(b[33:65], r)
195	pkComp := tx.FromBJJ.Compress()
196	copy(b[65:97], pkComp[:])
197	copy(b[97:101], tx.TokenID.Bytes())
198	return b[:], nil
199}
200
201// L1TxFromBytes decodes a L1Tx from []byte
202func L1TxFromBytes(b []byte) (*L1Tx, error) {
203	if len(b) != L1TxBytesLen {
204		return nil, fmt.Errorf("Can not parse L1Tx bytes, expected length %d, current: %d", 68, len(b))
205	}
206
207	tx := &L1Tx{}
208	var err error
209	tx.FromEthAddr = ethCommon.BytesToAddress(b[0:20])
210	pkCompB := b[20:52]
211	var pkComp babyjub.PublicKeyComp
212	copy(pkComp[:], pkCompB)
213	tx.FromBJJ, err = pkComp.Decompress()
214	if err != nil {
215		return nil, err
216	}
217	fromIdx, err := IdxFromBytes(b[52:58])
218	if err != nil {
219		return nil, err
220	}
221	if fromIdx != 0 {
222		tx.FromIdx = new(Idx)
223		*tx.FromIdx = fromIdx
224	}
225	tx.LoadAmount = Float16FromBytes(b[58:60]).BigInt()
226	tx.Amount = Float16FromBytes(b[60:62]).BigInt()
227	tx.TokenID, err = TokenIDFromBytes(b[62:66])
228	if err != nil {
229		return nil, err
230	}
231	tx.ToIdx, err = IdxFromBytes(b[66:72])
232	if err != nil {
233		return nil, err
234	}
235
236	return tx, nil
237}
238
239// L1TxFromCoordinatorBytes decodes a L1Tx from []byte
240func L1TxFromCoordinatorBytes(b []byte) (*L1Tx, error) {
241	if len(b) != L1CoordinatorTxBytesLen {
242		return nil, fmt.Errorf("Can not parse L1CoordinatorTx bytes, expected length %d, current: %d", 101, len(b))
243	}
244
245	bytesMessage1 := []byte("\x19Ethereum Signed Message:\n98")
246	bytesMessage2 := []byte("I authorize this babyjubjub key for hermez rollup account creation")
247
248	tx := &L1Tx{}
249	var err error
250	// Ethereum adds 27 to v
251	v := b[0] - byte(27) //nolint:gomnd
252	s := b[1:33]
253	r := b[33:65]
254
255	pkCompB := b[65:97]
256	var pkComp babyjub.PublicKeyComp
257	copy(pkComp[:], pkCompB)
258	tx.FromBJJ, err = pkComp.Decompress()
259	if err != nil {
260		return nil, err
261	}
262	tx.TokenID, err = TokenIDFromBytes(b[97:101])
263	if err != nil {
264		return nil, err
265	}
266
267	var data []byte
268	data = append(data, bytesMessage1...)
269	data = append(data, bytesMessage2...)
270	data = append(data, pkCompB...)
271	var signature []byte
272	signature = append(signature, r[:]...)
273	signature = append(signature, s[:]...)
274	signature = append(signature, v)
275	hash := crypto.Keccak256(data)
276	pubKeyBytes, err := crypto.Ecrecover(hash, signature)
277	if err != nil {
278		return nil, err
279	}
280	pubKey, err := crypto.UnmarshalPubkey(pubKeyBytes)
281	if err != nil {
282		return nil, err
283	}
284	tx.FromEthAddr = crypto.PubkeyToAddress(*pubKey)
285	return tx, nil
286}