common

package
v1.2.0-rc2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 30, 2021 License: AGPL-3.0 Imports: 25 Imported by: 10

Documentation

Overview

Package common float40.go provides methods to work with Hermez custom half float precision, 40 bits, codification internally called Float40 has been adopted to encode large integers. This is done in order to save bits when L2 transactions are published.

Package common zk.go contains all the common data structures used at the hermez-node, zk.go contains the zkSnark inputs used to generate the proof

Index

Constants

View Source
const (
	// NLeafElems is the number of elements for a leaf
	NLeafElems = 4

	// IdxBytesLen idx bytes
	IdxBytesLen = 6

	// UserThreshold determines the threshold from the User Idxs can be
	UserThreshold = 256
	// IdxUserThreshold is a Idx type value that determines the threshold
	// from the User Idxs can be
	IdxUserThreshold = Idx(UserThreshold)
)
View Source
const (
	// AccountCreationAuthMsg is the message that is signed to authorize a
	// Hermez account creation
	AccountCreationAuthMsg = "Account creation"
	// EIP712Version is the used version of the EIP-712
	EIP712Version = "1"
	// EIP712Provider defines the Provider for the EIP-712
	EIP712Provider = "Hermez Network"
)
View Source
const (
	// RollupConstMaxFeeIdxCoordinator is the maximum number of tokens the
	// coordinator can use to collect fees (determines the number of tokens
	// that the coordinator can collect fees from).  This value is
	// determined by the circuit.
	RollupConstMaxFeeIdxCoordinator = 64
	// RollupConstReservedIDx First 256 indexes reserved, first user index will be the 256
	RollupConstReservedIDx = 255
	// RollupConstExitIDx IDX 1 is reserved for exits
	RollupConstExitIDx = 1
	// RollupConstLimitTokens Max number of tokens allowed to be registered inside the rollup
	RollupConstLimitTokens = (1 << 32) //nolint:gomnd
	// RollupConstL1CoordinatorTotalBytes [4 bytes] token + [32 bytes] babyjub + [65 bytes]
	// compressedSignature
	RollupConstL1CoordinatorTotalBytes = 101
	// RollupConstL1UserTotalBytes [20 bytes] fromEthAddr + [32 bytes] fromBjj-compressed + [6
	// bytes] fromIdx + [5 bytes] depositAmountFloat40 + [5 bytes] amountFloat40 + [4 bytes]
	// tokenId + [6 bytes] toIdx
	RollupConstL1UserTotalBytes = 78
	// RollupConstMaxL1UserTx Maximum L1-user transactions allowed to be queued in a batch
	RollupConstMaxL1UserTx = 128
	// RollupConstMaxL1Tx Maximum L1 transactions allowed to be queued in a batch
	RollupConstMaxL1Tx = 256
	// RollupConstInputSHAConstantBytes [6 bytes] lastIdx + [6 bytes] newLastIdx  + [32 bytes]
	// stateRoot  + [32 bytes] newStRoot  + [32 bytes] newExitRoot + [_MAX_L1_TX *
	// _L1_USER_TOTALBYTES bytes] l1TxsData + totalL2TxsDataLength + feeIdxCoordinatorLength +
	// [2 bytes] chainID = 18542 bytes +  totalL2TxsDataLength + feeIdxCoordinatorLength
	RollupConstInputSHAConstantBytes = 18546
	// RollupConstMaxWithdrawalDelay max withdrawal delay in seconds
	RollupConstMaxWithdrawalDelay = 2 * 7 * 24 * 60 * 60
	// RollupConstExchangeMultiplier exchange multiplier
	RollupConstExchangeMultiplier = 1e14
)
View Source
const (
	// TxIDPrefixL1UserTx is the prefix that determines that the TxID is for
	// a L1UserTx
	//nolinter:gomnd
	TxIDPrefixL1UserTx = byte(0)

	// TxIDPrefixL1CoordTx is the prefix that determines that the TxID is
	// for a L1CoordinatorTx
	//nolinter:gomnd
	TxIDPrefixL1CoordTx = byte(1)

	// TxIDPrefixL2Tx is the prefix that determines that the TxID is for a
	// L2Tx (or PoolL2Tx)
	//nolinter:gomnd
	TxIDPrefixL2Tx = byte(2)

	// TxIDLen is the length of the TxID byte array
	TxIDLen = 33
)
View Source
const (
	// AuctionErrMsgCannotForge is the message returned in forge with the
	// address cannot forge
	AuctionErrMsgCannotForge = "HermezAuctionProtocol::forge: CANNOT_FORGE"
)
View Source
const (

	// Float40BytesLength defines the length of the Float40 values
	// represented as byte arrays
	Float40BytesLength = 5
)
View Source
const MaxFeePlan = 256

MaxFeePlan is the maximum value of the FeePlan

Variables

View Source
var (
	// FFAddr is used to check if an ethereum address is 0xff..ff
	FFAddr = ethCommon.HexToAddress("0xffffffffffffffffffffffffffffffffffffffff")
	// EmptyAddr is used to check if an ethereum address is 0
	EmptyAddr = ethCommon.HexToAddress("0x0000000000000000000000000000000000000000")
)
View Source
var (
	// RollupConstLimitDepositAmount Max deposit amount allowed (depositAmount: L1 --> L2)
	RollupConstLimitDepositAmount, _ = new(big.Int).SetString(
		"340282366920938463463374607431768211456", 10)
	// RollupConstLimitL2TransferAmount Max amount allowed (amount L2 --> L2)
	RollupConstLimitL2TransferAmount, _ = new(big.Int).SetString(
		"6277101735386680763835789423207666416102355444464034512896", 10)

	// RollupConstEthAddressInternalOnly This ethereum address is used internally for rollup
	// accounts that don't have ethereum address, only Babyjubjub.
	// This non-ethereum accounts can be created by the coordinator and allow users to have a
	// rollup account without needing an ethereum address
	RollupConstEthAddressInternalOnly = ethCommon.HexToAddress(
		"0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF")
	// RollupConstRfield Modulus zkSNARK
	RollupConstRfield, _ = new(big.Int).SetString(
		"21888242871839275222246405745257275088548364400416034343698204186575808495617", 10)

	// RollupConstERC1820 ERC1820Registry address
	RollupConstERC1820 = ethCommon.HexToAddress("0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24")

	// RollupConstRecipientInterfaceHash ERC777 recipient interface hash
	RollupConstRecipientInterfaceHash = crypto.Keccak256([]byte("ERC777TokensRecipient"))
	// RollupConstPerformL1UserTxSignature the signature of the function that can be called thru
	// an ERC777 `send`
	RollupConstPerformL1UserTxSignature = crypto.Keccak256([]byte(
		"addL1Transaction(uint256,uint48,uint16,uint16,uint32,uint48)"))
	// RollupConstAddTokenSignature the signature of the function that can be called thru an
	// ERC777 `send`
	RollupConstAddTokenSignature = crypto.Keccak256([]byte("addToken(address)"))
	// RollupConstSendSignature ERC777 Signature
	RollupConstSendSignature = crypto.Keccak256([]byte("send(address,uint256,bytes)"))
	// RollupConstERC777Granularity ERC777 Signature
	RollupConstERC777Granularity = crypto.Keccak256([]byte("granularity()"))
	// RollupConstWithdrawalDelayerDeposit  This constant are used to deposit tokens from ERC77
	// tokens into withdrawal delayer
	RollupConstWithdrawalDelayerDeposit = crypto.Keccak256([]byte("deposit(address,address,uint192)"))

	// RollupConstTransferSignature This constant is used in the _safeTransfer internal method
	// in order to safe GAS.
	RollupConstTransferSignature = crypto.Keccak256([]byte("transfer(address,uint256)"))
	// RollupConstTransferFromSignature This constant is used in the _safeTransfer internal
	// method in order to safe GAS.
	RollupConstTransferFromSignature = crypto.Keccak256([]byte(
		"transferFrom(address,address,uint256)"))
	// RollupConstApproveSignature This constant is used in the _safeTransfer internal method in
	// order to safe GAS.
	RollupConstApproveSignature = crypto.Keccak256([]byte("approve(address,uint256)"))
	// RollupConstERC20Signature ERC20 decimals signature
	RollupConstERC20Signature = crypto.Keccak256([]byte("decimals()"))
)
View Source
var (
	// ErrFloat40Overflow is used when a given Float40 overflows the
	// maximum capacity of the Float40 (2**40-1)
	ErrFloat40Overflow = errors.New("Float40 overflow, max value: 2**40 -1")
	// ErrFloat40E31 is used when the e > 31 when trying to convert a
	// *big.Int to Float40
	ErrFloat40E31 = errors.New("Float40 error, e > 31")
	// ErrFloat40NotEnoughPrecission is used when the given *big.Int can
	// not be represented as Float40 due not enough precission
	ErrFloat40NotEnoughPrecission = errors.New("Float40 error, not enough precission")
)
View Source
var EmptyBJJComp = babyjub.PublicKeyComp([32]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0})

EmptyBJJComp contains the 32 byte array of a empty BabyJubJub PublicKey Compressed. It is a valid point in the BabyJubJub curve, so does not give errors when being decompressed.

View Source
var (
	// EmptyEthSignature is an ethereum signature of all zeroes
	EmptyEthSignature = make([]byte, 65)
)
View Source
var ErrBatchQueueEmpty = errors.New("BatchQueue empty")

ErrBatchQueueEmpty is used when the coordinator.BatchQueue.Pop() is called and has no elements

View Source
var ErrDone = errors.New("done")

ErrDone is used when a function returns earlier due to a cancelled context

View Source
var ErrIdxOverflow = errors.New("Idx overflow, max value: 2**48 -1")

ErrIdxOverflow is used when a given nonce overflows the maximum capacity of the Idx (2**48-1)

View Source
var ErrNonceOverflow = errors.New("Nonce overflow, max value: 2**40 -1")

ErrNonceOverflow is used when a given nonce overflows the maximum capacity of the Nonce (2**40-1)

View Source
var ErrNotInFF = errors.New("BigInt not inside the Finite Field")

ErrNotInFF is used when the *big.Int does not fit inside the Finite Field

View Source
var ErrNumOverflow = errors.New("Value overflows the type")

ErrNumOverflow is used when a given value overflows the maximum capacity of the parameter

View Source
var ErrTODO = errors.New("TODO")

ErrTODO is used when a function is not yet implemented

View Source
var FeeFactorLsh60 [256]*big.Int

FeeFactorLsh60 is the feeFactor << 60

View Source
var FeePlan = [MaxFeePlan]float64{}

FeePlan represents the fee model, a position in the array indicates the percentage of tokens paid in concept of fee for a transaction

View Source
var (
	// SignatureConstantBytes contains the SignatureConstant in byte array
	// format, which is equivalent to 3322668559 as uint32 in byte array in
	// big endian representation.
	SignatureConstantBytes = []byte{198, 11, 230, 15}
)

Functions

func BJJFromStringWithChecksum

func BJJFromStringWithChecksum(s string) (babyjub.PublicKeyComp, error)

BJJFromStringWithChecksum parses a hex string in Hermez format (which has the Hermez checksum at the last byte, and is encoded in BigEndian) and returns the corresponding *babyjub.PublicKey. This method is not part of the spec, is used for importing javascript test vectors data.

func CalcFeeAmount

func CalcFeeAmount(amount *big.Int, feeSel FeeSelector) (*big.Int, error)

CalcFeeAmount calculates the fee amount in tokens from an amount and feeSelector (fee index).

func CopyBigInt

func CopyBigInt(a *big.Int) *big.Int

CopyBigInt returns a copy of the big int

func EthAddrToBigInt

func EthAddrToBigInt(a ethCommon.Address) *big.Int

EthAddrToBigInt returns a *big.Int from a given ethereum common.Address.

func IsErrDone

func IsErrDone(err error) bool

IsErrDone returns true if the error or wrapped (with tracerr) error is ErrDone

func RmEndingZeroes

func RmEndingZeroes(siblings []*merkletree.Hash) []*merkletree.Hash

RmEndingZeroes is used to convert the Siblings from a CircomProof into Siblings of a merkletree Proof compatible with the js version. This method should be used only if it exist an already generated CircomProof compatible with circom circuits and a CircomProof compatible with SmartContracts is needed. If the proof is not generated yet, this method should not be needed and should be used mt.GenerateSCVerifierProof to directly generate the CircomProof for the SmartContracts.

func SwapEndianness

func SwapEndianness(b []byte) []byte

SwapEndianness swaps the order of the bytes in the slice.

func TokensToUSD

func TokensToUSD(amount *big.Int, decimals uint64, valueUSD float64) float64

TokensToUSD is a helper function to calculate the USD value of a certain amount of tokens considering the normalized token price (which is the price commonly reported by exhanges)

func TxCompressedDataEmpty

func TxCompressedDataEmpty(chainID uint16) *big.Int

TxCompressedDataEmpty calculates the TxCompressedData of an empty transaction

Types

type Account

type Account struct {
	Idx      Idx                   `meddler:"idx"`
	TokenID  TokenID               `meddler:"token_id"`
	BatchNum BatchNum              `meddler:"batch_num"`
	BJJ      babyjub.PublicKeyComp `meddler:"bjj"`
	EthAddr  ethCommon.Address     `meddler:"eth_addr"`
	Nonce    Nonce                 `meddler:"-"` // max of 40 bits used
	Balance  *big.Int              `meddler:"-"` // max of 192 bits used
}

Account is a struct that gives information of the holdings of an address and a specific token. Is the data structure that generates the Value stored in the leaf of the MerkleTree

func AccountFromBigInts

func AccountFromBigInts(e [NLeafElems]*big.Int) (*Account, error)

AccountFromBigInts returns a Account from a [5]*big.Int

func AccountFromBytes

func AccountFromBytes(b [32 * NLeafElems]byte) (*Account, error)

AccountFromBytes returns a Account from a byte array

func (*Account) BigInts

func (a *Account) BigInts() ([NLeafElems]*big.Int, error)

BigInts returns the [5]*big.Int, where each *big.Int is inside the Finite Field

func (*Account) Bytes

func (a *Account) Bytes() ([32 * NLeafElems]byte, error)

Bytes returns the bytes representing the Account, in a way that each BigInt is represented by 32 bytes, in spite of the BigInt could be represented in less bytes (due a small big.Int), so in this way each BigInt is always 32 bytes and can be automatically parsed from a byte array.

func (*Account) HashValue

func (a *Account) HashValue() (*big.Int, error)

HashValue returns the value of the Account, which is the Poseidon hash of its *big.Int representation

func (*Account) String

func (a *Account) String() string

type AccountCreationAuth

type AccountCreationAuth struct {
	EthAddr   ethCommon.Address     `meddler:"eth_addr"`
	BJJ       babyjub.PublicKeyComp `meddler:"bjj"`
	Signature []byte                `meddler:"signature"`
	Timestamp time.Time             `meddler:"timestamp,utctime"`
}

AccountCreationAuth authorizations sent by users to the L2DB, to be used for account creations when necessary

func (*AccountCreationAuth) HashToSign

func (a *AccountCreationAuth) HashToSign(chainID uint16,
	hermezContractAddr ethCommon.Address) ([]byte, error)

HashToSign returns the hash to be signed by the Ethereum address to authorize the account creation, which follows the EIP-712 encoding

func (*AccountCreationAuth) Sign

func (a *AccountCreationAuth) Sign(signHash func(hash []byte) ([]byte, error),
	chainID uint16, hermezContractAddr ethCommon.Address) error

Sign signs the account creation authorization message using the provided `signHash` function, and stores the signature in `a.Signature`. `signHash` should do an ethereum signature using the account corresponding to `a.EthAddr`. The `signHash` function is used to make signing flexible: in tests we sign directly using the private key, outside tests we sign using the keystore (which never exposes the private key). Sign follows the EIP-712 encoding.

func (*AccountCreationAuth) VerifySignature

func (a *AccountCreationAuth) VerifySignature(chainID uint16,
	hermezContractAddr ethCommon.Address) bool

VerifySignature ensures that the Signature is done with the EthAddr, for the chainID and hermezContractAddress passed by parameter. VerifySignature follows the EIP-712 encoding.

type AccountUpdate

type AccountUpdate struct {
	EthBlockNum int64    `meddler:"eth_block_num"`
	BatchNum    BatchNum `meddler:"batch_num"`
	Idx         Idx      `meddler:"idx"`
	Nonce       Nonce    `meddler:"nonce"`
	Balance     *big.Int `meddler:"balance,bigint"`
}

AccountUpdate represents an account balance and/or nonce update after a processed batch

type AuctionConstants

type AuctionConstants struct {
	// Blocks per slot
	BlocksPerSlot uint8 `json:"blocksPerSlot"`
	// Minimum bid when no one has bid yet
	InitialMinimalBidding *big.Int `json:"initialMinimalBidding"`
	// First block where the first slot begins
	GenesisBlockNum int64 `json:"genesisBlockNum"`
	// ERC777 token with which the bids will be made
	TokenHEZ ethCommon.Address `json:"tokenHEZ"`
	// HermezRollup smartcontract address
	HermezRollup ethCommon.Address `json:"hermezRollup"`
	// Hermez Governanze Token smartcontract address who controls some parameters and collects HEZ fee
	GovernanceAddress ethCommon.Address `json:"governanceAddress"`
}

AuctionConstants are the constants of the Rollup Smart Contract

func (*AuctionConstants) RelativeBlock

func (c *AuctionConstants) RelativeBlock(blockNum int64) int64

RelativeBlock returns the relative block number within the slot where the block number belongs

func (*AuctionConstants) SlotBlocks

func (c *AuctionConstants) SlotBlocks(slotNum int64) (int64, int64)

SlotBlocks returns the first and the last block numbers included in that slot

func (*AuctionConstants) SlotNum

func (c *AuctionConstants) SlotNum(blockNum int64) int64

SlotNum returns the slot number of a block number

type AuctionData

type AuctionData struct {
	Bids         []Bid
	Coordinators []Coordinator
	Vars         *AuctionVariables
}

AuctionData contains information returned by the Action smart contract

func NewAuctionData

func NewAuctionData() AuctionData

NewAuctionData creates an empty AuctionData with the slices initialized.

type AuctionVariables

type AuctionVariables struct {
	EthBlockNum int64 `meddler:"eth_block_num"`
	// Donation Address
	DonationAddress ethCommon.Address `meddler:"donation_address" validate:"required"`
	// Boot Coordinator Address
	BootCoordinator ethCommon.Address `meddler:"boot_coordinator" validate:"required"`
	// Boot Coordinator URL
	BootCoordinatorURL string `meddler:"boot_coordinator_url" validate:"required"`
	// The minimum bid value in a series of 6 slots
	DefaultSlotSetBid [6]*big.Int `meddler:"default_slot_set_bid,json" validate:"required"`
	// SlotNum at which the new default_slot_set_bid applies
	DefaultSlotSetBidSlotNum int64 `meddler:"default_slot_set_bid_slot_num"`
	// Distance (#slots) to the closest slot to which you can bid ( 2 Slots = 2 * 40 Blocks = 20 min )
	ClosedAuctionSlots uint16 `meddler:"closed_auction_slots" validate:"required"`
	// Distance (#slots) to the farthest slot to which you can bid (30 days = 4320 slots )
	OpenAuctionSlots uint16 `meddler:"open_auction_slots" validate:"required"`
	// How the HEZ tokens deposited by the slot winner are distributed (Burn: 40% - Donation:
	// 40% - HGT: 20%)
	AllocationRatio [3]uint16 `meddler:"allocation_ratio,json" validate:"required"`
	// Minimum outbid (percentage) over the previous one to consider it valid
	Outbidding uint16 `meddler:"outbidding" validate:"required"`
	// Number of blocks at the end of a slot in which any coordinator can forge if the winner
	// has not forged one before
	SlotDeadline uint8 `meddler:"slot_deadline" validate:"required"`
}

AuctionVariables are the variables of the Auction Smart Contract

func (*AuctionVariables) Copy

Copy returns a deep copy of the Variables

type Batch

type Batch struct {
	BatchNum BatchNum `meddler:"batch_num"`
	// Ethereum block in which the batch is forged
	EthBlockNum        int64                `meddler:"eth_block_num"`
	ForgerAddr         ethCommon.Address    `meddler:"forger_addr"`
	CollectedFees      map[TokenID]*big.Int `meddler:"fees_collected,json"`
	FeeIdxsCoordinator []Idx                `meddler:"fee_idxs_coordinator,json"`
	StateRoot          *big.Int             `meddler:"state_root,bigint"`
	NumAccounts        int                  `meddler:"num_accounts"`
	LastIdx            int64                `meddler:"last_idx"`
	ExitRoot           *big.Int             `meddler:"exit_root,bigint"`
	// ForgeL1TxsNum is optional, Only when the batch forges L1 txs. Identifier that corresponds
	// to the group of L1 txs forged in the current batch.
	ForgeL1TxsNum *int64   `meddler:"forge_l1_txs_num"`
	SlotNum       int64    `meddler:"slot_num"` // Slot in which the batch is forged
	TotalFeesUSD  *float64 `meddler:"total_fees_usd"`
}

Batch is a struct that represents Hermez network batch

func NewEmptyBatch

func NewEmptyBatch() *Batch

NewEmptyBatch creates a new empty batch

type BatchData

type BatchData struct {
	L1Batch bool // TODO: Remove once Batch.ForgeL1TxsNum is a pointer
	// L1UserTxs that were forged in the batch
	L1UserTxs        []L1Tx
	L1CoordinatorTxs []L1Tx
	L2Txs            []L2Tx
	CreatedAccounts  []Account
	UpdatedAccounts  []AccountUpdate
	ExitTree         []ExitInfo
	Batch            Batch
}

BatchData contains the information of a Batch

func NewBatchData

func NewBatchData() *BatchData

NewBatchData creates an empty BatchData with the slices initialized.

type BatchNum

type BatchNum int64

BatchNum identifies a batch

func BatchNumFromBytes

func BatchNumFromBytes(b []byte) (BatchNum, error)

BatchNumFromBytes returns BatchNum from a []byte

func (BatchNum) BigInt

func (bn BatchNum) BigInt() *big.Int

BigInt returns a *big.Int representing the BatchNum

func (BatchNum) Bytes

func (bn BatchNum) Bytes() []byte

Bytes returns a byte array of length 4 representing the BatchNum

type Bid

type Bid struct {
	SlotNum     int64             `meddler:"slot_num"`
	BidValue    *big.Int          `meddler:"bid_value,bigint"`
	EthBlockNum int64             `meddler:"eth_block_num"`
	Bidder      ethCommon.Address `meddler:"bidder_addr"` // Coordinator reference
}

Bid is a struct that represents one bid in the PoH

type BidCoordinator

type BidCoordinator struct {
	SlotNum           int64             `meddler:"slot_num"`
	DefaultSlotSetBid [6]*big.Int       `meddler:"default_slot_set_bid,json"`
	BidValue          *big.Int          `meddler:"bid_value,bigint"`
	Bidder            ethCommon.Address `meddler:"bidder_addr"` // address of the bidder
	Forger            ethCommon.Address `meddler:"forger_addr"` // address of the forger
	URL               string            `meddler:"url"`         // URL of the coordinators API
}

BidCoordinator contains the coordinator info of a bid, along with the bid value

type Block

type Block struct {
	Num        int64          `meddler:"eth_block_num"`
	Timestamp  time.Time      `meddler:"timestamp,utctime"`
	Hash       ethCommon.Hash `meddler:"hash"`
	ParentHash ethCommon.Hash `meddler:"-" json:"-"`
}

Block represents of an Ethereum block

type BlockData

type BlockData struct {
	Block    Block
	Rollup   RollupData
	Auction  AuctionData
	WDelayer WDelayerData
}

BlockData contains the information of a Block

type BucketParams

type BucketParams struct {
	CeilUSD         *big.Int
	BlockStamp      *big.Int
	Withdrawals     *big.Int
	RateBlocks      *big.Int
	RateWithdrawals *big.Int
	MaxWithdrawals  *big.Int
}

BucketParams are the parameter variables of each Bucket of Rollup Smart Contract

type BucketUpdate

type BucketUpdate struct {
	EthBlockNum int64    `meddler:"eth_block_num"`
	NumBucket   int      `meddler:"num_bucket"`
	BlockStamp  int64    `meddler:"block_stamp"`
	Withdrawals *big.Int `meddler:"withdrawals,bigint"`
}

BucketUpdate are the bucket updates (tracking the withdrawals value changes) in Rollup Smart Contract

type Coordinator

type Coordinator struct {
	// Bidder is the address of the bidder
	Bidder ethCommon.Address `meddler:"bidder_addr"`
	// Forger is the address of the forger
	Forger ethCommon.Address `meddler:"forger_addr"`
	// EthBlockNum is the block in which the coordinator was registered
	EthBlockNum int64 `meddler:"eth_block_num"`
	// URL of the coordinators API
	URL string `meddler:"url"`
}

Coordinator represents a Hermez network coordinator who wins an auction for an specific slot WARNING: this is strongly based on the previous implementation, once the new spec is done, this may change a lot.

type ExitInfo

type ExitInfo struct {
	BatchNum    BatchNum                        `meddler:"batch_num"`
	AccountIdx  Idx                             `meddler:"account_idx"`
	MerkleProof *merkletree.CircomVerifierProof `meddler:"merkle_proof,json"`
	Balance     *big.Int                        `meddler:"balance,bigint"`
	// InstantWithdrawn is the ethBlockNum in which the exit is withdrawn
	// instantly.  nil means this hasn't happened.
	InstantWithdrawn *int64 `meddler:"instant_withdrawn"`
	// DelayedWithdrawRequest is the ethBlockNum in which the exit is
	// requested to be withdrawn from the delayedWithdrawn smart contract.
	// nil means this hasn't happened.
	DelayedWithdrawRequest *int64 `meddler:"delayed_withdraw_request"`
	// DelayedWithdrawn is the ethBlockNum in which the exit is withdrawn
	// from the delayedWithdrawn smart contract.  nil means this hasn't
	// happened.
	DelayedWithdrawn *int64 `meddler:"delayed_withdrawn"`
}

ExitInfo represents the ExitTree Leaf data

type FeeSelector

type FeeSelector uint8

FeeSelector is used to select a percentage from the FeePlan.

func (FeeSelector) Percentage

func (f FeeSelector) Percentage() float64

Percentage returns the associated percentage of the FeeSelector

type Float40

type Float40 uint64

Float40 represents a float in a 64 bit format

func Float40FromBytes

func Float40FromBytes(b []byte) Float40

Float40FromBytes returns a Float40 from a byte array of 5 bytes in Bigendian representation.

func NewFloat40

func NewFloat40(f *big.Int) (Float40, error)

NewFloat40 encodes a *big.Int integer as a Float40, returning error in case of loss during the encoding.

func NewFloat40Floor

func NewFloat40Floor(f *big.Int) (Float40, error)

NewFloat40Floor encodes a *big.Int integer as a Float40, rounding down in case of loss during the encoding. It returns an error in case that the number is too big (e>31). Warning: this method should not be used inside the hermez-node, it's a helper for external usage to generate valid Float40 values.

func (Float40) BigInt

func (f40 Float40) BigInt() (*big.Int, error)

BigInt converts the Float40 to a *big.Int v, where v = m * 10^e, being: [ e | m ] [ 5 bits | 35 bits ]

func (Float40) Bytes

func (f40 Float40) Bytes() ([]byte, error)

Bytes return a byte array of length 5 with the Float40 value encoded in BigEndian

type Idx

type Idx uint64

Idx represents the account Index in the MerkleTree

func IdxFromBigInt

func IdxFromBigInt(b *big.Int) (Idx, error)

IdxFromBigInt converts a *big.Int to Idx type

func IdxFromBytes

func IdxFromBytes(b []byte) (Idx, error)

IdxFromBytes returns Idx from a byte array

func (Idx) BigInt

func (idx Idx) BigInt() *big.Int

BigInt returns a *big.Int representing the Idx

func (Idx) Bytes

func (idx Idx) Bytes() ([6]byte, error)

Bytes returns a byte array representing the Idx

func (Idx) String

func (idx Idx) String() string

String returns a string representation of the Idx

type IdxNonce

type IdxNonce struct {
	Idx   Idx   `db:"idx"`
	Nonce Nonce `db:"nonce"`
}

IdxNonce is a pair of Idx and Nonce representing an account

type L1Tx

type L1Tx struct {

	// TxID (32 bytes) for L1Tx is the Keccak256 (ethereum) hash of:
	// bytes:  |  1   |        8        |    2     |      1      |
	// values: | type | ToForgeL1TxsNum | Position | 0 (padding) |
	// where type:
	// 	- L1UserTx: 0
	// 	- L1CoordinatorTx: 1
	TxID TxID `meddler:"id"`
	// ToForgeL1TxsNum indicates in which L1UserTx queue the tx was forged / will be forged
	ToForgeL1TxsNum *int64 `meddler:"to_forge_l1_txs_num"`
	Position        int    `meddler:"position"`
	// UserOrigin is set to 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
	UserOrigin bool `meddler:"user_origin"`
	// FromIdx is used by L1Tx/Deposit to indicate the Idx receiver of the L1Tx.DepositAmount
	// (deposit)
	FromIdx          Idx                   `meddler:"from_idx,zeroisnull"`
	EffectiveFromIdx Idx                   `meddler:"effective_from_idx,zeroisnull"`
	FromEthAddr      ethCommon.Address     `meddler:"from_eth_addr,zeroisnull"`
	FromBJJ          babyjub.PublicKeyComp `meddler:"from_bjj,zeroisnull"`
	// ToIdx is ignored in L1Tx/Deposit, but used in the L1Tx/DepositAndTransfer
	ToIdx   Idx      `meddler:"to_idx"`
	TokenID TokenID  `meddler:"token_id"`
	Amount  *big.Int `meddler:"amount,bigint"`
	// EffectiveAmount only applies to L1UserTx.
	EffectiveAmount *big.Int `meddler:"effective_amount,bigintnull"`
	DepositAmount   *big.Int `meddler:"deposit_amount,bigint"`
	// EffectiveDepositAmount only applies to L1UserTx.
	EffectiveDepositAmount *big.Int `meddler:"effective_deposit_amount,bigintnull"`
	// Ethereum Block Number in which this L1Tx was added to the queue
	EthBlockNum int64     `meddler:"eth_block_num"`
	Type        TxType    `meddler:"type"`
	BatchNum    *BatchNum `meddler:"batch_num"`
}

L1Tx is a struct that represents a L1 tx

func L1CoordinatorTxFromBytes

func L1CoordinatorTxFromBytes(b []byte, chainID *big.Int, hermezAddress ethCommon.Address) (*L1Tx,
	error)

L1CoordinatorTxFromBytes decodes a L1Tx from []byte

func L1TxFromDataAvailability

func L1TxFromDataAvailability(b []byte, nLevels uint32) (*L1Tx, error)

L1TxFromDataAvailability decodes a L1Tx from []byte (Data Availability)

func L1UserTxFromBytes

func L1UserTxFromBytes(b []byte) (*L1Tx, error)

L1UserTxFromBytes decodes a L1Tx from []byte

func NewL1Tx

func NewL1Tx(tx *L1Tx) (*L1Tx, error)

NewL1Tx returns the given L1Tx with the TxId & Type parameters calculated from the L1Tx values

func (*L1Tx) BytesCoordinatorTx

func (tx *L1Tx) BytesCoordinatorTx(compressedSignatureBytes []byte) ([]byte, error)

BytesCoordinatorTx encodes a L1CoordinatorTx into []byte

func (*L1Tx) BytesDataAvailability

func (tx *L1Tx) BytesDataAvailability(nLevels uint32) ([]byte, error)

BytesDataAvailability encodes a L1Tx into []byte for the Data Availability [ fromIdx | toIdx | amountFloat40 | Fee ]

func (*L1Tx) BytesGeneric

func (tx *L1Tx) BytesGeneric() ([]byte, error)

BytesGeneric returns the generic representation of a L1Tx. This method is used to compute the []byte representation of a L1UserTx, and also to compute the L1TxData for the ZKInputs (at the HashGlobalInputs), using this method for L1CoordinatorTxs & L1UserTxs (for the ZKInputs case).

func (*L1Tx) BytesUser

func (tx *L1Tx) BytesUser() ([]byte, error)

BytesUser encodes a L1UserTx into []byte

func (*L1Tx) SetID

func (tx *L1Tx) SetID() error

SetID sets the ID of the transaction. For L1UserTx uses (ToForgeL1TxsNum, Position), for L1CoordinatorTx uses (BatchNum, Position).

func (*L1Tx) SetType

func (tx *L1Tx) SetType() error

SetType sets the type of the transaction

func (L1Tx) Tx

func (tx L1Tx) Tx() Tx

Tx returns a *Tx from the L1Tx

func (L1Tx) TxCompressedData

func (tx L1Tx) TxCompressedData(chainID uint16) (*big.Int, error)

TxCompressedData spec: [ 1 bits ] empty (toBJJSign) // 1 byte [ 8 bits ] empty (userFee) // 1 byte [ 40 bits ] empty (nonce) // 5 bytes [ 32 bits ] tokenID // 4 bytes [ 48 bits ] toIdx // 6 bytes [ 48 bits ] fromIdx // 6 bytes [ 16 bits ] chainId // 2 bytes [ 32 bits ] empty (signatureConstant) // 4 bytes Total bits compressed data: 225 bits // 29 bytes in *big.Int representation

type L2Tx

type L2Tx struct {
	// Stored in DB: mandatory fields
	TxID     TxID     `meddler:"id"`
	BatchNum BatchNum `meddler:"batch_num"` // batchNum in which this tx was forged.
	Position int      `meddler:"position"`
	FromIdx  Idx      `meddler:"from_idx"`
	ToIdx    Idx      `meddler:"to_idx"`
	// TokenID is filled by the TxProcessor
	TokenID TokenID     `meddler:"token_id"`
	Amount  *big.Int    `meddler:"amount,bigint"`
	Fee     FeeSelector `meddler:"fee"`
	// Nonce is filled by the TxProcessor
	Nonce Nonce  `meddler:"nonce"`
	Type  TxType `meddler:"type"`
	// EthBlockNum in which this L2Tx was added to the queue
	EthBlockNum int64 `meddler:"eth_block_num"`
}

L2Tx is a struct that represents an already forged L2 tx

func L2TxFromBytesDataAvailability

func L2TxFromBytesDataAvailability(b []byte, nLevels int) (*L2Tx, error)

L2TxFromBytesDataAvailability decodes a L2Tx from []byte (Data Availability)

func NewL2Tx

func NewL2Tx(tx *L2Tx) (*L2Tx, error)

NewL2Tx returns the given L2Tx with the TxId & Type parameters calculated from the L2Tx values

func PoolL2TxsToL2Txs

func PoolL2TxsToL2Txs(txs []PoolL2Tx) ([]L2Tx, error)

PoolL2TxsToL2Txs returns an array of []L2Tx from an array of []PoolL2Tx

func (L2Tx) BytesDataAvailability

func (tx L2Tx) BytesDataAvailability(nLevels uint32) ([]byte, error)

BytesDataAvailability encodes a L2Tx into []byte for the Data Availability [ fromIdx | toIdx | amountFloat40 | Fee ]

func (L2Tx) CalculateTxID

func (tx L2Tx) CalculateTxID() ([TxIDLen]byte, error)

CalculateTxID returns the TxID of the transaction. This method is used to set the TxID for L2Tx and for PoolL2Tx.

func (L2Tx) PoolL2Tx

func (tx L2Tx) PoolL2Tx() *PoolL2Tx

PoolL2Tx returns the data structure of PoolL2Tx with the parameters of a L2Tx filled

func (*L2Tx) SetID

func (tx *L2Tx) SetID() error

SetID sets the ID of the transaction

func (*L2Tx) SetType

func (tx *L2Tx) SetType() error

SetType sets the type of the transaction. Uses (FromIdx, Nonce).

func (*L2Tx) Tx

func (tx *L2Tx) Tx() *Tx

Tx returns a *Tx from the L2Tx

type Nonce

type Nonce uint64

Nonce represents the nonce value in a uint64, which has the method Bytes that returns a byte array of length 5 (40 bits).

func NonceFromBytes

func NonceFromBytes(b [5]byte) Nonce

NonceFromBytes returns Nonce from a [5]byte

func (Nonce) BigInt

func (n Nonce) BigInt() *big.Int

BigInt returns the *big.Int representation of the Nonce value

func (Nonce) Bytes

func (n Nonce) Bytes() ([5]byte, error)

Bytes returns a byte array of length 5 representing the Nonce

type PoolL2Tx

type PoolL2Tx struct {

	// TxID (12 bytes) for L2Tx is:
	// bytes:  |  1   |    6    |   5   |
	// values: | type | FromIdx | Nonce |
	TxID    TxID `meddler:"tx_id"`
	FromIdx Idx  `meddler:"from_idx"`
	ToIdx   Idx  `meddler:"to_idx,zeroisnull"`
	// AuxToIdx is only used internally at the StateDB to avoid repeated
	// computation when processing transactions (from Synchronizer,
	// TxSelector, BatchBuilder)
	AuxToIdx  Idx                   `meddler:"-"`
	ToEthAddr ethCommon.Address     `meddler:"to_eth_addr,zeroisnull"`
	ToBJJ     babyjub.PublicKeyComp `meddler:"to_bjj,zeroisnull"`
	TokenID   TokenID               `meddler:"token_id"`
	Amount    *big.Int              `meddler:"amount,bigint"`
	Fee       FeeSelector           `meddler:"fee"`
	Nonce     Nonce                 `meddler:"nonce"` // effective 40 bits used
	State     PoolL2TxState         `meddler:"state"`
	// Info contains information about the status & State of the
	// transaction. As for example, if the Tx has not been selected in the
	// last batch due not enough Balance at the Sender account, this reason
	// would appear at this parameter.
	Info      string                `meddler:"info,zeroisnull"`
	Signature babyjub.SignatureComp `meddler:"signature"`         // tx signature
	Timestamp time.Time             `meddler:"timestamp,utctime"` // time when added to the tx pool
	// Stored in DB: optional fileds, may be uninitialized
	RqFromIdx         Idx                   `meddler:"rq_from_idx,zeroisnull"`
	RqToIdx           Idx                   `meddler:"rq_to_idx,zeroisnull"`
	RqToEthAddr       ethCommon.Address     `meddler:"rq_to_eth_addr,zeroisnull"`
	RqToBJJ           babyjub.PublicKeyComp `meddler:"rq_to_bjj,zeroisnull"`
	RqTokenID         TokenID               `meddler:"rq_token_id,zeroisnull"`
	RqAmount          *big.Int              `meddler:"rq_amount,bigintnull"`
	RqFee             FeeSelector           `meddler:"rq_fee,zeroisnull"`
	RqNonce           Nonce                 `meddler:"rq_nonce,zeroisnull"` // effective 48 bits used
	AbsoluteFee       float64               `meddler:"fee_usd,zeroisnull"`
	AbsoluteFeeUpdate time.Time             `meddler:"usd_update,utctimez"`
	Type              TxType                `meddler:"tx_type"`
	// Extra metadata, may be uninitialized
	RqTxCompressedData []byte `meddler:"-"` // 253 bits, optional for atomic txs
}

PoolL2Tx is a struct that represents a L2Tx sent by an account to the coordinator that is waiting to be forged

func L2TxsToPoolL2Txs

func L2TxsToPoolL2Txs(txs []L2Tx) []PoolL2Tx

L2TxsToPoolL2Txs returns an array of []*PoolL2Tx from an array of []*L2Tx, where the PoolL2Tx only have the parameters of a L2Tx filled.

func NewPoolL2Tx

func NewPoolL2Tx(tx *PoolL2Tx) (*PoolL2Tx, error)

NewPoolL2Tx returns the given L2Tx with the TxId & Type parameters calculated from the L2Tx values

func (*PoolL2Tx) HashToSign

func (tx *PoolL2Tx) HashToSign(chainID uint16) (*big.Int, error)

HashToSign returns the computed Poseidon hash from the *PoolL2Tx that will be signed by the sender.

func (PoolL2Tx) L2Tx

func (tx PoolL2Tx) L2Tx() L2Tx

L2Tx returns a *L2Tx from the PoolL2Tx

func (*PoolL2Tx) RqTxCompressedDataV2

func (tx *PoolL2Tx) RqTxCompressedDataV2() (*big.Int, error)

RqTxCompressedDataV2 is like the TxCompressedDataV2 but using the 'Rq' parameters. In a future iteration of the hermez-node, the 'Rq' parameters can be inside a struct, which contains the 'Rq' transaction grouped inside, so then computing the 'RqTxCompressedDataV2' would be just calling 'tx.Rq.TxCompressedDataV2()'. RqTxCompressedDataV2 spec: [ 1 bits ] rqToBJJSign // 1 byte [ 8 bits ] rqUserFee // 1 byte [ 40 bits ] rqNonce // 5 bytes [ 32 bits ] rqTokenID // 4 bytes [ 40 bits ] rqAmountFloat40 // 5 bytes [ 48 bits ] rqToIdx // 6 bytes [ 48 bits ] rqFromIdx // 6 bytes Total bits compressed data: 217 bits // 28 bytes in *big.Int representation

func (*PoolL2Tx) SetID

func (tx *PoolL2Tx) SetID() error

SetID sets the ID of the transaction

func (*PoolL2Tx) SetType

func (tx *PoolL2Tx) SetType() error

SetType sets the type of the transaction

func (PoolL2Tx) Tx

func (tx PoolL2Tx) Tx() Tx

Tx returns a *Tx from the PoolL2Tx

func (*PoolL2Tx) TxCompressedData

func (tx *PoolL2Tx) TxCompressedData(chainID uint16) (*big.Int, error)

TxCompressedData spec: [ 1 bits ] toBJJSign // 1 byte [ 8 bits ] userFee // 1 byte [ 40 bits ] nonce // 5 bytes [ 32 bits ] tokenID // 4 bytes [ 48 bits ] toIdx // 6 bytes [ 48 bits ] fromIdx // 6 bytes [ 16 bits ] chainId // 2 bytes [ 32 bits ] signatureConstant // 4 bytes Total bits compressed data: 225 bits // 29 bytes in *big.Int representation

func (*PoolL2Tx) TxCompressedDataV2

func (tx *PoolL2Tx) TxCompressedDataV2() (*big.Int, error)

TxCompressedDataV2 spec: [ 1 bits ] toBJJSign // 1 byte [ 8 bits ] userFee // 1 byte [ 40 bits ] nonce // 5 bytes [ 32 bits ] tokenID // 4 bytes [ 40 bits ] amountFloat40 // 5 bytes [ 48 bits ] toIdx // 6 bytes [ 48 bits ] fromIdx // 6 bytes Total bits compressed data: 217 bits // 28 bytes in *big.Int representation

func (*PoolL2Tx) VerifySignature

func (tx *PoolL2Tx) VerifySignature(chainID uint16, pkComp babyjub.PublicKeyComp) bool

VerifySignature returns true if the signature verification is correct for the given PublicKeyComp

type PoolL2TxState

type PoolL2TxState string

PoolL2TxState is a string that represents the status of a L2 transaction

const (
	// PoolL2TxStatePending represents a valid L2Tx that hasn't started the
	// forging process
	PoolL2TxStatePending PoolL2TxState = "pend"
	// PoolL2TxStateForging represents a valid L2Tx that has started the
	// forging process
	PoolL2TxStateForging PoolL2TxState = "fing"
	// PoolL2TxStateForged represents a L2Tx that has already been forged
	PoolL2TxStateForged PoolL2TxState = "fged"
	// PoolL2TxStateInvalid represents a L2Tx that has been invalidated
	PoolL2TxStateInvalid PoolL2TxState = "invl"
)

type RecommendedFee

type RecommendedFee struct {
	ExistingAccount        float64 `json:"existingAccount"`
	CreatesAccount         float64 `json:"createAccount"`
	CreatesAccountInternal float64 `json:"createAccountInternal"`
}

RecommendedFee is the recommended fee to pay in USD per transaction set by the coordinator according to the tx type (if the tx requires to create an account and register, only register or he account already esists)

type RollupConstants

type RollupConstants struct {
	AbsoluteMaxL1L2BatchTimeout int64                  `json:"absoluteMaxL1L2BatchTimeout"`
	TokenHEZ                    ethCommon.Address      `json:"tokenHEZ"`
	Verifiers                   []RollupVerifierStruct `json:"verifiers"`
	HermezAuctionContract       ethCommon.Address      `json:"hermezAuctionContract"`
	HermezGovernanceAddress     ethCommon.Address      `json:"hermezGovernanceAddress"`
	WithdrawDelayerContract     ethCommon.Address      `json:"withdrawDelayerContract"`
}

RollupConstants are the constants of the Rollup Smart Contract

func (*RollupConstants) FindVerifierIdx

func (c *RollupConstants) FindVerifierIdx(MaxTx, NLevels int64) (int, error)

FindVerifierIdx tries to find a matching verifier in the RollupConstants and returns its index

type RollupData

type RollupData struct {
	// L1UserTxs that were submitted in the block
	L1UserTxs            []L1Tx
	Batches              []BatchData
	AddedTokens          []Token
	Withdrawals          []WithdrawInfo
	UpdateBucketWithdraw []BucketUpdate
	TokenExchanges       []TokenExchange
	Vars                 *RollupVariables
}

RollupData contains information returned by the Rollup smart contract

func NewRollupData

func NewRollupData() RollupData

NewRollupData creates an empty RollupData with the slices initialized.

type RollupVariables

type RollupVariables struct {
	EthBlockNum           int64          `meddler:"eth_block_num"`
	FeeAddToken           *big.Int       `meddler:"fee_add_token,bigint" validate:"required"`
	ForgeL1L2BatchTimeout int64          `meddler:"forge_l1_timeout" validate:"required"`
	WithdrawalDelay       uint64         `meddler:"withdrawal_delay" validate:"required"`
	Buckets               []BucketParams `meddler:"buckets,json"`
	SafeMode              bool           `meddler:"safe_mode"`
}

RollupVariables are the variables of the Rollup Smart Contract

func (*RollupVariables) Copy

func (v *RollupVariables) Copy() *RollupVariables

Copy returns a deep copy of the Variables

type RollupVerifierStruct

type RollupVerifierStruct struct {
	MaxTx   int64 `json:"maxTx"`
	NLevels int64 `json:"nlevels"`
}

RollupVerifierStruct is the information about verifiers of the Rollup Smart Contract

type SCConsts

type SCConsts struct {
	Rollup   RollupConstants
	Auction  AuctionConstants
	WDelayer WDelayerConstants
}

SCConsts joins all the smart contract constants in a single struct

type SCVariables

type SCVariables struct {
	Rollup   RollupVariables   `validate:"required"`
	Auction  AuctionVariables  `validate:"required"`
	WDelayer WDelayerVariables `validate:"required"`
}

SCVariables joins all the smart contract variables in a single struct

func (*SCVariables) AsPtr

func (v *SCVariables) AsPtr() *SCVariablesPtr

AsPtr returns the SCVariables as a SCVariablesPtr using pointers to the original SCVariables

type SCVariablesPtr

type SCVariablesPtr struct {
	Rollup   *RollupVariables   `validate:"required"`
	Auction  *AuctionVariables  `validate:"required"`
	WDelayer *WDelayerVariables `validate:"required"`
}

SCVariablesPtr joins all the smart contract variables as pointers in a single struct

type Slot

type Slot struct {
	SlotNum          int64
	DefaultSlotBid   *big.Int
	StartBlock       int64
	EndBlock         int64
	ForgerCommitment bool
	// BatchesLen       int
	BidValue  *big.Int
	BootCoord bool
	// Bidder, Forger and URL correspond to the winner of the slot (which is
	// not always the highest bidder).  These are the values of the
	// coordinator that is able to forge exclusively before the deadline.
	Bidder ethCommon.Address
	Forger ethCommon.Address
	URL    string
}

Slot contains relevant information of a slot

type Token

type Token struct {
	TokenID TokenID `json:"id" meddler:"token_id"`
	// EthBlockNum indicates the Ethereum block number in which this token was registered
	EthBlockNum int64             `json:"ethereumBlockNum" meddler:"eth_block_num"`
	EthAddr     ethCommon.Address `json:"ethereumAddress" meddler:"eth_addr"`
	Name        string            `json:"name" meddler:"name"`
	Symbol      string            `json:"symbol" meddler:"symbol"`
	Decimals    uint64            `json:"decimals" meddler:"decimals"`
}

Token is a struct that represents an Ethereum token that is supported in Hermez network

type TokenExchange

type TokenExchange struct {
	EthBlockNum int64             `json:"ethereumBlockNum" meddler:"eth_block_num"`
	Address     ethCommon.Address `json:"address" meddler:"eth_addr"`
	ValueUSD    int64             `json:"valueUSD" meddler:"value_usd"`
}

TokenExchange are the exchange value for tokens registered in the Rollup Smart Contract

type TokenID

type TokenID uint32 // current implementation supports up to 2^32 tokens

TokenID is the unique identifier of the token, as set in the smart contract

func TokenIDFromBigInt

func TokenIDFromBigInt(b *big.Int) TokenID

TokenIDFromBigInt returns a TokenID with the value of the given *big.Int

func TokenIDFromBytes

func TokenIDFromBytes(b []byte) (TokenID, error)

TokenIDFromBytes returns TokenID from a byte array

func (TokenID) BigInt

func (t TokenID) BigInt() *big.Int

BigInt returns the *big.Int representation of the TokenID

func (TokenID) Bytes

func (t TokenID) Bytes() []byte

Bytes returns a byte array of length 4 representing the TokenID

type TokenInfo

type TokenInfo struct {
	TokenID     uint32
	Value       float64
	LastUpdated time.Time
}

TokenInfo provides the price of the token in USD

type Tx

type Tx struct {
	// Generic
	IsL1        bool     `meddler:"is_l1"`
	TxID        TxID     `meddler:"id"`
	Type        TxType   `meddler:"type"`
	Position    int      `meddler:"position"`
	FromIdx     Idx      `meddler:"from_idx"`
	ToIdx       Idx      `meddler:"to_idx"`
	Amount      *big.Int `meddler:"amount,bigint"`
	AmountFloat float64  `meddler:"amount_f"`
	TokenID     TokenID  `meddler:"token_id"`
	USD         *float64 `meddler:"amount_usd"`
	// BatchNum in which this tx was forged. If the tx is L2, this must be != 0
	BatchNum *BatchNum `meddler:"batch_num"`
	// Ethereum Block Number in which this L1Tx was added to the queue
	EthBlockNum int64 `meddler:"eth_block_num"`
	// L1
	// ToForgeL1TxsNum in which the tx was forged / will be forged
	ToForgeL1TxsNum *int64 `meddler:"to_forge_l1_txs_num"`
	// UserOrigin is set to 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
	UserOrigin         *bool                 `meddler:"user_origin"`
	FromEthAddr        ethCommon.Address     `meddler:"from_eth_addr"`
	FromBJJ            babyjub.PublicKeyComp `meddler:"from_bjj"`
	DepositAmount      *big.Int              `meddler:"deposit_amount,bigintnull"`
	DepositAmountFloat *float64              `meddler:"deposit_amount_f"`
	DepositAmountUSD   *float64              `meddler:"deposit_amount_usd"`
	// L2
	Fee    *FeeSelector `meddler:"fee"`
	FeeUSD *float64     `meddler:"fee_usd"`
	Nonce  *Nonce       `meddler:"nonce"`
}

Tx is a struct used by the TxSelector & BatchBuilder as a generic type generated from L1Tx & PoolL2Tx

func (*Tx) L1Tx

func (tx *Tx) L1Tx() (*L1Tx, error)

L1Tx returns a *L1Tx from the Tx

func (*Tx) String

func (tx *Tx) String() string

type TxID

type TxID [TxIDLen]byte

TxID is the identifier of a Hermez network transaction

func NewTxIDFromString

func NewTxIDFromString(idStr string) (TxID, error)

NewTxIDFromString returns a string hexadecimal representation of the TxID

func TxIDsFromL2Txs

func TxIDsFromL2Txs(txs []L2Tx) []TxID

TxIDsFromL2Txs returns an array of TxID from the []L2Tx

func TxIDsFromPoolL2Txs

func TxIDsFromPoolL2Txs(txs []PoolL2Tx) []TxID

TxIDsFromPoolL2Txs returns an array of TxID from the []PoolL2Tx

func (TxID) MarshalText

func (txid TxID) MarshalText() ([]byte, error)

MarshalText marshals a TxID

func (*TxID) Scan

func (txid *TxID) Scan(src interface{}) error

Scan implements Scanner for database/sql.

func (TxID) String

func (txid TxID) String() string

String returns a string hexadecimal representation of the TxID

func (*TxID) UnmarshalText

func (txid *TxID) UnmarshalText(data []byte) error

UnmarshalText unmarshalls a TxID

func (TxID) Value

func (txid TxID) Value() (driver.Value, error)

Value implements valuer for database/sql.

type TxType

type TxType string

TxType is a string that represents the type of a Hermez network transaction

const (
	// TxTypeExit represents L2->L1 token transfer.  A leaf for this account appears in the exit
	// tree of the block
	TxTypeExit TxType = "Exit"
	// TxTypeTransfer represents L2->L2 token transfer
	TxTypeTransfer TxType = "Transfer"
	// TxTypeDeposit represents L1->L2 transfer
	TxTypeDeposit TxType = "Deposit"
	// TxTypeCreateAccountDeposit represents creation of a new leaf in the state tree
	// (newAcconut) + L1->L2 transfer
	TxTypeCreateAccountDeposit TxType = "CreateAccountDeposit"
	// TxTypeCreateAccountDepositTransfer represents L1->L2 transfer + L2->L2 transfer
	TxTypeCreateAccountDepositTransfer TxType = "CreateAccountDepositTransfer"
	// TxTypeDepositTransfer TBD
	TxTypeDepositTransfer TxType = "DepositTransfer"
	// TxTypeForceTransfer TBD
	TxTypeForceTransfer TxType = "ForceTransfer"
	// TxTypeForceExit TBD
	TxTypeForceExit TxType = "ForceExit"
	// TxTypeTransferToEthAddr TBD
	TxTypeTransferToEthAddr TxType = "TransferToEthAddr"
	// TxTypeTransferToBJJ TBD
	TxTypeTransferToBJJ TxType = "TransferToBJJ"
)

type WDelayerConstants

type WDelayerConstants struct {
	// Max Withdrawal Delay
	MaxWithdrawalDelay uint64 `json:"maxWithdrawalDelay"`
	// Max Emergency mode time
	MaxEmergencyModeTime uint64 `json:"maxEmergencyModeTime"`
	// HermezRollup smartcontract address
	HermezRollup ethCommon.Address `json:"hermezRollup"`
}

WDelayerConstants are the constants of the Withdrawal Delayer Smart Contract

type WDelayerData

type WDelayerData struct {
	Vars     *WDelayerVariables
	Deposits []WDelayerTransfer
	// We use an array because there can be multiple deposits in a single eth transaction
	DepositsByTxHash       map[ethCommon.Hash][]*WDelayerTransfer
	Withdrawals            []WDelayerTransfer
	EscapeHatchWithdrawals []WDelayerEscapeHatchWithdrawal
}

WDelayerData contains information returned by the WDelayer smart contract

func NewWDelayerData

func NewWDelayerData() WDelayerData

NewWDelayerData creates an empty WDelayerData.

type WDelayerEscapeHatchWithdrawal

type WDelayerEscapeHatchWithdrawal struct {
	EthBlockNum int64             `json:"ethereumBlockNum" meddler:"eth_block_num"`
	Who         ethCommon.Address `json:"who" meddler:"who_addr"`
	To          ethCommon.Address `json:"to" meddler:"to_addr"`
	TokenAddr   ethCommon.Address `json:"tokenAddr" meddler:"token_addr"`
	Amount      *big.Int          `json:"amount" meddler:"amount,bigint"`
}

WDelayerEscapeHatchWithdrawal is an escape hatch withdrawal of the Withdrawal Delayer Smart Contract

type WDelayerTransfer

type WDelayerTransfer struct {
	Owner  ethCommon.Address
	Token  ethCommon.Address
	Amount *big.Int
}

WDelayerTransfer represents a transfer (either deposit or withdrawal) in the WDelayer smart contract

type WDelayerVariables

type WDelayerVariables struct {
	EthBlockNum int64 `json:"ethereumBlockNum" meddler:"eth_block_num"`
	// HermezRollupAddress        ethCommon.Address `json:"hermezRollupAddress" meddler:"rollup_address"`
	HermezGovernanceAddress    ethCommon.Address `json:"hermezGovernanceAddress" meddler:"gov_address" validate:"required"`
	EmergencyCouncilAddress    ethCommon.Address `json:"emergencyCouncilAddress" meddler:"emg_address" validate:"required"`
	WithdrawalDelay            uint64            `json:"withdrawalDelay" meddler:"withdrawal_delay" validate:"required"`
	EmergencyModeStartingBlock int64             `json:"emergencyModeStartingBlock" meddler:"emergency_start_block"`
	EmergencyMode              bool              `json:"emergencyMode" meddler:"emergency_mode"`
}

WDelayerVariables are the variables of the Withdrawal Delayer Smart Contract

func (*WDelayerVariables) Copy

Copy returns a deep copy of the Variables

type WithdrawInfo

type WithdrawInfo struct {
	Idx             Idx
	NumExitRoot     BatchNum
	InstantWithdraw bool
	TxHash          ethCommon.Hash // hash of the transaction in which the withdraw happened
	Owner           ethCommon.Address
	Token           ethCommon.Address
}

WithdrawInfo represents a withdraw action to the rollup

type ZKInputs

type ZKInputs struct {
	Metadata ZKMetadata `json:"-"`

	// CurrentNumBatch is the current batch number processed
	CurrentNumBatch *big.Int `json:"currentNumBatch"` // uint32
	// inputs for final `hashGlobalInputs`
	// OldLastIdx is the last index assigned to an account
	OldLastIdx *big.Int `json:"oldLastIdx"` // uint64 (max nLevels bits)
	// OldStateRoot is the current state merkle tree root
	OldStateRoot *big.Int `json:"oldStateRoot"` // Hash
	// GlobalChainID is the blockchain ID (0 for Ethereum mainnet). This
	// value can be get from the smart contract.
	GlobalChainID *big.Int `json:"globalChainID"` // uint16
	// FeeIdxs is an array of merkle tree indexes (Idxs) where the
	// coordinator will receive the accumulated fees
	FeeIdxs []*big.Int `json:"feeIdxs"` // uint64 (max nLevels bits), len: [maxFeeIdxs]

	// accumulate fees
	// FeePlanTokens contains all the tokenIDs for which the fees are being
	// accumulated and those fees accumulated will be paid to the FeeIdxs
	// array.  The order of FeeIdxs & FeePlanTokens & State3 must match.
	// Coordinator fees are processed correlated such as:
	// [FeePlanTokens[i], FeeIdxs[i]]
	FeePlanTokens []*big.Int `json:"feePlanTokens"` // uint32 (max nLevels bits), len: [maxFeeIdxs]

	// transaction L1-L2
	// TxCompressedData
	TxCompressedData []*big.Int `json:"txCompressedData"` // big.Int (max 251 bits), len: [maxTx]
	// TxCompressedDataV2, only used in L2Txs, in L1Txs is set to 0
	TxCompressedDataV2 []*big.Int `json:"txCompressedDataV2"` // big.Int (max 193 bits), len: [maxTx]
	// MaxNumBatch is the maximum allowed batch number when the transaction
	// can be processed
	MaxNumBatch []*big.Int `json:"maxNumBatch"` // big.Int (max 32 bits), len: [maxTx]

	// FromIdx
	FromIdx []*big.Int `json:"fromIdx"` // uint64 (max nLevels bits), len: [maxTx]
	// AuxFromIdx is the Idx of the new created account which is
	// consequence of a L1CreateAccountTx
	AuxFromIdx []*big.Int `json:"auxFromIdx"` // uint64 (max nLevels bits), len: [maxTx]

	// ToIdx
	ToIdx []*big.Int `json:"toIdx"` // uint64 (max nLevels bits), len: [maxTx]
	// AuxToIdx is the Idx of the Tx that has 'toIdx==0', is the
	// coordinator who will find which Idx corresponds to the 'toBJJAy' or
	// 'toEthAddr'
	AuxToIdx []*big.Int `json:"auxToIdx"` // uint64 (max nLevels bits), len: [maxTx]
	// ToBJJAy
	ToBJJAy []*big.Int `json:"toBjjAy"` // big.Int, len: [maxTx]
	// ToEthAddr
	ToEthAddr []*big.Int `json:"toEthAddr"` // ethCommon.Address, len: [maxTx]
	// AmountF encoded as float40
	AmountF []*big.Int `json:"amountF"` // uint40 len: [maxTx]

	// OnChain determines if is L1 (1/true) or L2 (0/false)
	OnChain []*big.Int `json:"onChain"` // bool, len: [maxTx]

	//
	// Txs/L1Txs
	//
	// NewAccount boolean (0/1) flag set 'true' when L1 tx creates a new
	// account (fromIdx==0)
	NewAccount []*big.Int `json:"newAccount"` // bool, len: [maxTx]
	// DepositAmountF encoded as float40
	DepositAmountF []*big.Int `json:"loadAmountF"` // uint40, len: [maxTx]
	// FromEthAddr
	FromEthAddr []*big.Int `json:"fromEthAddr"` // ethCommon.Address, len: [maxTx]
	// FromBJJCompressed boolean encoded where each value is a *big.Int
	FromBJJCompressed [][256]*big.Int `json:"fromBjjCompressed"` // bool array, len: [maxTx][256]

	// RqOffset relative transaction position to be linked. Used to perform
	// atomic transactions.
	RqOffset []*big.Int `json:"rqOffset"` // uint8 (max 3 bits), len: [maxTx]

	// transaction L2 request data
	// RqTxCompressedDataV2 big.Int (max 251 bits), len: [maxTx]
	RqTxCompressedDataV2 []*big.Int `json:"rqTxCompressedDataV2"`
	// RqToEthAddr
	RqToEthAddr []*big.Int `json:"rqToEthAddr"` // ethCommon.Address, len: [maxTx]
	// RqToBJJAy
	RqToBJJAy []*big.Int `json:"rqToBjjAy"` // big.Int, len: [maxTx]

	// transaction L2 signature
	// S
	S []*big.Int `json:"s"` // big.Int, len: [maxTx]
	// R8x
	R8x []*big.Int `json:"r8x"` // big.Int, len: [maxTx]
	// R8y
	R8y []*big.Int `json:"r8y"` // big.Int, len: [maxTx]

	// state 1, value of the sender (from) account leaf. The values at the
	// moment pre-smtprocessor of the update (before updating the Sender
	// leaf).
	TokenID1  []*big.Int   `json:"tokenID1"`  // uint32, len: [maxTx]
	Nonce1    []*big.Int   `json:"nonce1"`    // uint64 (max 40 bits), len: [maxTx]
	Sign1     []*big.Int   `json:"sign1"`     // bool, len: [maxTx]
	Ay1       []*big.Int   `json:"ay1"`       // big.Int, len: [maxTx]
	Balance1  []*big.Int   `json:"balance1"`  // big.Int (max 192 bits), len: [maxTx]
	EthAddr1  []*big.Int   `json:"ethAddr1"`  // ethCommon.Address, len: [maxTx]
	Siblings1 [][]*big.Int `json:"siblings1"` // big.Int, len: [maxTx][nLevels + 1]
	// Required for inserts and deletes, values of the CircomProcessorProof
	// (smt insert proof)
	IsOld0_1  []*big.Int `json:"isOld0_1"`  // bool, len: [maxTx]
	OldKey1   []*big.Int `json:"oldKey1"`   // uint64 (max 40 bits), len: [maxTx]
	OldValue1 []*big.Int `json:"oldValue1"` // Hash, len: [maxTx]

	// state 2, value of the receiver (to) account leaf. The values at the
	// moment pre-smtprocessor of the update (before updating the Receiver
	// leaf).
	// If Tx is an Exit (tx.ToIdx=1), state 2 is used for the Exit Merkle
	// Proof of the Exit MerkleTree.
	TokenID2  []*big.Int   `json:"tokenID2"`  // uint32, len: [maxTx]
	Nonce2    []*big.Int   `json:"nonce2"`    // uint64 (max 40 bits), len: [maxTx]
	Sign2     []*big.Int   `json:"sign2"`     // bool, len: [maxTx]
	Ay2       []*big.Int   `json:"ay2"`       // big.Int, len: [maxTx]
	Balance2  []*big.Int   `json:"balance2"`  // big.Int (max 192 bits), len: [maxTx]
	EthAddr2  []*big.Int   `json:"ethAddr2"`  // ethCommon.Address, len: [maxTx]
	Siblings2 [][]*big.Int `json:"siblings2"` // big.Int, len: [maxTx][nLevels + 1]
	// NewExit determines if an exit transaction has to create a new leaf
	// in the exit tree. If already exists an exit leaf of an account in
	// the ExitTree, there is no 'new leaf' creation and 'NewExit' for that
	// tx is 0 (if is an 'insert' in the tree, NewExit=1, if is an 'update'
	// of an existing leaf, NewExit=0).
	NewExit []*big.Int `json:"newExit"` // bool, len: [maxTx]
	// Required for inserts and deletes, values of the CircomProcessorProof
	// (smt insert proof)
	IsOld0_2  []*big.Int `json:"isOld0_2"`  // bool, len: [maxTx]
	OldKey2   []*big.Int `json:"oldKey2"`   // uint64 (max 40 bits), len: [maxTx]
	OldValue2 []*big.Int `json:"oldValue2"` // Hash, len: [maxTx]

	// state 3, fee leafs states, value of the account leaf receiver of the
	// Fees fee tx. The values at the moment pre-smtprocessor of the update
	// (before updating the Receiver leaf).
	// The order of FeeIdxs & FeePlanTokens & State3 must match.
	TokenID3  []*big.Int   `json:"tokenID3"`  // uint32, len: [maxFeeIdxs]
	Nonce3    []*big.Int   `json:"nonce3"`    // uint64 (max 40 bits), len: [maxFeeIdxs]
	Sign3     []*big.Int   `json:"sign3"`     // bool, len: [maxFeeIdxs]
	Ay3       []*big.Int   `json:"ay3"`       // big.Int, len: [maxFeeIdxs]
	Balance3  []*big.Int   `json:"balance3"`  // big.Int (max 192 bits), len: [maxFeeIdxs]
	EthAddr3  []*big.Int   `json:"ethAddr3"`  // ethCommon.Address, len: [maxFeeIdxs]
	Siblings3 [][]*big.Int `json:"siblings3"` // Hash, len: [maxFeeIdxs][nLevels + 1]

	// decode-tx
	// ISOnChain indicates if tx is L1 (true (1)) or L2 (false (0))
	ISOnChain []*big.Int `json:"imOnChain"` // bool, len: [maxTx - 1]
	// ISOutIdx current index account for each Tx
	// Contains the index of the created account in case that the tx is of
	// account creation type.
	ISOutIdx []*big.Int `json:"imOutIdx"` // uint64 (max nLevels bits), len: [maxTx - 1]
	// rollup-tx
	// ISStateRoot root at the moment of the Tx (once processed), the state
	// root value once the Tx is processed into the state tree
	ISStateRoot []*big.Int `json:"imStateRoot"` // Hash, len: [maxTx - 1]
	// ISExitTree root at the moment (once processed) of the Tx the value
	// once the Tx is processed into the exit tree
	ISExitRoot []*big.Int `json:"imExitRoot"` // Hash, len: [maxTx - 1]
	// ISAccFeeOut accumulated fees once the Tx is processed.  Contains the
	// array of FeeAccount Balances at each moment of each Tx processed.
	ISAccFeeOut [][]*big.Int `json:"imAccFeeOut"` // big.Int, len: [maxTx - 1][maxFeeIdxs]
	// fee-tx:
	// ISStateRootFee root at the moment of the Tx (once processed), the
	// state root value once the Tx is processed into the state tree
	ISStateRootFee []*big.Int `json:"imStateRootFee"` // Hash, len: [maxFeeIdxs - 1]
	// ISInitStateRootFee state root once all L1-L2 tx are processed
	// (before computing the fees-tx)
	ISInitStateRootFee *big.Int `json:"imInitStateRootFee"` // Hash
	// ISFinalAccFee final accumulated fees (before computing the fees-tx).
	// Contains the final values of the ISAccFeeOut parameter
	ISFinalAccFee []*big.Int `json:"imFinalAccFee"` // big.Int, len: [maxFeeIdxs]
}

ZKInputs represents the inputs that will be used to generate the zkSNARK proof

func NewZKInputs

func NewZKInputs(chainID uint16, maxTx, maxL1Tx, maxFeeIdxs, nLevels uint32,
	currentNumBatch *big.Int) *ZKInputs

NewZKInputs returns a pointer to an initialized struct of ZKInputs

func (ZKInputs) HashGlobalData

func (z ZKInputs) HashGlobalData() (*big.Int, error)

HashGlobalData returns the HashGlobalData

func (ZKInputs) MarshalJSON

func (z ZKInputs) MarshalJSON() ([]byte, error)

MarshalJSON implements the json marshaler for ZKInputs

func (ZKInputs) ToHashGlobalData

func (z ZKInputs) ToHashGlobalData() ([]byte, error)

ToHashGlobalData returns the data to be hashed in the method HashGlobalData

type ZKMetadata

type ZKMetadata struct {
	// Circuit parameters
	// absolute maximum of L1 or L2 transactions allowed
	MaxLevels uint32
	// merkle tree depth
	NLevels uint32
	// absolute maximum of L1 transaction allowed
	MaxL1Tx uint32
	// total txs allowed
	MaxTx uint32
	// Maximum number of Idxs where Fees can be send in a batch (currently
	// is constant for all circuits: 64)
	MaxFeeIdxs uint32

	L1TxsData             [][]byte
	L1TxsDataAvailability [][]byte
	L2TxsData             [][]byte
	ChainID               uint16

	NewLastIdxRaw   Idx
	NewStateRootRaw *merkletree.Hash
	NewExitRootRaw  *merkletree.Hash
}

ZKMetadata contains ZKInputs metadata that is not used directly in the ZKInputs result, but to calculate values for Hash check

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL