diff --git a/cmd/opdoc/opdoc.go b/cmd/opdoc/opdoc.go index 46a2185da0..8f59960f58 100644 --- a/cmd/opdoc/opdoc.go +++ b/cmd/opdoc/opdoc.go @@ -110,12 +110,12 @@ func assetHoldingFieldsMarkdown(out io.Writer) { func assetParamsFieldsMarkdown(out io.Writer) { fmt.Fprintf(out, "\n`asset_params_get` Fields:\n\n") - fieldTableMarkdown(out, logic.AssetParamsFieldNames, logic.AssetParamsFieldTypes, logic.AssetParamsFieldDocs) + fieldTableMarkdown(out, logic.AssetParamsFieldNames, logic.AssetParamsFieldTypes, logic.AssetParamsFieldDocs()) } func appParamsFieldsMarkdown(out io.Writer) { fmt.Fprintf(out, "\n`app_params_get` Fields:\n\n") - fieldTableMarkdown(out, logic.AppParamsFieldNames, logic.AppParamsFieldTypes, logic.AppParamsFieldDocs) + fieldTableMarkdown(out, logic.AppParamsFieldNames, logic.AppParamsFieldTypes, logic.AppParamsFieldDocs()) } func ecDsaCurvesMarkdown(out io.Writer) { @@ -373,11 +373,11 @@ func main() { assetholding.Close() assetparams, _ := os.Create("asset_params_fields.md") - fieldTableMarkdown(assetparams, logic.AssetParamsFieldNames, logic.AssetParamsFieldTypes, logic.AssetParamsFieldDocs) + fieldTableMarkdown(assetparams, logic.AssetParamsFieldNames, logic.AssetParamsFieldTypes, logic.AssetParamsFieldDocs()) assetparams.Close() appparams, _ := os.Create("app_params_fields.md") - fieldTableMarkdown(appparams, logic.AppParamsFieldNames, logic.AppParamsFieldTypes, logic.AppParamsFieldDocs) + fieldTableMarkdown(appparams, logic.AppParamsFieldNames, logic.AppParamsFieldTypes, logic.AppParamsFieldDocs()) appparams.Close() langspecjs, _ := os.Create("langspec.json") diff --git a/config/consensus.go b/config/consensus.go index 30a655b1e7..d04fd294f1 100644 --- a/config/consensus.go +++ b/config/consensus.go @@ -1022,6 +1022,11 @@ func initConsensusProtocols() { // Enable App calls to pool budget in grouped transactions vFuture.EnableAppCostPooling = true + + // Enable Inner Transactions, and set maximum number. 0 value is + // disabled. Value > 0 also activates storage of creatable IDs in + // ApplyData, as that is required to support REST API when inner + // transactions are activated. vFuture.MaxInnerTransactions = 16 // Allow 50 app opt ins diff --git a/daemon/algod/api/server/v1/handlers/handlers.go b/daemon/algod/api/server/v1/handlers/handlers.go index f956fb4174..0384e887e8 100644 --- a/daemon/algod/api/server/v1/handlers/handlers.go +++ b/daemon/algod/api/server/v1/handlers/handlers.go @@ -395,7 +395,7 @@ func computeCreatableIndexInPayset(tx node.TxnWithStatus, txnCounter uint64, pay // computeAssetIndexFromTxn returns the created asset index given a confirmed // transaction whose confirmation block is available in the ledger. Note that // 0 is an invalid asset index (they start at 1). -func computeAssetIndexFromTxn(tx node.TxnWithStatus, l *data.Ledger) (aidx uint64) { +func computeAssetIndexFromTxn(tx node.TxnWithStatus, l *data.Ledger) uint64 { // Must have ledger if l == nil { return 0 @@ -413,6 +413,15 @@ func computeAssetIndexFromTxn(tx node.TxnWithStatus, l *data.Ledger) (aidx uint6 return 0 } + aidx := uint64(tx.ApplyData.ConfigAsset) + if aidx > 0 { + return aidx + } + // If there is no ConfigAsset in the ApplyData, it must be a + // transaction before inner transactions were activated. Therefore + // the computeCreatableIndexInPayset function will work properly + // to deduce the aid. Proceed. + // Look up block where transaction was confirmed blk, err := l.Block(tx.ConfirmedRound) if err != nil { @@ -430,7 +439,7 @@ func computeAssetIndexFromTxn(tx node.TxnWithStatus, l *data.Ledger) (aidx uint6 // computeAppIndexFromTxn returns the created app index given a confirmed // transaction whose confirmation block is available in the ledger. Note that // 0 is an invalid asset index (they start at 1). -func computeAppIndexFromTxn(tx node.TxnWithStatus, l *data.Ledger) (aidx uint64) { +func computeAppIndexFromTxn(tx node.TxnWithStatus, l *data.Ledger) uint64 { // Must have ledger if l == nil { return 0 @@ -448,6 +457,15 @@ func computeAppIndexFromTxn(tx node.TxnWithStatus, l *data.Ledger) (aidx uint64) return 0 } + aidx := uint64(tx.ApplyData.ApplicationID) + if aidx > 0 { + return aidx + } + // If there is no ApplicationID in the ApplyData, it must be a + // transaction before inner transactions were activated. Therefore + // the computeCreatableIndexInPayset function will work properly + // to deduce the aidx. Proceed. + // Look up block where transaction was confirmed blk, err := l.Block(tx.ConfirmedRound) if err != nil { diff --git a/daemon/algod/api/server/v2/utils.go b/daemon/algod/api/server/v2/utils.go index 84e7d70a03..6498c575c7 100644 --- a/daemon/algod/api/server/v2/utils.go +++ b/daemon/algod/api/server/v2/utils.go @@ -110,7 +110,7 @@ func computeCreatableIndexInPayset(tx node.TxnWithStatus, txnCounter uint64, pay // computeAssetIndexFromTxn returns the created asset index given a confirmed // transaction whose confirmation block is available in the ledger. Note that // 0 is an invalid asset index (they start at 1). -func computeAssetIndexFromTxn(tx node.TxnWithStatus, l *data.Ledger) (aidx *uint64) { +func computeAssetIndexFromTxn(tx node.TxnWithStatus, l *data.Ledger) *uint64 { // Must have ledger if l == nil { return nil @@ -128,6 +128,15 @@ func computeAssetIndexFromTxn(tx node.TxnWithStatus, l *data.Ledger) (aidx *uint return nil } + aid := uint64(tx.ApplyData.ConfigAsset) + if aid > 0 { + return &aid + } + // If there is no ConfigAsset in the ApplyData, it must be a + // transaction before inner transactions were activated. Therefore + // the computeCreatableIndexInPayset function will work properly + // to deduce the aid. Proceed. + // Look up block where transaction was confirmed blk, err := l.Block(tx.ConfirmedRound) if err != nil { @@ -145,7 +154,7 @@ func computeAssetIndexFromTxn(tx node.TxnWithStatus, l *data.Ledger) (aidx *uint // computeAppIndexFromTxn returns the created app index given a confirmed // transaction whose confirmation block is available in the ledger. Note that // 0 is an invalid asset index (they start at 1). -func computeAppIndexFromTxn(tx node.TxnWithStatus, l *data.Ledger) (aidx *uint64) { +func computeAppIndexFromTxn(tx node.TxnWithStatus, l *data.Ledger) *uint64 { // Must have ledger if l == nil { return nil @@ -163,6 +172,15 @@ func computeAppIndexFromTxn(tx node.TxnWithStatus, l *data.Ledger) (aidx *uint64 return nil } + aid := uint64(tx.ApplyData.ApplicationID) + if aid > 0 { + return &aid + } + // If there is no ApplicationID in the ApplyData, it must be a + // transaction before inner transactions were activated. Therefore + // the computeCreatableIndexInPayset function will work properly + // to deduce the aid. Proceed. + // Look up block where transaction was confirmed blk, err := l.Block(tx.ConfirmedRound) if err != nil { @@ -283,12 +301,12 @@ func convertLogs(txn node.TxnWithStatus) *[][]byte { func convertInners(txn *node.TxnWithStatus) *[]preEncodedTxInfo { inner := make([]preEncodedTxInfo, len(txn.ApplyData.EvalDelta.InnerTxns)) for i, itxn := range txn.ApplyData.EvalDelta.InnerTxns { - inner[i] = convertTxn(&itxn) + inner[i] = convertInnerTxn(&itxn) } return &inner } -func convertTxn(txn *transactions.SignedTxnWithAD) preEncodedTxInfo { +func convertInnerTxn(txn *transactions.SignedTxnWithAD) preEncodedTxInfo { // This copies from handlers.PendingTransactionInformation, with // simplifications because we have a SignedTxnWithAD rather than // TxnWithStatus, and we know this txn has committed. @@ -301,9 +319,10 @@ func convertTxn(txn *transactions.SignedTxnWithAD) preEncodedTxInfo { response.ReceiverRewards = &txn.ApplyData.ReceiverRewards.Raw response.CloseRewards = &txn.ApplyData.CloseRewards.Raw - // Indexes can't be set until we allow acfg or appl - // response.AssetIndex = computeAssetIndexFromTxn(txn, v2.Node.Ledger()) - // response.ApplicationIndex = computeAppIndexFromTxn(txn, v2.Node.Ledger()) + // Since this is an inner txn, we know these indexes will be populated. No + // need to search payset for IDs + response.AssetIndex = numOrNil(uint64(txn.ApplyData.ConfigAsset)) + response.ApplicationIndex = numOrNil(uint64(txn.ApplyData.ApplicationID)) // Deltas, Logs, and Inners can not be set until we allow appl // response.LocalStateDelta, response.GlobalStateDelta = convertToDeltas(txn) diff --git a/data/pools/transactionPool.go b/data/pools/transactionPool.go index 3d7125f5e0..35871e91ab 100644 --- a/data/pools/transactionPool.go +++ b/data/pools/transactionPool.go @@ -539,7 +539,7 @@ func (pool *TransactionPool) isAssemblyTimedOut() bool { // we have no deadline, so no reason to timeout. return false } - generateBlockDuration := generateBlockBaseDuration + time.Duration(pool.pendingBlockEvaluator.TxnCounter())*generateBlockTransactionDuration + generateBlockDuration := generateBlockBaseDuration + time.Duration(pool.pendingBlockEvaluator.PaySetSize())*generateBlockTransactionDuration return time.Now().After(pool.assemblyDeadline.Add(-generateBlockDuration)) } diff --git a/data/transactions/logic/README.md b/data/transactions/logic/README.md index 4a5aae217a..95179f0783 100644 --- a/data/transactions/logic/README.md +++ b/data/transactions/logic/README.md @@ -1,17 +1,23 @@ # Transaction Execution Approval Language (TEAL) TEAL is a bytecode based stack language that executes inside Algorand transactions. TEAL programs can be used to check the parameters of the transaction and approve the transaction as if by a signature. This use of TEAL is called a _LogicSig_. Starting with v2, TEAL programs may -also execute as _Applications_ which are invoked with explicit application call transactions. Programs have read-only access to the transaction they are attached to, transactions in their atomic transaction group, and a few global values. In addition, _Application_ programs have access to limited state that is global to the application and per-account local state for each account that has opted-in to the application. Programs cannot modify or create transactions, only reject or approve them. For both types of program, approval is signaled by finishing with the stack containing a single non-zero uint64 value. +also execute as _Applications_ which are invoked with explicit application call transactions. Programs have read-only access to the transaction they are attached to, transactions in their atomic transaction group, and a few global values. In addition, _Application_ programs have access to limited state that is global to the application and per-account local state for each account that has opted-in to the application. For both types of program, approval is signaled by finishing with the stack containing a single non-zero uint64 value. ## The Stack -The stack starts empty and contains values of either uint64 or bytes (`bytes` are implemented in Go as a []byte slice). Most operations act on the stack, popping arguments from it and pushing results to it. +The stack starts empty and contains values of either uint64 or bytes +(`bytes` are implemented in Go as a []byte slice and may not exceed +4096 bytes in length). Most operations act on the stack, popping +arguments from it and pushing results to it. The maximum stack depth is currently 1000. ## Scratch Space -In addition to the stack there are 256 positions of scratch space, also uint64-bytes union values, accessed by the `load` and `store` ops moving data from or to scratch space, respectively. +In addition to the stack there are 256 positions of scratch space, +also uint64-bytes union values, each initialized as uint64 +zero. Scratch space is acccesed by the `load(s)` and `store(s)` ops +moving data from or to scratch space, respectively. ## Execution Modes @@ -30,14 +36,14 @@ TEAL LogicSigs run in Algorand nodes as part of testing a proposed transaction t If an authorized program executes and finishes with a single non-zero uint64 value on the stack then that program has validated the transaction it is attached to. -The TEAL program has access to data from the transaction it is attached to (`txn` op), any transactions in a transaction group it is part of (`gtxn` op), and a few global values like consensus parameters (`global` op). Some "Args" may be attached to a transaction being validated by a TEAL program. Args are an array of byte strings. A common pattern would be to have the key to unlock some contract as an Arg. Args are recorded on the blockchain and publicly visible when the transaction is submitted to the network. +The TEAL program has access to data from the transaction it is attached to (`txn` op), any transactions in a transaction group it is part of (`gtxn` op), and a few global values like consensus parameters (`global` op). Some "Args" may be attached to a transaction being validated by a TEAL program. Args are an array of byte strings. A common pattern would be to have the key to unlock some contract as an Arg. Args are recorded on the blockchain and publicly visible when the transaction is submitted to the network. These LogicSig Args are _not_ signed. A program can either authorize some delegated action on a normal private key signed or multisig account or be wholly in charge of a contract account. * If the account has signed the program (an ed25519 signature on "Program" concatenated with the program bytes) then if the program returns true the transaction is authorized as if the account had signed it. This allows an account to hand out a signed program so that other users can carry out delegated actions which are approved by the program. * If the SHA512_256 hash of the program (prefixed by "Program") is equal to the transaction Sender address then this is a contract account wholly controlled by the program. No other signature is necessary or possible. The only way to execute a transaction against the contract account is for the program to approve it. -The TEAL bytecode plus the length of any Args must add up to less than 1000 bytes (consensus parameter LogicSigMaxSize). Each TEAL op has an associated cost and the program cost must total less than 20000 (consensus parameter LogicSigMaxCost). Most ops have a cost of 1, but a few slow crypto ops are much higher. Prior to v4, the program's cost was estimated as the static sum of all the opcode costs in the program (whether they were actually executed or not). Beginning with v4, the program's cost is tracked dynamically, while being evaluated. If the program exceeds its budget, it fails. +The TEAL bytecode plus the length of all Args must add up to no more than 1000 bytes (consensus parameter LogicSigMaxSize). Each TEAL op has an associated cost and the program cost must total no more than 20000 (consensus parameter LogicSigMaxCost). Most ops have a cost of 1, but a few slow crypto ops are much higher. Prior to v4, the program's cost was estimated as the static sum of all the opcode costs in the program (whether they were actually executed or not). Beginning with v4, the program's cost is tracked dynamically, while being evaluated. If the program exceeds its budget, it fails. ## Constants @@ -86,7 +92,7 @@ Many programs need only a few dozen instructions. The instruction set has some o This summary is supplemented by more detail in the [opcodes document](TEAL_opcodes.md). -Some operations 'panic' and immediately end execution of the program. +Some operations 'panic' and immediately fail the program. A transaction checked by a program that panics is not valid. A contract account governed by a buggy program might not have a way to get assets back out of it. Code carefully. @@ -107,10 +113,10 @@ For three-argument ops, `A` is the element two below the top, `B` is the penulti | `ecdsa_verify v` | for (data A, signature B, C and pubkey D, E) verify the signature of the data against the pubkey => {0 or 1} | | `ecdsa_pk_recover v` | for (data A, recovery id B, signature C, D) recover a public key => [*... stack*, X, Y] | | `ecdsa_pk_decompress v` | decompress pubkey A into components X, Y => [*... stack*, X, Y] | -| `+` | A plus B. Panic on overflow. | -| `-` | A minus B. Panic if B > A. | -| `/` | A divided by B (truncated division). Panic if B == 0. | -| `*` | A times B. Panic on overflow. | +| `+` | A plus B. Fail on overflow. | +| `-` | A minus B. Fail if B > A. | +| `/` | A divided by B (truncated division). Fail if B == 0. | +| `*` | A times B. Fail on overflow. | | `<` | A less than B => {0 or 1} | | `>` | A greater than B => {0 or 1} | | `<=` | A less than or equal to B => {0 or 1} | @@ -121,14 +127,14 @@ For three-argument ops, `A` is the element two below the top, `B` is the penulti | `shr` | A divided by 2^B | | `sqrt` | The largest integer B such that B^2 <= X | | `bitlen` | The highest set bit in X. If X is a byte-array, it is interpreted as a big-endian unsigned integer. bitlen of 0 is 0, bitlen of 8 is 4 | -| `exp` | A raised to the Bth power. Panic if A == B == 0 and on overflow | +| `exp` | A raised to the Bth power. Fail if A == B == 0 and on overflow | | `==` | A is equal to B => {0 or 1} | | `!=` | A is not equal to B => {0 or 1} | | `!` | X == 0 yields 1; else 0 | | `len` | yields length of byte value X | | `itob` | converts uint64 X to big endian bytes | | `btoi` | converts bytes X as big endian to uint64 | -| `%` | A modulo B. Panic if B == 0. | +| `%` | A modulo B. Fail if B == 0. | | `\|` | A bitwise-or B | | `&` | A bitwise-and B | | `^` | A bitwise-xor B | @@ -136,7 +142,7 @@ For three-argument ops, `A` is the element two below the top, `B` is the penulti | `mulw` | A times B out to 128-bit long result as low (top) and high uint64 values on the stack | | `addw` | A plus B out to 128-bit long result as sum (top) and carry-bit uint64 values on the stack | | `divmodw` | Pop four uint64 values. The deepest two are interpreted as a uint128 dividend (deepest value is high word), the top two are interpreted as a uint128 divisor. Four uint64 values are pushed to the stack. The deepest two are the quotient (deeper value is the high uint64). The top two are the remainder, low bits on top. | -| `expw` | A raised to the Bth power as a 128-bit long result as low (top) and high uint64 values on the stack. Panic if A == B == 0 or if the results exceeds 2^128-1 | +| `expw` | A raised to the Bth power as a 128-bit long result as low (top) and high uint64 values on the stack. Fail if A == B == 0 or if the results exceeds 2^128-1 | | `getbit` | pop a target A (integer or byte-array), and index B. Push the Bth bit of A. | | `setbit` | pop a target A, index B, and bit C. Set the Bth bit of A to C, and push the result | | `getbyte` | pop a byte-array A and integer B. Extract the Bth byte of A and push it as an integer | @@ -146,6 +152,8 @@ For three-argument ops, `A` is the element two below the top, `B` is the penulti These opcodes return portions of byte arrays, accessed by position, in various sizes. +### Byte Array Manipulation + | Op | Description | | --- | --- | | `substring s e` | pop a byte-array A. For immediate values in 0..255 S and E: extract a range of bytes from A starting at S up to but not including E, push the substring result. If E < S, or either is larger than the array length, the program fails | @@ -171,8 +179,8 @@ bytes on outputs. | Op | Description | | --- | --- | | `b+` | A plus B, where A and B are byte-arrays interpreted as big-endian unsigned integers | -| `b-` | A minus B, where A and B are byte-arrays interpreted as big-endian unsigned integers. Panic on underflow. | -| `b/` | A divided by B (truncated division), where A and B are byte-arrays interpreted as big-endian unsigned integers. Panic if B is zero. | +| `b-` | A minus B, where A and B are byte-arrays interpreted as big-endian unsigned integers. Fail on underflow. | +| `b/` | A divided by B (truncated division), where A and B are byte-arrays interpreted as big-endian unsigned integers. Fail if B is zero. | | `b*` | A times B, where A and B are byte-arrays interpreted as big-endian unsigned integers. | | `b<` | A is less than B, where A and B are byte-arrays interpreted as big-endian unsigned integers => { 0 or 1} | | `b>` | A is greater than B, where A and B are byte-arrays interpreted as big-endian unsigned integers => { 0 or 1} | @@ -180,10 +188,10 @@ bytes on outputs. | `b>=` | A is greater than or equal to B, where A and B are byte-arrays interpreted as big-endian unsigned integers => { 0 or 1} | | `b==` | A is equals to B, where A and B are byte-arrays interpreted as big-endian unsigned integers => { 0 or 1} | | `b!=` | A is not equal to B, where A and B are byte-arrays interpreted as big-endian unsigned integers => { 0 or 1} | -| `b%` | A modulo B, where A and B are byte-arrays interpreted as big-endian unsigned integers. Panic if B is zero. | +| `b%` | A modulo B, where A and B are byte-arrays interpreted as big-endian unsigned integers. Fail if B is zero. | These opcodes operate on the bits of byte-array values. The shorter -array is interpeted as though left padded with zeros until it is the +array is interpreted as though left padded with zeros until it is the same length as the other input. The returned values are the same length as the longest input. Therefore, unlike array arithmetic, these results may contain leading zero bytes. @@ -195,16 +203,6 @@ these results may contain leading zero bytes. | `b^` | A bitwise-xor B, where A and B are byte-arrays, zero-left extended to the greater of their lengths | | `b~` | X with all bits inverted | -The following opcodes allow for the construction and submission of -"inner transaction" - -| Op | Description | -| --- | --- | -| `tx_begin` | Begin preparation of a new inner transaction | -| `tx_field f` | Set field F of the current inner transaction to X | -| `tx_submit` | Execute the current inner transaction. Panic on any failure. | - - ### Loading Values Opcodes for getting data onto the stack. @@ -233,6 +231,7 @@ Some of these have immediate data in the byte or bytes after the opcode. | `arg_1` | push LogicSig argument 1 to stack | | `arg_2` | push LogicSig argument 2 to stack | | `arg_3` | push LogicSig argument 3 to stack | +| `args` | push Xth LogicSig argument to stack | | `txn f` | push field F of current transaction to stack | | `gtxn t f` | push field F of the Tth transaction in the current group | | `txna f i` | push Ith value of the array field F of the current transaction | @@ -243,15 +242,14 @@ Some of these have immediate data in the byte or bytes after the opcode. | `gtxnsa f i` | push Ith value of the array field F from the Xth transaction in the current group | | `gtxnsas f` | pop an index A and an index B. push Bth value of the array field F from the Ath transaction in the current group | | `global f` | push value from globals to stack | -| `load i` | copy a value from scratch space to the stack | -| `loads` | copy a value from the Xth scratch space to the stack | +| `load i` | copy a value from scratch space to the stack. All scratch spaces are 0 at program start. | +| `loads` | copy a value from the Xth scratch space to the stack. All scratch spaces are 0 at program start. | | `store i` | pop value X. store X to the Ith scratch space | | `stores` | pop indexes A and B. store B to the Ath scratch space | | `gload t i` | push Ith scratch space index of the Tth transaction in the current group | | `gloads i` | push Ith scratch space index of the Xth transaction in the current group | | `gaid t` | push the ID of the asset or application created in the Tth transaction of the current group | | `gaids` | push the ID of the asset or application created in the Xth transaction of the current group | -| `args` | push Xth LogicSig argument to stack | **Transaction Fields** @@ -315,6 +313,10 @@ Some of these have immediate data in the byte or bytes after the opcode. | 55 | LocalNumByteSlice | uint64 | Number of local state byteslices in ApplicationCall. LogicSigVersion >= 3. | | 56 | ExtraProgramPages | uint64 | Number of additional pages for each of the application's approval and clear state programs. An ExtraProgramPages of 1 means 2048 more total bytes, or 1024 for each program. LogicSigVersion >= 4. | | 57 | Nonparticipation | uint64 | Marks an account nonparticipating for rewards. LogicSigVersion >= 5. | +| 58 | Logs | []byte | Log messages emitted by an application call (itxn only). LogicSigVersion >= 5. | +| 59 | NumLogs | uint64 | Number of Logs (itxn only). LogicSigVersion >= 5. | +| 60 | CreatedAssetID | uint64 | Asset ID allocated by the creation of an ASA (itxn only). LogicSigVersion >= 5. | +| 61 | CreatedApplicationID | uint64 | ApplicationID allocated by the creation of an application (itxn only). LogicSigVersion >= 5. | Additional details in the [opcodes document](TEAL_opcodes.md#txn) on the `txn` op. @@ -333,9 +335,9 @@ Global fields are fields that are common to all the transactions in the group. I | 5 | LogicSigVersion | uint64 | Maximum supported TEAL version. LogicSigVersion >= 2. | | 6 | Round | uint64 | Current round number. LogicSigVersion >= 2. | | 7 | LatestTimestamp | uint64 | Last confirmed block UNIX timestamp. Fails if negative. LogicSigVersion >= 2. | -| 8 | CurrentApplicationID | uint64 | ID of current application executing. Fails if no such application is executing. LogicSigVersion >= 2. | +| 8 | CurrentApplicationID | uint64 | ID of current application executing. Fails in LogicSigs. LogicSigVersion >= 2. | | 9 | CreatorAddress | []byte | Address of the creator of the current application. Fails if no such application is executing. LogicSigVersion >= 3. | -| 10 | CurrentApplicationAddress | []byte | Address that the current application controls. Fails if no such application is executing. LogicSigVersion >= 5. | +| 10 | CurrentApplicationAddress | []byte | Address that the current application controls. Fails in LogicSigs. LogicSigVersion >= 5. | | 11 | GroupID | []byte | ID of the transaction group. 32 zero bytes if the transaction is not part of a group. LogicSigVersion >= 5. | @@ -362,7 +364,7 @@ Asset fields include `AssetHolding` and `AssetParam` fields that are used in the | 8 | AssetReserve | []byte | Reserve address | | 9 | AssetFreeze | []byte | Freeze address | | 10 | AssetClawback | []byte | Clawback address | -| 11 | AssetCreator | []byte | Creator address | +| 11 | AssetCreator | []byte | Creator address. LogicSigVersion >= 5. | **App Fields** @@ -386,7 +388,7 @@ App fields used in the `app_params_get` opcode. | Op | Description | | --- | --- | -| `err` | Error. Panic immediately. This is primarily a fencepost against accidental zero bytes getting compiled into programs. | +| `err` | Error. Fail immediately. This is primarily a fencepost against accidental zero bytes getting compiled into programs. | | `bnz target` | branch to TARGET if value X is not zero | | `bz target` | branch to TARGET if value X is zero | | `b target` | branch unconditionally to TARGET | @@ -395,8 +397,8 @@ App fields used in the `app_params_get` opcode. | `dup` | duplicate last value on stack | | `dup2` | duplicate two last values on stack: A, B -> A, B, A, B | | `dig n` | push the Nth value from the top of the stack. dig 0 is equivalent to dup | -| `cover n` | remove top of stack, and place it deeper in the stack such that N elements are above it | -| `uncover n` | remove the value at depth N in the stack and shift above items down so the Nth deep value is on top of the stack | +| `cover n` | remove top of stack, and place it deeper in the stack such that N elements are above it. Fails if stack depth <= N. | +| `uncover n` | remove the value at depth N in the stack and shift above items down so the Nth deep value is on top of the stack. Fails if stack depth <= N. | | `swap` | swaps two last values on stack: A, B -> B, A | | `select` | selects one of two values based on top-of-stack: A, B, C -> (if C != 0 then B else A) | | `assert` | immediately fail unless value X is a non-zero number | @@ -423,6 +425,42 @@ App fields used in the `app_params_get` opcode. | `app_params_get i` | read from app A params field X (imm arg) => {0 or 1 (top), value} | | `log` | write bytes to log state of the current application | +### Inner Transactions + +The following opcodes allow for "inner transactions". Inner +transactions allow stateful applications to have many of the effects +of a true top-level transaction, programatically. However, they are +different in significant ways. The most important differences are +that they are not signed, and do not appear in the block in the usual +away. Instead, their effects are noted in metadata associated with the +associated top-level application call transaction. An inner +transaction's `Sender` must be the SHA512_256 hash of the application +ID (prefixed by "appID"), or an account that has been rekeyed to that +hash. + +Currently, inner transactions may perform `pay`, `axfer`, `acfg`, and +`afrz` effects. After executing an inner transaction with +`itxn_submit`, the effects of the transaction are visible begining +with the next instruction with, for example, `balance` and +`min_balance` checks. + +Of the transaction Header fields, only a few fields may be set: +`Type`/`TypeEnum`, `Sender`, and `Fee`. For the specific fields of +each transaction types, any field, except `RekeyTo` may be set. This +allows, for example, clawback transactions, asset opt-ins, and asset +creates in addtion to the more common uses of `axfer` and `acfg`. All +fields default to the zero value, except those described under +`itxn_begin`. + +| Op | Description | +| --- | --- | +| `itxn_begin` | Begin preparation of a new inner transaction | +| `itxn_field f` | Set field F of the current inner transaction to X | +| `itxn_submit` | Execute the current inner transaction. Fail if 16 inner transactions have already been executed, or if the transaction itself fails. | +| `itxn f` | push field F of the last inner transaction to stack | +| `itxna f i` | push Ith value of the array field F of the last inner transaction to stack | + + # Assembler Syntax The assembler parses line by line. Ops that just use the stack appear on a line by themselves. Ops that take arguments are the op and then whitespace and then any argument or arguments. @@ -493,7 +531,6 @@ A '[proto-buf style variable length unsigned int](https://developers.google.com/ Design and implementation limitations to be aware of with various versions of TEAL. -* TEAL cannot create or change a transaction, only approve or reject. * Stateless TEAL cannot lookup balances of Algos or other assets. (Standard transaction accounting will apply after TEAL has run and authorized a transaction. A TEAL-approved transaction could still be invalid by other accounting rules just as a standard signed transaction could be invalid. e.g. I can't give away money I don't have.) * TEAL cannot access information in previous blocks. TEAL cannot access most information in other transactions in the current block. (TEAL can access fields of the transaction it is attached to and the transactions in an atomic transaction group.) * TEAL cannot know exactly what round the current transaction will commit in (but it is somewhere in FirstValid through LastValid). diff --git a/data/transactions/logic/README_in.md b/data/transactions/logic/README_in.md index 86b3d2ea88..7521ff1cfc 100644 --- a/data/transactions/logic/README_in.md +++ b/data/transactions/logic/README_in.md @@ -1,17 +1,23 @@ # Transaction Execution Approval Language (TEAL) TEAL is a bytecode based stack language that executes inside Algorand transactions. TEAL programs can be used to check the parameters of the transaction and approve the transaction as if by a signature. This use of TEAL is called a _LogicSig_. Starting with v2, TEAL programs may -also execute as _Applications_ which are invoked with explicit application call transactions. Programs have read-only access to the transaction they are attached to, transactions in their atomic transaction group, and a few global values. In addition, _Application_ programs have access to limited state that is global to the application and per-account local state for each account that has opted-in to the application. Programs cannot modify or create transactions, only reject or approve them. For both types of program, approval is signaled by finishing with the stack containing a single non-zero uint64 value. +also execute as _Applications_ which are invoked with explicit application call transactions. Programs have read-only access to the transaction they are attached to, transactions in their atomic transaction group, and a few global values. In addition, _Application_ programs have access to limited state that is global to the application and per-account local state for each account that has opted-in to the application. For both types of program, approval is signaled by finishing with the stack containing a single non-zero uint64 value. ## The Stack -The stack starts empty and contains values of either uint64 or bytes (`bytes` are implemented in Go as a []byte slice). Most operations act on the stack, popping arguments from it and pushing results to it. +The stack starts empty and contains values of either uint64 or bytes +(`bytes` are implemented in Go as a []byte slice and may not exceed +4096 bytes in length). Most operations act on the stack, popping +arguments from it and pushing results to it. The maximum stack depth is currently 1000. ## Scratch Space -In addition to the stack there are 256 positions of scratch space, also uint64-bytes union values, accessed by the `load` and `store` ops moving data from or to scratch space, respectively. +In addition to the stack there are 256 positions of scratch space, +also uint64-bytes union values, each initialized as uint64 +zero. Scratch space is acccesed by the `load(s)` and `store(s)` ops +moving data from or to scratch space, respectively. ## Execution Modes @@ -30,14 +36,14 @@ TEAL LogicSigs run in Algorand nodes as part of testing a proposed transaction t If an authorized program executes and finishes with a single non-zero uint64 value on the stack then that program has validated the transaction it is attached to. -The TEAL program has access to data from the transaction it is attached to (`txn` op), any transactions in a transaction group it is part of (`gtxn` op), and a few global values like consensus parameters (`global` op). Some "Args" may be attached to a transaction being validated by a TEAL program. Args are an array of byte strings. A common pattern would be to have the key to unlock some contract as an Arg. Args are recorded on the blockchain and publicly visible when the transaction is submitted to the network. +The TEAL program has access to data from the transaction it is attached to (`txn` op), any transactions in a transaction group it is part of (`gtxn` op), and a few global values like consensus parameters (`global` op). Some "Args" may be attached to a transaction being validated by a TEAL program. Args are an array of byte strings. A common pattern would be to have the key to unlock some contract as an Arg. Args are recorded on the blockchain and publicly visible when the transaction is submitted to the network. These LogicSig Args are _not_ signed. A program can either authorize some delegated action on a normal private key signed or multisig account or be wholly in charge of a contract account. * If the account has signed the program (an ed25519 signature on "Program" concatenated with the program bytes) then if the program returns true the transaction is authorized as if the account had signed it. This allows an account to hand out a signed program so that other users can carry out delegated actions which are approved by the program. * If the SHA512_256 hash of the program (prefixed by "Program") is equal to the transaction Sender address then this is a contract account wholly controlled by the program. No other signature is necessary or possible. The only way to execute a transaction against the contract account is for the program to approve it. -The TEAL bytecode plus the length of any Args must add up to less than 1000 bytes (consensus parameter LogicSigMaxSize). Each TEAL op has an associated cost and the program cost must total less than 20000 (consensus parameter LogicSigMaxCost). Most ops have a cost of 1, but a few slow crypto ops are much higher. Prior to v4, the program's cost was estimated as the static sum of all the opcode costs in the program (whether they were actually executed or not). Beginning with v4, the program's cost is tracked dynamically, while being evaluated. If the program exceeds its budget, it fails. +The TEAL bytecode plus the length of all Args must add up to no more than 1000 bytes (consensus parameter LogicSigMaxSize). Each TEAL op has an associated cost and the program cost must total no more than 20000 (consensus parameter LogicSigMaxCost). Most ops have a cost of 1, but a few slow crypto ops are much higher. Prior to v4, the program's cost was estimated as the static sum of all the opcode costs in the program (whether they were actually executed or not). Beginning with v4, the program's cost is tracked dynamically, while being evaluated. If the program exceeds its budget, it fails. ## Constants @@ -63,7 +69,7 @@ Many programs need only a few dozen instructions. The instruction set has some o This summary is supplemented by more detail in the [opcodes document](TEAL_opcodes.md). -Some operations 'panic' and immediately end execution of the program. +Some operations 'panic' and immediately fail the program. A transaction checked by a program that panics is not valid. A contract account governed by a buggy program might not have a way to get assets back out of it. Code carefully. @@ -80,6 +86,8 @@ For three-argument ops, `A` is the element two below the top, `B` is the penulti These opcodes return portions of byte arrays, accessed by position, in various sizes. +### Byte Array Manipulation + @@ Byte_Array_Slicing.md @@ These opcodes take byte-array values that are interpreted as @@ -97,19 +105,13 @@ bytes on outputs. @@ Byte_Array_Arithmetic.md @@ These opcodes operate on the bits of byte-array values. The shorter -array is interpeted as though left padded with zeros until it is the +array is interpreted as though left padded with zeros until it is the same length as the other input. The returned values are the same length as the longest input. Therefore, unlike array arithmetic, these results may contain leading zero bytes. @@ Byte_Array_Logic.md @@ -The following opcodes allow for the construction and submission of -"inner transaction" - -@@ Inner_Transactions.md @@ - - ### Loading Values Opcodes for getting data onto the stack. @@ -152,6 +154,36 @@ App fields used in the `app_params_get` opcode. @@ State_Access.md @@ +### Inner Transactions + +The following opcodes allow for "inner transactions". Inner +transactions allow stateful applications to have many of the effects +of a true top-level transaction, programatically. However, they are +different in significant ways. The most important differences are +that they are not signed, and do not appear in the block in the usual +away. Instead, their effects are noted in metadata associated with the +associated top-level application call transaction. An inner +transaction's `Sender` must be the SHA512_256 hash of the application +ID (prefixed by "appID"), or an account that has been rekeyed to that +hash. + +Currently, inner transactions may perform `pay`, `axfer`, `acfg`, and +`afrz` effects. After executing an inner transaction with +`itxn_submit`, the effects of the transaction are visible begining +with the next instruction with, for example, `balance` and +`min_balance` checks. + +Of the transaction Header fields, only a few fields may be set: +`Type`/`TypeEnum`, `Sender`, and `Fee`. For the specific fields of +each transaction types, any field, except `RekeyTo` may be set. This +allows, for example, clawback transactions, asset opt-ins, and asset +creates in addtion to the more common uses of `axfer` and `acfg`. All +fields default to the zero value, except those described under +`itxn_begin`. + +@@ Inner_Transactions.md @@ + + # Assembler Syntax The assembler parses line by line. Ops that just use the stack appear on a line by themselves. Ops that take arguments are the op and then whitespace and then any argument or arguments. @@ -222,7 +254,6 @@ A '[proto-buf style variable length unsigned int](https://developers.google.com/ Design and implementation limitations to be aware of with various versions of TEAL. -* TEAL cannot create or change a transaction, only approve or reject. * Stateless TEAL cannot lookup balances of Algos or other assets. (Standard transaction accounting will apply after TEAL has run and authorized a transaction. A TEAL-approved transaction could still be invalid by other accounting rules just as a standard signed transaction could be invalid. e.g. I can't give away money I don't have.) * TEAL cannot access information in previous blocks. TEAL cannot access most information in other transactions in the current block. (TEAL can access fields of the transaction it is attached to and the transactions in an atomic transaction group.) * TEAL cannot know exactly what round the current transaction will commit in (but it is somewhere in FirstValid through LastValid). diff --git a/data/transactions/logic/TEAL_opcodes.md b/data/transactions/logic/TEAL_opcodes.md index a487e29086..ec9b69faf8 100644 --- a/data/transactions/logic/TEAL_opcodes.md +++ b/data/transactions/logic/TEAL_opcodes.md @@ -8,7 +8,7 @@ Ops have a 'cost' of 1 unless otherwise specified. - Opcode: 0x00 - Pops: _None_ - Pushes: _None_ -- Error. Panic immediately. This is primarily a fencepost against accidental zero bytes getting compiled into programs. +- Error. Fail immediately. This is primarily a fencepost against accidental zero bytes getting compiled into programs. ## sha256 @@ -109,7 +109,7 @@ S (top) and R elements of a signature, recovery id and data (bottom) are expecte - Opcode: 0x08 - Pops: *... stack*, {uint64 A}, {uint64 B} - Pushes: uint64 -- A plus B. Panic on overflow. +- A plus B. Fail on overflow. Overflow is an error condition which halts execution and fails the transaction. Full precision is available from `addw`. @@ -118,14 +118,14 @@ Overflow is an error condition which halts execution and fails the transaction. - Opcode: 0x09 - Pops: *... stack*, {uint64 A}, {uint64 B} - Pushes: uint64 -- A minus B. Panic if B > A. +- A minus B. Fail if B > A. ## / - Opcode: 0x0a - Pops: *... stack*, {uint64 A}, {uint64 B} - Pushes: uint64 -- A divided by B (truncated division). Panic if B == 0. +- A divided by B (truncated division). Fail if B == 0. `divmodw` is available to divide the two-element values produced by `mulw` and `addw`. @@ -134,7 +134,7 @@ Overflow is an error condition which halts execution and fails the transaction. - Opcode: 0x0b - Pops: *... stack*, {uint64 A}, {uint64 B} - Pushes: uint64 -- A times B. Panic on overflow. +- A times B. Fail on overflow. Overflow is an error condition which halts execution and fails the transaction. Full precision is available from `mulw`. @@ -222,14 +222,14 @@ Overflow is an error condition which halts execution and fails the transaction. - Pushes: uint64 - converts bytes X as big endian to uint64 -`btoi` panics if the input is longer than 8 bytes. +`btoi` fails if the input is longer than 8 bytes. ## % - Opcode: 0x18 - Pops: *... stack*, {uint64 A}, {uint64 B} - Pushes: uint64 -- A modulo B. Panic if B == 0. +- A modulo B. Fail if B == 0. ## | @@ -480,6 +480,10 @@ Overflow is an error condition which halts execution and fails the transaction. | 55 | LocalNumByteSlice | uint64 | Number of local state byteslices in ApplicationCall. LogicSigVersion >= 3. | | 56 | ExtraProgramPages | uint64 | Number of additional pages for each of the application's approval and clear state programs. An ExtraProgramPages of 1 means 2048 more total bytes, or 1024 for each program. LogicSigVersion >= 4. | | 57 | Nonparticipation | uint64 | Marks an account nonparticipating for rewards. LogicSigVersion >= 5. | +| 58 | Logs | []byte | Log messages emitted by an application call (itxn only). LogicSigVersion >= 5. | +| 59 | NumLogs | uint64 | Number of Logs (itxn only). LogicSigVersion >= 5. | +| 60 | CreatedAssetID | uint64 | Asset ID allocated by the creation of an ASA (itxn only). LogicSigVersion >= 5. | +| 61 | CreatedApplicationID | uint64 | ApplicationID allocated by the creation of an application (itxn only). LogicSigVersion >= 5. | TypeEnum mapping: @@ -516,9 +520,9 @@ FirstValidTime causes the program to fail. The field is reserved for future use. | 5 | LogicSigVersion | uint64 | Maximum supported TEAL version. LogicSigVersion >= 2. | | 6 | Round | uint64 | Current round number. LogicSigVersion >= 2. | | 7 | LatestTimestamp | uint64 | Last confirmed block UNIX timestamp. Fails if negative. LogicSigVersion >= 2. | -| 8 | CurrentApplicationID | uint64 | ID of current application executing. Fails if no such application is executing. LogicSigVersion >= 2. | +| 8 | CurrentApplicationID | uint64 | ID of current application executing. Fails in LogicSigs. LogicSigVersion >= 2. | | 9 | CreatorAddress | []byte | Address of the creator of the current application. Fails if no such application is executing. LogicSigVersion >= 3. | -| 10 | CurrentApplicationAddress | []byte | Address that the current application controls. Fails if no such application is executing. LogicSigVersion >= 5. | +| 10 | CurrentApplicationAddress | []byte | Address that the current application controls. Fails in LogicSigs. LogicSigVersion >= 5. | | 11 | GroupID | []byte | ID of the transaction group. 32 zero bytes if the transaction is not part of a group. LogicSigVersion >= 5. | @@ -536,7 +540,7 @@ for notes on transaction fields available, see `txn`. If this transaction is _i_ - Opcode: 0x34 {uint8 position in scratch space to load from} - Pops: _None_ - Pushes: any -- copy a value from scratch space to the stack +- copy a value from scratch space to the stack. All scratch spaces are 0 at program start. ## store i @@ -628,7 +632,7 @@ for notes on transaction fields available, see `txn`. If top of stack is _i_, `g - Opcode: 0x3e - Pops: *... stack*, uint64 - Pushes: any -- copy a value from the Xth scratch space to the stack +- copy a value from the Xth scratch space to the stack. All scratch spaces are 0 at program start. - LogicSigVersion >= 5 ## stores @@ -737,7 +741,7 @@ See `bnz` for details on how branches work. `b` always jumps to the offset. - Opcode: 0x4e {uint8 depth} - Pops: *... stack*, any - Pushes: any -- remove top of stack, and place it deeper in the stack such that N elements are above it +- remove top of stack, and place it deeper in the stack such that N elements are above it. Fails if stack depth <= N. - LogicSigVersion >= 5 ## uncover n @@ -745,7 +749,7 @@ See `bnz` for details on how branches work. `b` always jumps to the offset. - Opcode: 0x4f {uint8 depth} - Pops: *... stack*, any - Pushes: any -- remove the value at depth N in the stack and shift above items down so the Nth deep value is on top of the stack +- remove the value at depth N in the stack and shift above items down so the Nth deep value is on top of the stack. Fails if stack depth <= N. - LogicSigVersion >= 5 ## concat @@ -756,7 +760,7 @@ See `bnz` for details on how branches work. `b` always jumps to the offset. - pop two byte-arrays A and B and join them, push the result - LogicSigVersion >= 2 -`concat` panics if the result would be greater than 4096 bytes. +`concat` fails if the result would be greater than 4096 bytes. ## substring s e @@ -892,7 +896,7 @@ params: Txn.Accounts offset (or, since v4, an account address that appears in Tx - LogicSigVersion >= 2 - Mode: Application -params: Txn.Accounts offset (or, since v4, an account address that appears in Txn.Accounts or is Txn.Sender), application id (or, since v4, a Txn.ForeignApps offset), state key. Return: did_exist flag (top of the stack, 1 if exist and 0 otherwise), value. The value is zero (of type uint64) if the key does not exist. +params: Txn.Accounts offset (or, since v4, an account address that appears in Txn.Accounts or is Txn.Sender), application id (or, since v4, a Txn.ForeignApps offset), state key. Return: did_exist flag (top of the stack, 1 if the application existed and 0 otherwise), value. The value is zero (of type uint64) if the key does not exist. ## app_global_get @@ -914,7 +918,7 @@ params: state key. Return: value. The value is zero (of type uint64) if the key - LogicSigVersion >= 2 - Mode: Application -params: Txn.ForeignApps offset (or, since v4, an application id that appears in Txn.ForeignApps or is the CurrentApplicationID), state key. Return: did_exist flag (top of the stack, 1 if exist and 0 otherwise), value. The value is zero (of type uint64) if the key does not exist. +params: Txn.ForeignApps offset (or, since v4, an application id that appears in Txn.ForeignApps or is the CurrentApplicationID), state key. Return: did_exist flag (top of the stack, 1 if the application existed and 0 otherwise), value. The value is zero (of type uint64) if the key does not exist. ## app_local_put @@ -979,7 +983,7 @@ Deleting a key which is already absent has no effect on the application global s | 1 | AssetFrozen | uint64 | Is the asset frozen or not | -params: Txn.Accounts offset (or, since v4, an account address that appears in Txn.Accounts or is Txn.Sender), asset id (or, since v4, a Txn.ForeignAssets offset). Return: did_exist flag (1 if exist and 0 otherwise), value. +params: Txn.Accounts offset (or, since v4, an account address that appears in Txn.Accounts or is Txn.Sender), asset id (or, since v4, a Txn.ForeignAssets offset). Return: did_exist flag (1 if the asset existed and 0 otherwise), value. ## asset_params_get i @@ -1005,10 +1009,10 @@ params: Txn.Accounts offset (or, since v4, an account address that appears in Tx | 8 | AssetReserve | []byte | Reserve address | | 9 | AssetFreeze | []byte | Freeze address | | 10 | AssetClawback | []byte | Clawback address | -| 11 | AssetCreator | []byte | Creator address | +| 11 | AssetCreator | []byte | Creator address. LogicSigVersion >= 5. | -params: Before v4, Txn.ForeignAssets offset. Since v4, Txn.ForeignAssets offset or an asset id that appears in Txn.ForeignAssets. Return: did_exist flag (1 if exist and 0 otherwise), value. +params: Before v4, Txn.ForeignAssets offset. Since v4, Txn.ForeignAssets offset or an asset id that appears in Txn.ForeignAssets. Return: did_exist flag (1 if the asset existed and 0 otherwise), value. ## app_params_get i @@ -1034,7 +1038,7 @@ params: Before v4, Txn.ForeignAssets offset. Since v4, Txn.ForeignAssets offset | 8 | AppAddress | []byte | Address for which this application has authority | -params: Txn.ForeignApps offset or an app id that appears in Txn.ForeignApps. Return: did_exist flag (1 if exist and 0 otherwise), value. +params: Txn.ForeignApps offset or an app id that appears in Txn.ForeignApps. Return: did_exist flag (1 if the application existed and 0 otherwise), value. ## min_balance @@ -1127,7 +1131,7 @@ bitlen interprets arrays as big-endian integers, unlike setbit/getbit - Opcode: 0x94 - Pops: *... stack*, {uint64 A}, {uint64 B} - Pushes: uint64 -- A raised to the Bth power. Panic if A == B == 0 and on overflow +- A raised to the Bth power. Fail if A == B == 0 and on overflow - LogicSigVersion >= 4 ## expw @@ -1135,7 +1139,7 @@ bitlen interprets arrays as big-endian integers, unlike setbit/getbit - Opcode: 0x95 - Pops: *... stack*, {uint64 A}, {uint64 B} - Pushes: *... stack*, uint64, uint64 -- A raised to the Bth power as a 128-bit long result as low (top) and high uint64 values on the stack. Panic if A == B == 0 or if the results exceeds 2^128-1 +- A raised to the Bth power as a 128-bit long result as low (top) and high uint64 values on the stack. Fail if A == B == 0 or if the results exceeds 2^128-1 - **Cost**: 10 - LogicSigVersion >= 4 @@ -1153,7 +1157,7 @@ bitlen interprets arrays as big-endian integers, unlike setbit/getbit - Opcode: 0xa1 - Pops: *... stack*, {[]byte A}, {[]byte B} - Pushes: []byte -- A minus B, where A and B are byte-arrays interpreted as big-endian unsigned integers. Panic on underflow. +- A minus B, where A and B are byte-arrays interpreted as big-endian unsigned integers. Fail on underflow. - **Cost**: 10 - LogicSigVersion >= 4 @@ -1162,7 +1166,7 @@ bitlen interprets arrays as big-endian integers, unlike setbit/getbit - Opcode: 0xa2 - Pops: *... stack*, {[]byte A}, {[]byte B} - Pushes: []byte -- A divided by B (truncated division), where A and B are byte-arrays interpreted as big-endian unsigned integers. Panic if B is zero. +- A divided by B (truncated division), where A and B are byte-arrays interpreted as big-endian unsigned integers. Fail if B is zero. - **Cost**: 20 - LogicSigVersion >= 4 @@ -1228,7 +1232,7 @@ bitlen interprets arrays as big-endian integers, unlike setbit/getbit - Opcode: 0xaa - Pops: *... stack*, {[]byte A}, {[]byte B} - Pushes: []byte -- A modulo B, where A and B are byte-arrays interpreted as big-endian unsigned integers. Panic if B is zero. +- A modulo B, where A and B are byte-arrays interpreted as big-endian unsigned integers. Fail if B is zero. - **Cost**: 20 - LogicSigVersion >= 4 @@ -1285,9 +1289,9 @@ bitlen interprets arrays as big-endian integers, unlike setbit/getbit - LogicSigVersion >= 5 - Mode: Application -`log` can be called up to MaxLogCalls times in a program, and log up to a total of 1k bytes. +`log` fails if called more than MaxLogCalls times in a program, or if the sum of logged bytes exceeds 1024 bytes. -## tx_begin +## itxn_begin - Opcode: 0xb1 - Pops: _None_ @@ -1296,7 +1300,9 @@ bitlen interprets arrays as big-endian integers, unlike setbit/getbit - LogicSigVersion >= 5 - Mode: Application -## tx_field f +`itxn_begin` initializes Sender to the application address; Fee to the minimum allowable, taking into account MinTxnFee and credit from overpaying in earlier transactions; FirstValid/LastValid to the values in the top-level transaction, and all other fields to zero values. + +## itxn_field f - Opcode: 0xb2 {uint8 transaction field index} - Pops: *... stack*, any @@ -1305,12 +1311,32 @@ bitlen interprets arrays as big-endian integers, unlike setbit/getbit - LogicSigVersion >= 5 - Mode: Application -## tx_submit +`itxn_field` fails if X is of the wrong type for F, including a byte array of the wrong size for use as an address when F is an address field. `itxn_field` also fails if X is an account or asset that does not appear in `txn.Accounts` or `txn.ForeignAssets` of the top-level transaction. (Setting addresses in asset creation are exempted from this requirement.) + +## itxn_submit - Opcode: 0xb3 - Pops: _None_ - Pushes: _None_ -- Execute the current inner transaction. Panic on any failure. +- Execute the current inner transaction. Fail if 16 inner transactions have already been executed, or if the transaction itself fails. +- LogicSigVersion >= 5 +- Mode: Application + +## itxn f + +- Opcode: 0xb4 {uint8 transaction field index} +- Pops: _None_ +- Pushes: any +- push field F of the last inner transaction to stack +- LogicSigVersion >= 5 +- Mode: Application + +## itxna f i + +- Opcode: 0xb5 {uint8 transaction field index} {uint8 transaction field array index} +- Pops: _None_ +- Pushes: any +- push Ith value of the array field F of the last inner transaction to stack - LogicSigVersion >= 5 - Mode: Application diff --git a/data/transactions/logic/assembler.go b/data/transactions/logic/assembler.go index d9b4ed2b06..58e597ecd7 100644 --- a/data/transactions/logic/assembler.go +++ b/data/transactions/logic/assembler.go @@ -1055,6 +1055,69 @@ func assembleGtxnsas(ops *OpStream, spec *OpSpec, args []string) error { return nil } +// asmItxn delegates to asmItxnOnly or asmItxna depending on number of operands +func asmItxn(ops *OpStream, spec *OpSpec, args []string) error { + if len(args) == 1 { + return asmItxnOnly(ops, spec, args) + } + if len(args) == 2 { + itxna := OpsByName[ops.Version]["itxna"] + return asmItxna(ops, &itxna, args) + } + return ops.errorf("%s expects one or two arguments", spec.Name) +} + +func asmItxnOnly(ops *OpStream, spec *OpSpec, args []string) error { + if len(args) != 1 { + return ops.errorf("%s expects one argument", spec.Name) + } + fs, ok := txnFieldSpecByName[args[0]] + if !ok { + return ops.errorf("%s unknown field: %#v", spec.Name, args[0]) + } + _, ok = txnaFieldSpecByField[fs.field] + if ok { + return ops.errorf("found array field %#v in %s op", args[0], spec.Name) + } + if fs.version > ops.Version { + return ops.errorf("field %#v available in version %d. Missed #pragma version?", args[0], fs.version) + } + ops.pending.WriteByte(spec.Opcode) + ops.pending.WriteByte(uint8(fs.field)) + ops.returns(fs.ftype) + return nil +} + +func asmItxna(ops *OpStream, spec *OpSpec, args []string) error { + if len(args) != 2 { + return ops.errorf("%s expects two immediate arguments", spec.Name) + } + fs, ok := txnFieldSpecByName[args[0]] + if !ok { + return ops.errorf("%s unknown field: %#v", spec.Name, args[0]) + } + _, ok = txnaFieldSpecByField[fs.field] + if !ok { + return ops.errorf("%s unknown field: %#v", spec.Name, args[0]) + } + if fs.version > ops.Version { + return ops.errorf("%s %#v available in version %d. Missed #pragma version?", spec.Name, args[0], fs.version) + } + arrayFieldIdx, err := strconv.ParseUint(args[1], 0, 64) + if err != nil { + return ops.error(err) + } + if arrayFieldIdx > 255 { + return ops.errorf("%s array index beyond 255: %d", spec.Name, arrayFieldIdx) + } + + ops.pending.WriteByte(spec.Opcode) + ops.pending.WriteByte(uint8(fs.field)) + ops.pending.WriteByte(uint8(arrayFieldIdx)) + ops.returns(fs.ftype) + return nil +} + func assembleGlobal(ops *OpStream, spec *OpSpec, args []string) error { if len(args) != 1 { return ops.errorf("%s expects one argument", spec.Name) @@ -2416,7 +2479,7 @@ func checkPushBytes(cx *EvalContext) error { return cx.err } -// This is also used to disassemble gtxns, gtxnsas and txnas +// This is also used to disassemble gtxns, gtxnsas, txnas, itxn func disTxn(dis *disassembleState, spec *OpSpec) (string, error) { lastIdx := dis.pc + 1 if len(dis.program) <= lastIdx { diff --git a/data/transactions/logic/assembler_test.go b/data/transactions/logic/assembler_test.go index 4e3b76a4d8..02a991d4a9 100644 --- a/data/transactions/logic/assembler_test.go +++ b/data/transactions/logic/assembler_test.go @@ -312,9 +312,9 @@ extract16bits log txn Nonparticipation gtxn 0 Nonparticipation -tx_begin -tx_field Sender -tx_submit +itxn_begin +itxn_field Sender +itxn_submit int 1 txnas ApplicationArgs int 0 @@ -339,6 +339,7 @@ byte 0x0123456789abcd dup dup ecdsa_pk_recover Secp256k1 +itxna Logs 3 ` var nonsense = map[uint64]string{ @@ -354,7 +355,7 @@ var compiled = map[uint64]string{ 2: "022008b7a60cf8acd19181cf959a12f8acd19181cf951af8acd19181cf15f8acd191810f01020026050212340c68656c6c6f20776f726c6421208dae2087fbba51304eb02b91f656948397a7946390e8cb70fc9ea4d95f92251d024242047465737400320032013202320328292929292a0431003101310231043105310731083109310a310b310c310d310e310f3111311231133114311533000033000133000233000433000533000733000833000933000a33000b33000c33000d33000e33000f3300113300123300133300143300152d2e0102222324252104082209240a220b230c240d250e230f23102311231223132314181b1c2b171615400003290349483403350222231d4a484848482a50512a63222352410003420000432105602105612105270463484821052b62482b642b65484821052b2106662b21056721072b682b692107210570004848210771004848361c0037001a0031183119311b311d311e311f3120210721051e312131223123312431253126312731283129312a312b312c312d312e312f", 3: "032008b7a60cf8acd19181cf959a12f8acd19181cf951af8acd19181cf15f8acd191810f01020026050212340c68656c6c6f20776f726c6421208dae2087fbba51304eb02b91f656948397a7946390e8cb70fc9ea4d95f92251d024242047465737400320032013202320328292929292a0431003101310231043105310731083109310a310b310c310d310e310f3111311231133114311533000033000133000233000433000533000733000833000933000a33000b33000c33000d33000e33000f3300113300123300133300143300152d2e0102222324252104082209240a220b230c240d250e230f23102311231223132314181b1c2b171615400003290349483403350222231d4a484848482a50512a63222352410003420000432105602105612105270463484821052b62482b642b65484821052b2106662b21056721072b682b692107210570004848210771004848361c0037001a0031183119311b311d311e311f3120210721051e312131223123312431253126312731283129312a312b312c312d312e312f4478222105531421055427042106552105082106564c4d4b02210538212106391c0081e80780046a6f686e", 4: "042004010200b7a60c26040242420c68656c6c6f20776f726c6421208dae2087fbba51304eb02b91f656948397a7946390e8cb70fc9ea4d95f92251d047465737400320032013202320380021234292929292a0431003101310231043105310731083109310a310b310c310d310e310f3111311231133114311533000033000133000233000433000533000733000833000933000a33000b33000c33000d33000e33000f3300113300123300133300143300152d2e01022581f8acd19181cf959a1281f8acd19181cf951a81f8acd19181cf1581f8acd191810f082209240a220b230c240d250e230f23102311231223132314181b1c28171615400003290349483403350222231d4a484848482a50512a632223524100034200004322602261222b634848222862482864286548482228236628226724286828692422700048482471004848361c0037001a0031183119311b311d311e311f312024221e312131223123312431253126312731283129312a312b312c312d312e312f44782522531422542b2355220823564c4d4b0222382123391c0081e80780046a6f686e2281d00f24231f880003420001892223902291922394239593a0a1a2a3a4a5a6a7a8a9aaabacadae23af3a00003b003c003d8164", - 5: "052004010002b7a60c26050242420c68656c6c6f20776f726c6421070123456789abcd208dae2087fbba51304eb02b91f656948397a7946390e8cb70fc9ea4d95f92251d047465737400320032013202320380021234292929292b0431003101310231043105310731083109310a310b310c310d310e310f3111311231133114311533000033000133000233000433000533000733000833000933000a33000b33000c33000d33000e33000f3300113300123300133300143300152d2e01022581f8acd19181cf959a1281f8acd19181cf951a81f8acd19181cf1581f8acd191810f082209240a220b230c240d250e230f23102311231223132314181b1c28171615400003290349483403350222231d4a484848482b50512a632223524100034200004322602261222704634848222862482864286548482228246628226723286828692322700048482371004848361c0037001a0031183119311b311d311e311f312023221e312131223123312431253126312731283129312a312b312c312d312e312f447825225314225427042455220824564c4d4b0222382124391c0081e80780046a6f686e2281d00f23241f880003420001892224902291922494249593a0a1a2a3a4a5a6a7a8a9aaabacadae24af3a00003b003c003d816472064e014f012a57000823810858235b235a2359b03139330039b1b200b322c01a23c1001a2323c21a23c3233e233f8120af06002a494905002a49490700", + 5: "052004010002b7a60c26050242420c68656c6c6f20776f726c6421070123456789abcd208dae2087fbba51304eb02b91f656948397a7946390e8cb70fc9ea4d95f92251d047465737400320032013202320380021234292929292b0431003101310231043105310731083109310a310b310c310d310e310f3111311231133114311533000033000133000233000433000533000733000833000933000a33000b33000c33000d33000e33000f3300113300123300133300143300152d2e01022581f8acd19181cf959a1281f8acd19181cf951a81f8acd19181cf1581f8acd191810f082209240a220b230c240d250e230f23102311231223132314181b1c28171615400003290349483403350222231d4a484848482b50512a632223524100034200004322602261222704634848222862482864286548482228246628226723286828692322700048482371004848361c0037001a0031183119311b311d311e311f312023221e312131223123312431253126312731283129312a312b312c312d312e312f447825225314225427042455220824564c4d4b0222382124391c0081e80780046a6f686e2281d00f23241f880003420001892224902291922494249593a0a1a2a3a4a5a6a7a8a9aaabacadae24af3a00003b003c003d816472064e014f012a57000823810858235b235a2359b03139330039b1b200b322c01a23c1001a2323c21a23c3233e233f8120af06002a494905002a49490700b53a03", } func pseudoOp(opcode string) bool { @@ -1345,6 +1346,10 @@ gtxn 12 Fee txn ExtraProgramPages txn Nonparticipation global CurrentApplicationAddress +itxna Logs 1 +itxn NumLogs +itxn CreatedAssetID +itxn CreatedApplicationID `, AssemblerMaxVersion) for _, globalField := range GlobalFieldNames { if !strings.Contains(text, globalField) { @@ -2261,11 +2266,11 @@ func TestUncoverAsm(t *testing.T) { } func TestTxTypes(t *testing.T) { - testProg(t, "tx_begin; tx_field Sender", 5, expect{2, "tx_field Sender expects 1 stack argument..."}) - testProg(t, "tx_begin; int 1; tx_field Sender", 5, expect{3, "...wanted type []byte got uint64"}) - testProg(t, "tx_begin; byte 0x56127823; tx_field Sender", 5) + testProg(t, "itxn_begin; itxn_field Sender", 5, expect{2, "itxn_field Sender expects 1 stack argument..."}) + testProg(t, "itxn_begin; int 1; itxn_field Sender", 5, expect{3, "...wanted type []byte got uint64"}) + testProg(t, "itxn_begin; byte 0x56127823; itxn_field Sender", 5) - testProg(t, "tx_begin; tx_field Amount", 5, expect{2, "tx_field Amount expects 1 stack argument..."}) - testProg(t, "tx_begin; byte 0x87123376; tx_field Amount", 5, expect{3, "...wanted type uint64 got []byte"}) - testProg(t, "tx_begin; int 1; tx_field Amount", 5) + testProg(t, "itxn_begin; itxn_field Amount", 5, expect{2, "itxn_field Amount expects 1 stack argument..."}) + testProg(t, "itxn_begin; byte 0x87123376; itxn_field Amount", 5, expect{3, "...wanted type uint64 got []byte"}) + testProg(t, "itxn_begin; int 1; itxn_field Amount", 5) } diff --git a/data/transactions/logic/doc.go b/data/transactions/logic/doc.go index cd7b55f677..29742a1fcd 100644 --- a/data/transactions/logic/doc.go +++ b/data/transactions/logic/doc.go @@ -24,7 +24,7 @@ import ( // short description of every op var opDocByName = map[string]string{ - "err": "Error. Panic immediately. This is primarily a fencepost against accidental zero bytes getting compiled into programs.", + "err": "Error. Fail immediately. This is primarily a fencepost against accidental zero bytes getting compiled into programs.", "sha256": "SHA256 hash of value X, yields [32]byte", "keccak256": "Keccak256 hash of value X, yields [32]byte", "sha512_256": "SHA512_256 hash of value X, yields [32]byte", @@ -32,95 +32,107 @@ var opDocByName = map[string]string{ "ecdsa_verify": "for (data A, signature B, C and pubkey D, E) verify the signature of the data against the pubkey => {0 or 1}", "ecdsa_pk_decompress": "decompress pubkey A into components X, Y => [*... stack*, X, Y]", "ecdsa_pk_recover": "for (data A, recovery id B, signature C, D) recover a public key => [*... stack*, X, Y]", - "+": "A plus B. Panic on overflow.", - "-": "A minus B. Panic if B > A.", - "/": "A divided by B (truncated division). Panic if B == 0.", - "*": "A times B. Panic on overflow.", - "<": "A less than B => {0 or 1}", - ">": "A greater than B => {0 or 1}", - "<=": "A less than or equal to B => {0 or 1}", - ">=": "A greater than or equal to B => {0 or 1}", - "&&": "A is not zero and B is not zero => {0 or 1}", - "||": "A is not zero or B is not zero => {0 or 1}", - "==": "A is equal to B => {0 or 1}", - "!=": "A is not equal to B => {0 or 1}", - "!": "X == 0 yields 1; else 0", - "len": "yields length of byte value X", - "itob": "converts uint64 X to big endian bytes", - "btoi": "converts bytes X as big endian to uint64", - "%": "A modulo B. Panic if B == 0.", - "|": "A bitwise-or B", - "&": "A bitwise-and B", - "^": "A bitwise-xor B", - "~": "bitwise invert value X", - "shl": "A times 2^B, modulo 2^64", - "shr": "A divided by 2^B", - "sqrt": "The largest integer B such that B^2 <= X", - "bitlen": "The highest set bit in X. If X is a byte-array, it is interpreted as a big-endian unsigned integer. bitlen of 0 is 0, bitlen of 8 is 4", - "exp": "A raised to the Bth power. Panic if A == B == 0 and on overflow", - "expw": "A raised to the Bth power as a 128-bit long result as low (top) and high uint64 values on the stack. Panic if A == B == 0 or if the results exceeds 2^128-1", - "mulw": "A times B out to 128-bit long result as low (top) and high uint64 values on the stack", - "addw": "A plus B out to 128-bit long result as sum (top) and carry-bit uint64 values on the stack", - "divmodw": "Pop four uint64 values. The deepest two are interpreted as a uint128 dividend (deepest value is high word), the top two are interpreted as a uint128 divisor. Four uint64 values are pushed to the stack. The deepest two are the quotient (deeper value is the high uint64). The top two are the remainder, low bits on top.", - "intcblock": "prepare block of uint64 constants for use by intc", - "intc": "push Ith constant from intcblock to stack", - "intc_0": "push constant 0 from intcblock to stack", - "intc_1": "push constant 1 from intcblock to stack", - "intc_2": "push constant 2 from intcblock to stack", - "intc_3": "push constant 3 from intcblock to stack", - "pushint": "push immediate UINT to the stack as an integer", - "bytecblock": "prepare block of byte-array constants for use by bytec", - "bytec": "push Ith constant from bytecblock to stack", - "bytec_0": "push constant 0 from bytecblock to stack", - "bytec_1": "push constant 1 from bytecblock to stack", - "bytec_2": "push constant 2 from bytecblock to stack", - "bytec_3": "push constant 3 from bytecblock to stack", - "pushbytes": "push the following program bytes to the stack", - "bzero": "push a byte-array of length X, containing all zero bytes", - "arg": "push Nth LogicSig argument to stack", - "arg_0": "push LogicSig argument 0 to stack", - "arg_1": "push LogicSig argument 1 to stack", - "arg_2": "push LogicSig argument 2 to stack", - "arg_3": "push LogicSig argument 3 to stack", - "txn": "push field F of current transaction to stack", - "gtxn": "push field F of the Tth transaction in the current group", - "gtxns": "push field F of the Xth transaction in the current group", - "txna": "push Ith value of the array field F of the current transaction", - "gtxna": "push Ith value of the array field F from the Tth transaction in the current group", - "gtxnsa": "push Ith value of the array field F from the Xth transaction in the current group", - "global": "push value from globals to stack", - "load": "copy a value from scratch space to the stack", - "store": "pop value X. store X to the Ith scratch space", - "loads": "copy a value from the Xth scratch space to the stack", - "stores": "pop indexes A and B. store B to the Ath scratch space", - "gload": "push Ith scratch space index of the Tth transaction in the current group", - "gloads": "push Ith scratch space index of the Xth transaction in the current group", - "gaid": "push the ID of the asset or application created in the Tth transaction of the current group", - "gaids": "push the ID of the asset or application created in the Xth transaction of the current group", - "bnz": "branch to TARGET if value X is not zero", - "bz": "branch to TARGET if value X is zero", - "b": "branch unconditionally to TARGET", - "return": "use last value on stack as success value; end", - "pop": "discard value X from stack", - "dup": "duplicate last value on stack", - "dup2": "duplicate two last values on stack: A, B -> A, B, A, B", - "dig": "push the Nth value from the top of the stack. dig 0 is equivalent to dup", - "cover": "remove top of stack, and place it deeper in the stack such that N elements are above it", - "uncover": "remove the value at depth N in the stack and shift above items down so the Nth deep value is on top of the stack", - "swap": "swaps two last values on stack: A, B -> B, A", - "select": "selects one of two values based on top-of-stack: A, B, C -> (if C != 0 then B else A)", - "concat": "pop two byte-arrays A and B and join them, push the result", - "substring": "pop a byte-array A. For immediate values in 0..255 S and E: extract a range of bytes from A starting at S up to but not including E, push the substring result. If E < S, or either is larger than the array length, the program fails", - "substring3": "pop a byte-array A and two integers B and C. Extract a range of bytes from A starting at B up to but not including C, push the substring result. If C < B, or either is larger than the array length, the program fails", - "getbit": "pop a target A (integer or byte-array), and index B. Push the Bth bit of A.", - "setbit": "pop a target A, index B, and bit C. Set the Bth bit of A to C, and push the result", - "getbyte": "pop a byte-array A and integer B. Extract the Bth byte of A and push it as an integer", - "setbyte": "pop a byte-array A, integer B, and small integer C (between 0..255). Set the Bth byte of A to C, and push the result", - "extract": "pop a byte-array A. For immediate values in 0..255 S and L: extract a range of bytes from A starting at S up to but not including S+L, push the substring result. If L is 0, then extract to the end of the string. If S or S+L is larger than the array length, the program fails", - "extract3": "pop a byte-array A and two integers B and C. Extract a range of bytes from A starting at B up to but not including B+C, push the substring result. If B+C is larger than the array length, the program fails", - "extract16bits": "pop a byte-array A and integer B. Extract a range of bytes from A starting at B up to but not including B+2, convert bytes as big endian and push the uint64 result. If B+2 is larger than the array length, the program fails", - "extract32bits": "pop a byte-array A and integer B. Extract a range of bytes from A starting at B up to but not including B+4, convert bytes as big endian and push the uint64 result. If B+4 is larger than the array length, the program fails", - "extract64bits": "pop a byte-array A and integer B. Extract a range of bytes from A starting at B up to but not including B+8, convert bytes as big endian and push the uint64 result. If B+8 is larger than the array length, the program fails", + + "+": "A plus B. Fail on overflow.", + "-": "A minus B. Fail if B > A.", + "/": "A divided by B (truncated division). Fail if B == 0.", + "*": "A times B. Fail on overflow.", + "<": "A less than B => {0 or 1}", + ">": "A greater than B => {0 or 1}", + "<=": "A less than or equal to B => {0 or 1}", + ">=": "A greater than or equal to B => {0 or 1}", + "&&": "A is not zero and B is not zero => {0 or 1}", + "||": "A is not zero or B is not zero => {0 or 1}", + "==": "A is equal to B => {0 or 1}", + "!=": "A is not equal to B => {0 or 1}", + "!": "X == 0 yields 1; else 0", + "len": "yields length of byte value X", + "itob": "converts uint64 X to big endian bytes", + "btoi": "converts bytes X as big endian to uint64", + "%": "A modulo B. Fail if B == 0.", + "|": "A bitwise-or B", + "&": "A bitwise-and B", + "^": "A bitwise-xor B", + "~": "bitwise invert value X", + "shl": "A times 2^B, modulo 2^64", + "shr": "A divided by 2^B", + "sqrt": "The largest integer B such that B^2 <= X", + "bitlen": "The highest set bit in X. If X is a byte-array, it is interpreted as a big-endian unsigned integer. bitlen of 0 is 0, bitlen of 8 is 4", + "exp": "A raised to the Bth power. Fail if A == B == 0 and on overflow", + "expw": "A raised to the Bth power as a 128-bit long result as low (top) and high uint64 values on the stack. Fail if A == B == 0 or if the results exceeds 2^128-1", + "mulw": "A times B out to 128-bit long result as low (top) and high uint64 values on the stack", + "addw": "A plus B out to 128-bit long result as sum (top) and carry-bit uint64 values on the stack", + "divmodw": "Pop four uint64 values. The deepest two are interpreted as a uint128 dividend (deepest value is high word), the top two are interpreted as a uint128 divisor. Four uint64 values are pushed to the stack. The deepest two are the quotient (deeper value is the high uint64). The top two are the remainder, low bits on top.", + + "intcblock": "prepare block of uint64 constants for use by intc", + "intc": "push Ith constant from intcblock to stack", + "intc_0": "push constant 0 from intcblock to stack", + "intc_1": "push constant 1 from intcblock to stack", + "intc_2": "push constant 2 from intcblock to stack", + "intc_3": "push constant 3 from intcblock to stack", + "pushint": "push immediate UINT to the stack as an integer", + "bytecblock": "prepare block of byte-array constants for use by bytec", + "bytec": "push Ith constant from bytecblock to stack", + "bytec_0": "push constant 0 from bytecblock to stack", + "bytec_1": "push constant 1 from bytecblock to stack", + "bytec_2": "push constant 2 from bytecblock to stack", + "bytec_3": "push constant 3 from bytecblock to stack", + "pushbytes": "push the following program bytes to the stack", + + "bzero": "push a byte-array of length X, containing all zero bytes", + "arg": "push Nth LogicSig argument to stack", + "arg_0": "push LogicSig argument 0 to stack", + "arg_1": "push LogicSig argument 1 to stack", + "arg_2": "push LogicSig argument 2 to stack", + "arg_3": "push LogicSig argument 3 to stack", + "args": "push Xth LogicSig argument to stack", + "txn": "push field F of current transaction to stack", + "gtxn": "push field F of the Tth transaction in the current group", + "gtxns": "push field F of the Xth transaction in the current group", + "txna": "push Ith value of the array field F of the current transaction", + "gtxna": "push Ith value of the array field F from the Tth transaction in the current group", + "gtxnsa": "push Ith value of the array field F from the Xth transaction in the current group", + "txnas": "push Xth value of the array field F of the current transaction", + "gtxnas": "push Xth value of the array field F from the Tth transaction in the current group", + "gtxnsas": "pop an index A and an index B. push Bth value of the array field F from the Ath transaction in the current group", + "itxn": "push field F of the last inner transaction to stack", + "itxna": "push Ith value of the array field F of the last inner transaction to stack", + + "global": "push value from globals to stack", + "load": "copy a value from scratch space to the stack. All scratch spaces are 0 at program start.", + "store": "pop value X. store X to the Ith scratch space", + "loads": "copy a value from the Xth scratch space to the stack. All scratch spaces are 0 at program start.", + "stores": "pop indexes A and B. store B to the Ath scratch space", + "gload": "push Ith scratch space index of the Tth transaction in the current group", + "gloads": "push Ith scratch space index of the Xth transaction in the current group", + "gaid": "push the ID of the asset or application created in the Tth transaction of the current group", + "gaids": "push the ID of the asset or application created in the Xth transaction of the current group", + + "bnz": "branch to TARGET if value X is not zero", + "bz": "branch to TARGET if value X is zero", + "b": "branch unconditionally to TARGET", + "return": "use last value on stack as success value; end", + "pop": "discard value X from stack", + "dup": "duplicate last value on stack", + "dup2": "duplicate two last values on stack: A, B -> A, B, A, B", + "dig": "push the Nth value from the top of the stack. dig 0 is equivalent to dup", + "cover": "remove top of stack, and place it deeper in the stack such that N elements are above it. Fails if stack depth <= N.", + "uncover": "remove the value at depth N in the stack and shift above items down so the Nth deep value is on top of the stack. Fails if stack depth <= N.", + "swap": "swaps two last values on stack: A, B -> B, A", + "select": "selects one of two values based on top-of-stack: A, B, C -> (if C != 0 then B else A)", + + "concat": "pop two byte-arrays A and B and join them, push the result", + "substring": "pop a byte-array A. For immediate values in 0..255 S and E: extract a range of bytes from A starting at S up to but not including E, push the substring result. If E < S, or either is larger than the array length, the program fails", + "substring3": "pop a byte-array A and two integers B and C. Extract a range of bytes from A starting at B up to but not including C, push the substring result. If C < B, or either is larger than the array length, the program fails", + "getbit": "pop a target A (integer or byte-array), and index B. Push the Bth bit of A.", + "setbit": "pop a target A, index B, and bit C. Set the Bth bit of A to C, and push the result", + "getbyte": "pop a byte-array A and integer B. Extract the Bth byte of A and push it as an integer", + "setbyte": "pop a byte-array A, integer B, and small integer C (between 0..255). Set the Bth byte of A to C, and push the result", + "extract": "pop a byte-array A. For immediate values in 0..255 S and L: extract a range of bytes from A starting at S up to but not including S+L, push the substring result. If L is 0, then extract to the end of the string. If S or S+L is larger than the array length, the program fails", + "extract3": "pop a byte-array A and two integers B and C. Extract a range of bytes from A starting at B up to but not including B+C, push the substring result. If B+C is larger than the array length, the program fails", + "extract16bits": "pop a byte-array A and integer B. Extract a range of bytes from A starting at B up to but not including B+2, convert bytes as big endian and push the uint64 result. If B+2 is larger than the array length, the program fails", + "extract32bits": "pop a byte-array A and integer B. Extract a range of bytes from A starting at B up to but not including B+4, convert bytes as big endian and push the uint64 result. If B+4 is larger than the array length, the program fails", + "extract64bits": "pop a byte-array A and integer B. Extract a range of bytes from A starting at B up to but not including B+8, convert bytes as big endian and push the uint64 result. If B+8 is larger than the array length, the program fails", "balance": "get balance for account A, in microalgos. The balance is observed after the effects of previous transactions in the group, and after the fee for the current transaction is deducted.", "min_balance": "get minimum required balance for account A, in microalgos. Required balance is affected by [ASA](https://developer.algorand.org/docs/features/asa/#assets-overview) and [App](https://developer.algorand.org/docs/features/asc1/stateful/#minimum-balance-requirement-for-a-smart-contract) usage. When creating or opting into an app, the minimum balance grows before the app code runs, therefore the increase is visible there. When deleting or closing out, the minimum balance decreases after the app executes.", @@ -141,8 +153,8 @@ var opDocByName = map[string]string{ "retsub": "pop the top instruction from the call stack and branch to it", "b+": "A plus B, where A and B are byte-arrays interpreted as big-endian unsigned integers", - "b-": "A minus B, where A and B are byte-arrays interpreted as big-endian unsigned integers. Panic on underflow.", - "b/": "A divided by B (truncated division), where A and B are byte-arrays interpreted as big-endian unsigned integers. Panic if B is zero.", + "b-": "A minus B, where A and B are byte-arrays interpreted as big-endian unsigned integers. Fail on underflow.", + "b/": "A divided by B (truncated division), where A and B are byte-arrays interpreted as big-endian unsigned integers. Fail if B is zero.", "b*": "A times B, where A and B are byte-arrays interpreted as big-endian unsigned integers.", "b<": "A is less than B, where A and B are byte-arrays interpreted as big-endian unsigned integers => { 0 or 1}", "b>": "A is greater than B, where A and B are byte-arrays interpreted as big-endian unsigned integers => { 0 or 1}", @@ -150,21 +162,16 @@ var opDocByName = map[string]string{ "b>=": "A is greater than or equal to B, where A and B are byte-arrays interpreted as big-endian unsigned integers => { 0 or 1}", "b==": "A is equals to B, where A and B are byte-arrays interpreted as big-endian unsigned integers => { 0 or 1}", "b!=": "A is not equal to B, where A and B are byte-arrays interpreted as big-endian unsigned integers => { 0 or 1}", - "b%": "A modulo B, where A and B are byte-arrays interpreted as big-endian unsigned integers. Panic if B is zero.", + "b%": "A modulo B, where A and B are byte-arrays interpreted as big-endian unsigned integers. Fail if B is zero.", "b|": "A bitwise-or B, where A and B are byte-arrays, zero-left extended to the greater of their lengths", "b&": "A bitwise-and B, where A and B are byte-arrays, zero-left extended to the greater of their lengths", "b^": "A bitwise-xor B, where A and B are byte-arrays, zero-left extended to the greater of their lengths", "b~": "X with all bits inverted", - "log": "write bytes to log state of the current application", - "tx_begin": "Begin preparation of a new inner transaction", - "tx_field": "Set field F of the current inner transaction to X", - "tx_submit": "Execute the current inner transaction. Panic on any failure.", - - "txnas": "push Xth value of the array field F of the current transaction", - "gtxnas": "push Xth value of the array field F from the Tth transaction in the current group", - "gtxnsas": "pop an index A and an index B. push Bth value of the array field F from the Ath transaction in the current group", - "args": "push Xth LogicSig argument to stack", + "log": "write bytes to log state of the current application", + "itxn_begin": "Begin preparation of a new inner transaction", + "itxn_field": "Set field F of the current inner transaction to X", + "itxn_submit": "Execute the current inner transaction. Fail if 16 inner transactions have already been executed, or if the transaction itself fails.", } // OpDoc returns a description of the op @@ -173,41 +180,51 @@ func OpDoc(opName string) string { } var opcodeImmediateNotes = map[string]string{ - "intcblock": "{varuint length} [{varuint value}, ...]", - "intc": "{uint8 int constant index}", - "pushint": "{varuint int}", - "bytecblock": "{varuint length} [({varuint value length} bytes), ...]", - "bytec": "{uint8 byte constant index}", - "pushbytes": "{varuint length} {bytes}", - "arg": "{uint8 arg index N}", - "txn": "{uint8 transaction field index}", - "gtxn": "{uint8 transaction group index} {uint8 transaction field index}", - "gtxns": "{uint8 transaction field index}", - "txna": "{uint8 transaction field index} {uint8 transaction field array index}", - "gtxna": "{uint8 transaction group index} {uint8 transaction field index} {uint8 transaction field array index}", - "gtxnsa": "{uint8 transaction field index} {uint8 transaction field array index}", - "global": "{uint8 global field index}", - "bnz": "{int16 branch offset, big endian}", - "bz": "{int16 branch offset, big endian}", - "b": "{int16 branch offset, big endian}", - "callsub": "{int16 branch offset, big endian}", - "load": "{uint8 position in scratch space to load from}", - "store": "{uint8 position in scratch space to store to}", - "gload": "{uint8 transaction group index} {uint8 position in scratch space to load from}", - "gloads": "{uint8 position in scratch space to load from}", - "gaid": "{uint8 transaction group index}", - "substring": "{uint8 start position} {uint8 end position}", - "extract": "{uint8 start position} {uint8 length}", - "dig": "{uint8 depth}", - "cover": "{uint8 depth}", - "uncover": "{uint8 depth}", - "asset_holding_get": "{uint8 asset holding field index}", - "asset_params_get": "{uint8 asset params field index}", - "app_params_get": "{uint8 app params field index}", - "tx_field": "{uint8 transaction field index}", - "txnas": "{uint8 transaction field index}", - "gtxnas": "{uint8 transaction group index} {uint8 transaction field index}", - "gtxnsas": "{uint8 transaction field index}", + "intcblock": "{varuint length} [{varuint value}, ...]", + "intc": "{uint8 int constant index}", + "pushint": "{varuint int}", + "bytecblock": "{varuint length} [({varuint value length} bytes), ...]", + "bytec": "{uint8 byte constant index}", + "pushbytes": "{varuint length} {bytes}", + + "arg": "{uint8 arg index N}", + "global": "{uint8 global field index}", + + "txn": "{uint8 transaction field index}", + "gtxn": "{uint8 transaction group index} {uint8 transaction field index}", + "gtxns": "{uint8 transaction field index}", + "txna": "{uint8 transaction field index} {uint8 transaction field array index}", + "gtxna": "{uint8 transaction group index} {uint8 transaction field index} {uint8 transaction field array index}", + "gtxnsa": "{uint8 transaction field index} {uint8 transaction field array index}", + "txnas": "{uint8 transaction field index}", + "gtxnas": "{uint8 transaction group index} {uint8 transaction field index}", + "gtxnsas": "{uint8 transaction field index}", + + "bnz": "{int16 branch offset, big endian}", + "bz": "{int16 branch offset, big endian}", + "b": "{int16 branch offset, big endian}", + "callsub": "{int16 branch offset, big endian}", + + "load": "{uint8 position in scratch space to load from}", + "store": "{uint8 position in scratch space to store to}", + "gload": "{uint8 transaction group index} {uint8 position in scratch space to load from}", + "gloads": "{uint8 position in scratch space to load from}", + "gaid": "{uint8 transaction group index}", + + "substring": "{uint8 start position} {uint8 end position}", + "extract": "{uint8 start position} {uint8 length}", + "dig": "{uint8 depth}", + "cover": "{uint8 depth}", + "uncover": "{uint8 depth}", + + "asset_holding_get": "{uint8 asset holding field index}", + "asset_params_get": "{uint8 asset params field index}", + "app_params_get": "{uint8 app params field index}", + + "itxn_field": "{uint8 transaction field index}", + "itxn": "{uint8 transaction field index}", + "itxna": "{uint8 transaction field index} {uint8 transaction field array index}", + "ecdsa_verify": "{uint8 curve index}", "ecdsa_pk_decompress": "{uint8 curve index}", "ecdsa_pk_recover": "{uint8 curve index}", @@ -242,8 +259,8 @@ var opDocExtras = map[string]string{ "gloads": "`gloads` fails unless the requested transaction is an ApplicationCall and X < GroupIndex.", "gaid": "`gaid` fails unless the requested transaction created an asset or application and T < GroupIndex.", "gaids": "`gaids` fails unless the requested transaction created an asset or application and X < GroupIndex.", - "btoi": "`btoi` panics if the input is longer than 8 bytes.", - "concat": "`concat` panics if the result would be greater than 4096 bytes.", + "btoi": "`btoi` fails if the input is longer than 8 bytes.", + "concat": "`concat` fails if the result would be greater than 4096 bytes.", "pushbytes": "pushbytes args are not added to the bytecblock during assembly processes", "pushint": "pushint args are not added to the intcblock during assembly processes", "getbit": "see explanation of bit ordering in setbit", @@ -252,16 +269,18 @@ var opDocExtras = map[string]string{ "min_balance": "params: Before v4, Txn.Accounts offset. Since v4, Txn.Accounts offset or an account address that appears in Txn.Accounts or is Txn.Sender). Return: value.", "app_opted_in": "params: Txn.Accounts offset (or, since v4, an account address that appears in Txn.Accounts or is Txn.Sender), application id (or, since v4, a Txn.ForeignApps offset). Return: 1 if opted in and 0 otherwise.", "app_local_get": "params: Txn.Accounts offset (or, since v4, an account address that appears in Txn.Accounts or is Txn.Sender), state key. Return: value. The value is zero (of type uint64) if the key does not exist.", - "app_local_get_ex": "params: Txn.Accounts offset (or, since v4, an account address that appears in Txn.Accounts or is Txn.Sender), application id (or, since v4, a Txn.ForeignApps offset), state key. Return: did_exist flag (top of the stack, 1 if exist and 0 otherwise), value. The value is zero (of type uint64) if the key does not exist.", - "app_global_get_ex": "params: Txn.ForeignApps offset (or, since v4, an application id that appears in Txn.ForeignApps or is the CurrentApplicationID), state key. Return: did_exist flag (top of the stack, 1 if exist and 0 otherwise), value. The value is zero (of type uint64) if the key does not exist.", + "app_local_get_ex": "params: Txn.Accounts offset (or, since v4, an account address that appears in Txn.Accounts or is Txn.Sender), application id (or, since v4, a Txn.ForeignApps offset), state key. Return: did_exist flag (top of the stack, 1 if the application existed and 0 otherwise), value. The value is zero (of type uint64) if the key does not exist.", + "app_global_get_ex": "params: Txn.ForeignApps offset (or, since v4, an application id that appears in Txn.ForeignApps or is the CurrentApplicationID), state key. Return: did_exist flag (top of the stack, 1 if the application existed and 0 otherwise), value. The value is zero (of type uint64) if the key does not exist.", "app_global_get": "params: state key. Return: value. The value is zero (of type uint64) if the key does not exist.", "app_local_put": "params: Txn.Accounts offset (or, since v4, an account address that appears in Txn.Accounts or is Txn.Sender), state key, value.", "app_local_del": "params: Txn.Accounts offset (or, since v4, an account address that appears in Txn.Accounts or is Txn.Sender), state key.\n\nDeleting a key which is already absent has no effect on the application local state. (In particular, it does _not_ cause the program to fail.)", "app_global_del": "params: state key.\n\nDeleting a key which is already absent has no effect on the application global state. (In particular, it does _not_ cause the program to fail.)", - "asset_holding_get": "params: Txn.Accounts offset (or, since v4, an account address that appears in Txn.Accounts or is Txn.Sender), asset id (or, since v4, a Txn.ForeignAssets offset). Return: did_exist flag (1 if exist and 0 otherwise), value.", - "asset_params_get": "params: Before v4, Txn.ForeignAssets offset. Since v4, Txn.ForeignAssets offset or an asset id that appears in Txn.ForeignAssets. Return: did_exist flag (1 if exist and 0 otherwise), value.", - "app_params_get": "params: Txn.ForeignApps offset or an app id that appears in Txn.ForeignApps. Return: did_exist flag (1 if exist and 0 otherwise), value.", - "log": "`log` can be called up to MaxLogCalls times in a program, and log up to a total of 1k bytes.", + "asset_holding_get": "params: Txn.Accounts offset (or, since v4, an account address that appears in Txn.Accounts or is Txn.Sender), asset id (or, since v4, a Txn.ForeignAssets offset). Return: did_exist flag (1 if the asset existed and 0 otherwise), value.", + "asset_params_get": "params: Before v4, Txn.ForeignAssets offset. Since v4, Txn.ForeignAssets offset or an asset id that appears in Txn.ForeignAssets. Return: did_exist flag (1 if the asset existed and 0 otherwise), value.", + "app_params_get": "params: Txn.ForeignApps offset or an app id that appears in Txn.ForeignApps. Return: did_exist flag (1 if the application existed and 0 otherwise), value.", + "log": "`log` fails if called more than MaxLogCalls times in a program, or if the sum of logged bytes exceeds 1024 bytes.", + "itxn_begin": "`itxn_begin` initializes Sender to the application address; Fee to the minimum allowable, taking into account MinTxnFee and credit from overpaying in earlier transactions; FirstValid/LastValid to the values in the top-level transaction, and all other fields to zero values.", + "itxn_field": "`itxn_field` fails if X is of the wrong type for F, including a byte array of the wrong size for use as an address when F is an address field. `itxn_field` also fails if X is an account or asset that does not appear in `txn.Accounts` or `txn.ForeignAssets` of the top-level transaction. (Setting addresses in asset creation are exempted from this requirement.)", } // OpDocExtra returns extra documentation text about an op @@ -269,16 +288,18 @@ func OpDocExtra(opName string) string { return opDocExtras[opName] } -// OpGroups is groupings of ops for documentation purposes. +// OpGroups is groupings of ops for documentation purposes. The order +// here is the order args opcodes are presented, so place related +// opcodes consecutively, even if their opcode values are not. var OpGroups = map[string][]string{ "Arithmetic": {"sha256", "keccak256", "sha512_256", "ed25519verify", "ecdsa_verify", "ecdsa_pk_recover", "ecdsa_pk_decompress", "+", "-", "/", "*", "<", ">", "<=", ">=", "&&", "||", "shl", "shr", "sqrt", "bitlen", "exp", "==", "!=", "!", "len", "itob", "btoi", "%", "|", "&", "^", "~", "mulw", "addw", "divmodw", "expw", "getbit", "setbit", "getbyte", "setbyte", "concat"}, "Byte Array Slicing": {"substring", "substring3", "extract", "extract3", "extract16bits", "extract32bits", "extract64bits"}, "Byte Array Arithmetic": {"b+", "b-", "b/", "b*", "b<", "b>", "b<=", "b>=", "b==", "b!=", "b%"}, "Byte Array Logic": {"b|", "b&", "b^", "b~"}, - "Loading Values": {"intcblock", "intc", "intc_0", "intc_1", "intc_2", "intc_3", "pushint", "bytecblock", "bytec", "bytec_0", "bytec_1", "bytec_2", "bytec_3", "pushbytes", "bzero", "arg", "arg_0", "arg_1", "arg_2", "arg_3", "txn", "gtxn", "txna", "txnas", "gtxna", "gtxnas", "gtxns", "gtxnsa", "gtxnsas", "global", "load", "loads", "store", "stores", "gload", "gloads", "gaid", "gaids", "args"}, + "Loading Values": {"intcblock", "intc", "intc_0", "intc_1", "intc_2", "intc_3", "pushint", "bytecblock", "bytec", "bytec_0", "bytec_1", "bytec_2", "bytec_3", "pushbytes", "bzero", "arg", "arg_0", "arg_1", "arg_2", "arg_3", "args", "txn", "gtxn", "txna", "txnas", "gtxna", "gtxnas", "gtxns", "gtxnsa", "gtxnsas", "global", "load", "loads", "store", "stores", "gload", "gloads", "gaid", "gaids"}, "Flow Control": {"err", "bnz", "bz", "b", "return", "pop", "dup", "dup2", "dig", "cover", "uncover", "swap", "select", "assert", "callsub", "retsub"}, "State Access": {"balance", "min_balance", "app_opted_in", "app_local_get", "app_local_get_ex", "app_global_get", "app_global_get_ex", "app_local_put", "app_global_put", "app_local_del", "app_global_del", "asset_holding_get", "asset_params_get", "app_params_get", "log"}, - "Inner Transactions": {"tx_begin", "tx_field", "tx_submit"}, + "Inner Transactions": {"itxn_begin", "itxn_field", "itxn_submit", "itxn", "itxna"}, } // OpCost indicates the cost of an operation over the range of @@ -346,48 +367,55 @@ func OnCompletionDescription(value uint64) string { const OnCompletionPreamble = "An application transaction must indicate the action to be taken following the execution of its approvalProgram or clearStateProgram. The constants below describe the available actions." var txnFieldDocs = map[string]string{ - "Sender": "32 byte address", - "Fee": "micro-Algos", - "FirstValid": "round number", - "FirstValidTime": "Causes program to fail; reserved for future use", - "LastValid": "round number", - "Note": "Any data up to 1024 bytes", - "Lease": "32 byte lease value", - "Receiver": "32 byte address", - "Amount": "micro-Algos", - "CloseRemainderTo": "32 byte address", - "VotePK": "32 byte address", - "SelectionPK": "32 byte address", - "VoteFirst": "The first round that the participation key is valid.", - "VoteLast": "The last round that the participation key is valid.", - "VoteKeyDilution": "Dilution for the 2-level participation key", - "Nonparticipation": "Marks an account nonparticipating for rewards", - "Type": "Transaction type as bytes", - "TypeEnum": "See table below", - "XferAsset": "Asset ID", - "AssetAmount": "value in Asset's units", - "AssetSender": "32 byte address. Causes clawback of all value of asset from AssetSender if Sender is the Clawback address of the asset.", - "AssetReceiver": "32 byte address", - "AssetCloseTo": "32 byte address", - "GroupIndex": "Position of this transaction within an atomic transaction group. A stand-alone transaction is implicitly element 0 in a group of 1", - "TxID": "The computed ID for this transaction. 32 bytes.", - "ApplicationID": "ApplicationID from ApplicationCall transaction", - "OnCompletion": "ApplicationCall transaction on completion action", - "ApplicationArgs": "Arguments passed to the application in the ApplicationCall transaction", - "NumAppArgs": "Number of ApplicationArgs", - "Accounts": "Accounts listed in the ApplicationCall transaction", - "NumAccounts": "Number of Accounts", - "Assets": "Foreign Assets listed in the ApplicationCall transaction", - "NumAssets": "Number of Assets", - "Applications": "Foreign Apps listed in the ApplicationCall transaction", - "NumApplications": "Number of Applications", - "GlobalNumUint": "Number of global state integers in ApplicationCall", - "GlobalNumByteSlice": "Number of global state byteslices in ApplicationCall", - "LocalNumUint": "Number of local state integers in ApplicationCall", - "LocalNumByteSlice": "Number of local state byteslices in ApplicationCall", - "ApprovalProgram": "Approval program", - "ClearStateProgram": "Clear state program", - "RekeyTo": "32 byte Sender's new AuthAddr", + "Type": "Transaction type as bytes", + "TypeEnum": "See table below", + "Sender": "32 byte address", + "Fee": "micro-Algos", + "FirstValid": "round number", + "FirstValidTime": "Causes program to fail; reserved for future use", + "LastValid": "round number", + "Note": "Any data up to 1024 bytes", + "Lease": "32 byte lease value", + "RekeyTo": "32 byte Sender's new AuthAddr", + + "GroupIndex": "Position of this transaction within an atomic transaction group. A stand-alone transaction is implicitly element 0 in a group of 1", + "TxID": "The computed ID for this transaction. 32 bytes.", + + "Receiver": "32 byte address", + "Amount": "micro-Algos", + "CloseRemainderTo": "32 byte address", + + "VotePK": "32 byte address", + "SelectionPK": "32 byte address", + "VoteFirst": "The first round that the participation key is valid.", + "VoteLast": "The last round that the participation key is valid.", + "VoteKeyDilution": "Dilution for the 2-level participation key", + "Nonparticipation": "Marks an account nonparticipating for rewards", + + "XferAsset": "Asset ID", + "AssetAmount": "value in Asset's units", + "AssetSender": "32 byte address. Causes clawback of all value of asset from AssetSender if Sender is the Clawback address of the asset.", + "AssetReceiver": "32 byte address", + "AssetCloseTo": "32 byte address", + + "ApplicationID": "ApplicationID from ApplicationCall transaction", + "OnCompletion": "ApplicationCall transaction on completion action", + "ApplicationArgs": "Arguments passed to the application in the ApplicationCall transaction", + "NumAppArgs": "Number of ApplicationArgs", + "Accounts": "Accounts listed in the ApplicationCall transaction", + "NumAccounts": "Number of Accounts", + "Assets": "Foreign Assets listed in the ApplicationCall transaction", + "NumAssets": "Number of Assets", + "Applications": "Foreign Apps listed in the ApplicationCall transaction", + "NumApplications": "Number of Applications", + "GlobalNumUint": "Number of global state integers in ApplicationCall", + "GlobalNumByteSlice": "Number of global state byteslices in ApplicationCall", + "LocalNumUint": "Number of local state integers in ApplicationCall", + "LocalNumByteSlice": "Number of local state byteslices in ApplicationCall", + "ApprovalProgram": "Approval program", + "ClearStateProgram": "Clear state program", + "ExtraProgramPages": "Number of additional pages for each of the application's approval and clear state programs. An ExtraProgramPages of 1 means 2048 more total bytes, or 1024 for each program.", + "ConfigAsset": "Asset ID in asset config transaction", "ConfigAssetTotal": "Total number of units of this asset created", "ConfigAssetDecimals": "Number of digits to display after the decimal place when displaying the asset", @@ -400,10 +428,15 @@ var txnFieldDocs = map[string]string{ "ConfigAssetReserve": "32 byte address", "ConfigAssetFreeze": "32 byte address", "ConfigAssetClawback": "32 byte address", - "FreezeAsset": "Asset ID being frozen or un-frozen", - "FreezeAssetAccount": "32 byte address of the account whose asset slot is being frozen or un-frozen", - "FreezeAssetFrozen": "The new frozen value, 0 or 1", - "ExtraProgramPages": "Number of additional pages for each of the application's approval and clear state programs. An ExtraProgramPages of 1 means 2048 more total bytes, or 1024 for each program.", + + "FreezeAsset": "Asset ID being frozen or un-frozen", + "FreezeAssetAccount": "32 byte address of the account whose asset slot is being frozen or un-frozen", + "FreezeAssetFrozen": "The new frozen value, 0 or 1", + + "Logs": "Log messages emitted by an application call (itxn only)", + "NumLogs": "Number of Logs (itxn only)", + "CreatedAssetID": "Asset ID allocated by the creation of an ASA (itxn only)", + "CreatedApplicationID": "ApplicationID allocated by the creation of an application (itxn only)", } // TxnFieldDocs are notes on fields available by `txn` and `gtxn` with extra versioning info if any @@ -420,9 +453,9 @@ var globalFieldDocs = map[string]string{ "LogicSigVersion": "Maximum supported TEAL version", "Round": "Current round number", "LatestTimestamp": "Last confirmed block UNIX timestamp. Fails if negative", - "CurrentApplicationID": "ID of current application executing. Fails if no such application is executing", + "CurrentApplicationID": "ID of current application executing. Fails in LogicSigs", "CreatorAddress": "Address of the creator of the current application. Fails if no such application is executing", - "CurrentApplicationAddress": "Address that the current application controls. Fails if no such application is executing", + "CurrentApplicationAddress": "Address that the current application controls. Fails in LogicSigs", "GroupID": "ID of the transaction group. 32 zero bytes if the transaction is not part of a group.", } @@ -460,8 +493,8 @@ var AssetHoldingFieldDocs = map[string]string{ "AssetFrozen": "Is the asset frozen or not", } -// AssetParamsFieldDocs are notes on fields available in `asset_params_get` -var AssetParamsFieldDocs = map[string]string{ +// assetParamsFieldDocs are notes on fields available in `asset_params_get` +var assetParamsFieldDocs = map[string]string{ "AssetTotal": "Total number of units of this asset", "AssetDecimals": "See AssetParams.Decimals", "AssetDefaultFrozen": "Frozen by default or not", @@ -476,8 +509,13 @@ var AssetParamsFieldDocs = map[string]string{ "AssetCreator": "Creator address", } -// AppParamsFieldDocs are notes on fields available in `app_params_get` -var AppParamsFieldDocs = map[string]string{ +// AssetParamsFieldDocs are notes on fields available in `asset_params_get` with extra versioning info if any +func AssetParamsFieldDocs() map[string]string { + return fieldsDocWithExtra(assetParamsFieldDocs, assetParamsFieldSpecByName) +} + +// appParamsFieldDocs are notes on fields available in `app_params_get` +var appParamsFieldDocs = map[string]string{ "AppApprovalProgram": "Bytecode of Approval Program", "AppClearStateProgram": "Bytecode of Clear State Program", "AppGlobalNumUint": "Number of uint64 values allowed in Global State", @@ -489,6 +527,11 @@ var AppParamsFieldDocs = map[string]string{ "AppAddress": "Address for which this application has authority", } +// AppParamsFieldDocs are notes on fields available in `app_params_get` with extra versioning info if any +func AppParamsFieldDocs() map[string]string { + return fieldsDocWithExtra(appParamsFieldDocs, appParamsFieldSpecByName) +} + // EcdsaCurveDocs are notes on curves available in `ecdsa_` opcodes var EcdsaCurveDocs = map[string]string{ "Secp256k1": "secp256k1 curve", diff --git a/data/transactions/logic/doc_test.go b/data/transactions/logic/doc_test.go index a5ed17ade1..f415016247 100644 --- a/data/transactions/logic/doc_test.go +++ b/data/transactions/logic/doc_test.go @@ -48,12 +48,27 @@ func TestOpDocs(t *testing.T) { require.Len(t, onCompletionDescriptions, len(OnCompletionNames)) require.Len(t, globalFieldDocs, len(GlobalFieldNames)) require.Len(t, AssetHoldingFieldDocs, len(AssetHoldingFieldNames)) - require.Len(t, AssetParamsFieldDocs, len(AssetParamsFieldNames)) - require.Len(t, AppParamsFieldDocs, len(AppParamsFieldNames)) + require.Len(t, assetParamsFieldDocs, len(AssetParamsFieldNames)) + require.Len(t, appParamsFieldDocs, len(AppParamsFieldNames)) require.Len(t, TypeNameDescriptions, len(TxnTypeNames)) require.Len(t, EcdsaCurveDocs, len(EcdsaCurveNames)) } +// TestDocStragglers confirms that we don't have any docs laying +// around for non-existent opcodes, most likely from a rename. +func TestDocStragglers(t *testing.T) { + partitiontest.PartitionTest(t) + + for op := range opDocExtras { + _, ok := opDocByName[op] + require.True(t, ok, "%s is in opDocExtra, but not opDocByName", op) + } + for op := range opcodeImmediateNotes { + _, ok := opDocByName[op] + require.True(t, ok, "%s is in opcodeImmediateNotes, but not opDocByName", op) + } +} + func TestOpGroupCoverage(t *testing.T) { partitiontest.PartitionTest(t) diff --git a/data/transactions/logic/eval.go b/data/transactions/logic/eval.go index dbc898ddfb..aa2744ddc4 100644 --- a/data/transactions/logic/eval.go +++ b/data/transactions/logic/eval.go @@ -115,6 +115,31 @@ func (sv *stackValue) uint() (uint64, error) { return sv.Uint, nil } +func (sv *stackValue) bool() (bool, error) { + u64, err := sv.uint() + if err != nil { + return false, err + } + switch u64 { + case 0: + return false, nil + case 1: + return true, nil + default: + return false, fmt.Errorf("boolean is neither 1 nor 0: %d", u64) + } +} + +func (sv *stackValue) string(limit int) (string, error) { + if sv.Bytes == nil { + return "", errors.New("not a byte array") + } + if len(sv.Bytes) > limit { + return "", errors.New("value is too long") + } + return string(sv.Bytes), nil +} + func stackValueFromTealValue(tv *basics.TealValue) (sv stackValue, err error) { switch tv.Type { case basics.TealBytesType: @@ -324,7 +349,7 @@ type EvalContext struct { version uint64 scratch scratchSpace - subtxn *transactions.SignedTxn // place to build for tx_submit + subtxn *transactions.SignedTxn // place to build for itxn_submit // The transactions Performed() and their effects InnerTxns []transactions.SignedTxnWithAD @@ -1859,7 +1884,8 @@ func TxnFieldToTealValue(txn *transactions.Transaction, groupIndex int, field Tx return basics.TealValue{}, fmt.Errorf("negative groupIndex %d", groupIndex) } cx := EvalContext{EvalParams: EvalParams{GroupIndex: uint64(groupIndex)}} - sv, err := cx.txnFieldToStack(txn, field, arrayFieldIdx, uint64(groupIndex)) + fs := txnFieldSpecByField[field] + sv, err := cx.txnFieldToStack(txn, fs, arrayFieldIdx, uint64(groupIndex)) return sv.toTealValue(), err } @@ -1879,9 +1905,41 @@ func (cx *EvalContext) getTxID(txn *transactions.Transaction, groupIndex uint64) return txid } -func (cx *EvalContext) txnFieldToStack(txn *transactions.Transaction, field TxnField, arrayFieldIdx uint64, groupIndex uint64) (sv stackValue, err error) { +func (cx *EvalContext) itxnFieldToStack(itxn *transactions.SignedTxnWithAD, fs txnFieldSpec, arrayFieldIdx uint64) (sv stackValue, err error) { + if fs.effects { + switch fs.field { + case Logs: + if arrayFieldIdx >= uint64(len(itxn.EvalDelta.Logs)) { + err = fmt.Errorf("invalid Logs index %d", arrayFieldIdx) + return + } + sv.Bytes = nilToEmpty([]byte(itxn.EvalDelta.Logs[arrayFieldIdx])) + case NumLogs: + sv.Uint = uint64(len(itxn.EvalDelta.Logs)) + case CreatedAssetID: + sv.Uint = uint64(itxn.ApplyData.ConfigAsset) + case CreatedApplicationID: + sv.Uint = uint64(itxn.ApplyData.ApplicationID) + default: + err = fmt.Errorf("invalid txn field %d", fs.field) + } + return + } + + if fs.field == GroupIndex || fs.field == TxID { + err = fmt.Errorf("illegal field for inner transaction %s", fs.field) + } else { + sv, err = cx.txnFieldToStack(&itxn.Txn, fs, arrayFieldIdx, 0) + } + return +} + +func (cx *EvalContext) txnFieldToStack(txn *transactions.Transaction, fs txnFieldSpec, arrayFieldIdx uint64, groupIndex uint64) (sv stackValue, err error) { + if fs.effects { + return sv, errors.New("Unable to obtain effects from top-level transactions") + } err = nil - switch field { + switch fs.field { case Sender: sv.Bytes = txn.Sender[:] case Fee: @@ -2031,14 +2089,13 @@ func (cx *EvalContext) txnFieldToStack(txn *transactions.Transaction, field TxnF case ExtraProgramPages: sv.Uint = uint64(txn.ExtraProgramPages) default: - err = fmt.Errorf("invalid txn field %d", field) + err = fmt.Errorf("invalid txn field %d", fs.field) return } - txnField := TxnField(field) - txnFieldType := TxnFieldTypes[txnField] + txnFieldType := TxnFieldTypes[fs.field] if !typecheck(txnFieldType, sv.argType()) { - err = fmt.Errorf("%s expected field type is %s but got %s", txnField.String(), txnFieldType.String(), sv.argType().String()) + err = fmt.Errorf("%s expected field type is %s but got %s", fs.field.String(), txnFieldType.String(), sv.argType().String()) } return } @@ -2055,7 +2112,7 @@ func opTxn(cx *EvalContext) { cx.err = fmt.Errorf("invalid txn field %d", field) return } - sv, err := cx.txnFieldToStack(&cx.Txn.Txn, field, 0, cx.GroupIndex) + sv, err := cx.txnFieldToStack(&cx.Txn.Txn, fs, 0, cx.GroupIndex) if err != nil { cx.err = err return @@ -2076,7 +2133,7 @@ func opTxna(cx *EvalContext) { return } arrayFieldIdx := uint64(cx.program[cx.pc+2]) - sv, err := cx.txnFieldToStack(&cx.Txn.Txn, field, arrayFieldIdx, cx.GroupIndex) + sv, err := cx.txnFieldToStack(&cx.Txn.Txn, fs, arrayFieldIdx, cx.GroupIndex) if err != nil { cx.err = err return @@ -2099,7 +2156,7 @@ func opTxnas(cx *EvalContext) { return } arrayFieldIdx := cx.stack[last].Uint - sv, err := cx.txnFieldToStack(&cx.Txn.Txn, field, arrayFieldIdx, cx.GroupIndex) + sv, err := cx.txnFieldToStack(&cx.Txn.Txn, fs, arrayFieldIdx, cx.GroupIndex) if err != nil { cx.err = err return @@ -2131,7 +2188,7 @@ func opGtxn(cx *EvalContext) { // GroupIndex; asking this when we just specified it is _dumb_, but oh well sv.Uint = uint64(gtxid) } else { - sv, err = cx.txnFieldToStack(tx, field, 0, uint64(gtxid)) + sv, err = cx.txnFieldToStack(tx, fs, 0, uint64(gtxid)) if err != nil { cx.err = err return @@ -2159,7 +2216,7 @@ func opGtxna(cx *EvalContext) { return } arrayFieldIdx := uint64(cx.program[cx.pc+3]) - sv, err := cx.txnFieldToStack(tx, field, arrayFieldIdx, uint64(gtxid)) + sv, err := cx.txnFieldToStack(tx, fs, arrayFieldIdx, uint64(gtxid)) if err != nil { cx.err = err return @@ -2188,7 +2245,7 @@ func opGtxnas(cx *EvalContext) { return } arrayFieldIdx := cx.stack[last].Uint - sv, err := cx.txnFieldToStack(tx, field, arrayFieldIdx, uint64(gtxid)) + sv, err := cx.txnFieldToStack(tx, fs, arrayFieldIdx, uint64(gtxid)) if err != nil { cx.err = err return @@ -2221,7 +2278,7 @@ func opGtxns(cx *EvalContext) { // GroupIndex; asking this when we just specified it is _dumb_, but oh well sv.Uint = gtxid } else { - sv, err = cx.txnFieldToStack(tx, field, 0, gtxid) + sv, err = cx.txnFieldToStack(tx, fs, 0, gtxid) if err != nil { cx.err = err return @@ -2250,7 +2307,7 @@ func opGtxnsa(cx *EvalContext) { return } arrayFieldIdx := uint64(cx.program[cx.pc+2]) - sv, err := cx.txnFieldToStack(tx, field, arrayFieldIdx, gtxid) + sv, err := cx.txnFieldToStack(tx, fs, arrayFieldIdx, gtxid) if err != nil { cx.err = err return @@ -2280,7 +2337,7 @@ func opGtxnsas(cx *EvalContext) { return } arrayFieldIdx := cx.stack[last].Uint - sv, err := cx.txnFieldToStack(tx, field, arrayFieldIdx, gtxid) + sv, err := cx.txnFieldToStack(tx, fs, arrayFieldIdx, gtxid) if err != nil { cx.err = err return @@ -2289,6 +2346,61 @@ func opGtxnsas(cx *EvalContext) { cx.stack = cx.stack[:last] } +func opItxn(cx *EvalContext) { + field := TxnField(cx.program[cx.pc+1]) + fs, ok := txnFieldSpecByField[field] + if !ok || fs.version > cx.version { + cx.err = fmt.Errorf("invalid itxn field %d", field) + return + } + _, ok = txnaFieldSpecByField[field] + if ok { + cx.err = fmt.Errorf("invalid itxn field %d", field) + return + } + + if len(cx.InnerTxns) == 0 { + cx.err = fmt.Errorf("no inner transaction available %d", field) + return + } + + itxn := &cx.InnerTxns[len(cx.InnerTxns)-1] + sv, err := cx.itxnFieldToStack(itxn, fs, 0) + if err != nil { + cx.err = err + return + } + cx.stack = append(cx.stack, sv) +} + +func opItxna(cx *EvalContext) { + field := TxnField(cx.program[cx.pc+1]) + fs, ok := txnFieldSpecByField[field] + if !ok || fs.version > cx.version { + cx.err = fmt.Errorf("invalid itxn field %d", field) + return + } + _, ok = txnaFieldSpecByField[field] + if !ok { + cx.err = fmt.Errorf("itxna unsupported field %d", field) + return + } + arrayFieldIdx := uint64(cx.program[cx.pc+2]) + + if len(cx.InnerTxns) == 0 { + cx.err = fmt.Errorf("no inner transaction available %d", field) + return + } + + itxn := &cx.InnerTxns[len(cx.InnerTxns)-1] + sv, err := cx.itxnFieldToStack(itxn, fs, arrayFieldIdx) + if err != nil { + cx.err = err + return + } + cx.stack = append(cx.stack, sv) +} + func opGaidImpl(cx *EvalContext, groupIdx uint64, opName string) (sv stackValue, err error) { if groupIdx >= uint64(len(cx.TxnGroup)) { err = fmt.Errorf("%s lookup TxnGroup[%d] but it only has %d", opName, groupIdx, len(cx.TxnGroup)) @@ -3566,7 +3678,7 @@ func authorizedSender(cx *EvalContext, addr basics.Address) bool { func opTxBegin(cx *EvalContext) { if cx.subtxn != nil { - cx.err = errors.New("tx_begin without tx_submit") + cx.err = errors.New("itxn_begin without itxn_submit") return } // Start fresh @@ -3581,8 +3693,8 @@ func opTxBegin(cx *EvalContext) { fee := cx.Proto.MinTxnFee if cx.FeeCredit != nil { // Use credit to shrink the fee, but don't change FeeCredit - // here, because they might never tx_submit, or they might - // change the fee. Do it in tx_submit. + // here, because they might never itxn_submit, or they might + // change the fee. Do it in itxn_submit. fee = basics.SubSaturate(fee, *cx.FeeCredit) } cx.subtxn.Txn.Header = transactions.Header{ @@ -3633,7 +3745,7 @@ func (cx *EvalContext) stackIntoTxnField(sv stackValue, fs txnFieldSpec, txn *tr if ok { txn.Type = txType } else { - err = fmt.Errorf("%s is not a valid Type for tx_field", sv.Bytes) + err = fmt.Errorf("%s is not a valid Type for itxn_field", sv.Bytes) } case TypeEnum: var i uint64 @@ -3647,7 +3759,7 @@ func (cx *EvalContext) stackIntoTxnField(sv stackValue, fs txnFieldSpec, txn *tr if ok { txn.Type = txType } else { - err = fmt.Errorf("%s is not a valid Type for tx_field", TxnTypeNames[i]) + err = fmt.Errorf("%s is not a valid Type for itxn_field", TxnTypeNames[i]) } } else { err = fmt.Errorf("%d is not a valid TypeEnum", i) @@ -3665,12 +3777,14 @@ func (cx *EvalContext) stackIntoTxnField(sv stackValue, fs txnFieldSpec, txn *tr // KeyReg not allowed yet, so no fields settable + // Payment case Receiver: txn.Receiver, err = cx.availableAccount(sv) case Amount: txn.Amount.Raw, err = sv.uint() case CloseRemainderTo: txn.CloseRemainderTo, err = cx.availableAccount(sv) + // AssetTransfer case XferAsset: txn.XferAsset, err = cx.availableAsset(sv) case AssetAmount: @@ -3681,29 +3795,69 @@ func (cx *EvalContext) stackIntoTxnField(sv stackValue, fs txnFieldSpec, txn *tr txn.AssetReceiver, err = cx.availableAccount(sv) case AssetCloseTo: txn.AssetCloseTo, err = cx.availableAccount(sv) - - // acfg likely next - - // afrz seems easy but not high demand + // AssetConfig + case ConfigAsset: + txn.ConfigAsset, err = cx.availableAsset(sv) + case ConfigAssetTotal: + txn.AssetParams.Total, err = sv.uint() + case ConfigAssetDecimals: + var decimals uint64 + decimals, err = sv.uint() + if err == nil { + if decimals > uint64(cx.Proto.MaxAssetDecimals) { + err = fmt.Errorf("too many decimals (%d)", decimals) + } else { + txn.AssetParams.Decimals = uint32(decimals) + } + } + case ConfigAssetDefaultFrozen: + txn.AssetParams.DefaultFrozen, err = sv.bool() + case ConfigAssetUnitName: + txn.AssetParams.UnitName, err = sv.string(cx.Proto.MaxAssetUnitNameBytes) + case ConfigAssetName: + txn.AssetParams.AssetName, err = sv.string(cx.Proto.MaxAssetNameBytes) + case ConfigAssetURL: + txn.AssetParams.URL, err = sv.string(cx.Proto.MaxAssetURLBytes) + case ConfigAssetMetadataHash: + if len(sv.Bytes) != 32 { + err = fmt.Errorf("ConfigAssetMetadataHash must be 32 bytes") + } else { + copy(txn.AssetParams.MetadataHash[:], sv.Bytes) + } + case ConfigAssetManager: + txn.AssetParams.Manager, err = sv.address() + case ConfigAssetReserve: + txn.AssetParams.Reserve, err = sv.address() + case ConfigAssetFreeze: + txn.AssetParams.Freeze, err = sv.address() + case ConfigAssetClawback: + txn.AssetParams.Clawback, err = sv.address() + // Freeze + case FreezeAsset: + txn.FreezeAsset, err = cx.availableAsset(sv) + case FreezeAssetAccount: + txn.FreezeAccount, err = cx.availableAccount(sv) + case FreezeAssetFrozen: + txn.AssetFrozen, err = sv.bool() // appl needs to wait. Can't call AVM from AVM. default: - return fmt.Errorf("invalid tx_field %s", fs.field) + return fmt.Errorf("invalid itxn_field %s", fs.field) } return } func opTxField(cx *EvalContext) { if cx.subtxn == nil { - cx.err = errors.New("tx_field without tx_begin") + cx.err = errors.New("itxn_field without itxn_begin") return } last := len(cx.stack) - 1 field := TxnField(cx.program[cx.pc+1]) fs, ok := txnFieldSpecByField[field] if !ok || fs.itxVersion == 0 || fs.itxVersion > cx.version { - cx.err = fmt.Errorf("invalid tx_field field %d", field) + cx.err = fmt.Errorf("invalid itxn_field field %d", field) } sv := cx.stack[last] cx.err = cx.stackIntoTxnField(sv, fs, &cx.subtxn.Txn) @@ -3717,21 +3871,21 @@ func opTxSubmit(cx *EvalContext) { } if cx.subtxn == nil { - cx.err = errors.New("tx_submit without tx_begin") + cx.err = errors.New("itxn_submit without itxn_begin") return } if len(cx.InnerTxns) >= cx.Proto.MaxInnerTransactions { - cx.err = errors.New("tx_submit with MaxInnerTransactions") + cx.err = errors.New("itxn_submit with MaxInnerTransactions") return } // Error out on anything unusual. Allow pay, axfer. switch cx.subtxn.Txn.Type { - case protocol.PaymentTx, protocol.AssetTransferTx: - // only pay and axfer for now + case protocol.PaymentTx, protocol.AssetTransferTx, protocol.AssetConfigTx, protocol.AssetFreezeTx: + // only pay, axfer, acfg, afrz for now default: - cx.err = fmt.Errorf("Invalid inner transaction type %s", cx.subtxn.Txn.Type) + cx.err = fmt.Errorf("Invalid inner transaction type %#v", cx.subtxn.Txn.Type) return } @@ -3765,7 +3919,9 @@ func opTxSubmit(cx *EvalContext) { if cx.FeeCredit != nil && *cx.FeeCredit >= underpaid { *cx.FeeCredit -= underpaid } else { - // This should be impossible until we allow changing the Fee + // We allow changing the fee. One pattern might be for an + // app to unilaterally set its Fee to 0. The idea would be + // that other transactions were supposed to overpay. cx.err = fmt.Errorf("fee too small") return } diff --git a/data/transactions/logic/evalAppTxn_test.go b/data/transactions/logic/evalAppTxn_test.go index bac19afd7f..693e1e82e4 100644 --- a/data/transactions/logic/evalAppTxn_test.go +++ b/data/transactions/logic/evalAppTxn_test.go @@ -21,77 +21,87 @@ import ( "testing" "github.com/algorand/go-algorand/data/basics" + + "github.com/stretchr/testify/require" ) func TestActionTypes(t *testing.T) { ep, ledger := makeSampleEnv() - testApp(t, "tx_submit; int 1;", ep, "tx_submit without tx_begin") - testApp(t, "int pay; tx_field TypeEnum; tx_submit; int 1;", ep, "tx_field without tx_begin") - testApp(t, "tx_begin; tx_submit; int 1;", ep, "Invalid inner transaction type") + testApp(t, "itxn_submit; int 1;", ep, "itxn_submit without itxn_begin") + testApp(t, "int pay; itxn_field TypeEnum; itxn_submit; int 1;", ep, "itxn_field without itxn_begin") + testApp(t, "itxn_begin; itxn_submit; int 1;", ep, "Invalid inner transaction type") // bad type - testApp(t, "tx_begin; byte \"pya\"; tx_field Type; tx_submit; int 1;", ep, "pya is not a valid Type") + testApp(t, "itxn_begin; byte \"pya\"; itxn_field Type; itxn_submit; int 1;", ep, "pya is not a valid Type") // mixed up the int form for the byte form - testApp(t, obfuscate("tx_begin; int pay; tx_field Type; tx_submit; int 1;"), ep, "Type arg not a byte array") + testApp(t, obfuscate("itxn_begin; int pay; itxn_field Type; itxn_submit; int 1;"), ep, "Type arg not a byte array") // or vice versa - testApp(t, obfuscate("tx_begin; byte \"pay\"; tx_field TypeEnum; tx_submit; int 1;"), ep, "not a uint64") + testApp(t, obfuscate("itxn_begin; byte \"pay\"; itxn_field TypeEnum; itxn_submit; int 1;"), ep, "not a uint64") // good types, not alllowed yet - testApp(t, "tx_begin; byte \"keyreg\"; tx_field Type; tx_submit; int 1;", ep, "keyreg is not a valid Type for tx_field") - testApp(t, "tx_begin; byte \"acfg\"; tx_field Type; tx_submit; int 1;", ep, "acfg is not a valid Type for tx_field") - testApp(t, "tx_begin; byte \"afrz\"; tx_field Type; tx_submit; int 1;", ep, "afrz is not a valid Type for tx_field") - testApp(t, "tx_begin; byte \"appl\"; tx_field Type; tx_submit; int 1;", ep, "appl is not a valid Type for tx_field") + testApp(t, "itxn_begin; byte \"keyreg\"; itxn_field Type; itxn_submit; int 1;", ep, "keyreg is not a valid Type for itxn_field") + testApp(t, "itxn_begin; byte \"appl\"; itxn_field Type; itxn_submit; int 1;", ep, "appl is not a valid Type for itxn_field") // same, as enums - testApp(t, "tx_begin; int keyreg; tx_field TypeEnum; tx_submit; int 1;", ep, "keyreg is not a valid Type for tx_field") - testApp(t, "tx_begin; int acfg; tx_field TypeEnum; tx_submit; int 1;", ep, "acfg is not a valid Type for tx_field") - testApp(t, "tx_begin; int afrz; tx_field TypeEnum; tx_submit; int 1;", ep, "afrz is not a valid Type for tx_field") - testApp(t, "tx_begin; int appl; tx_field TypeEnum; tx_submit; int 1;", ep, "appl is not a valid Type for tx_field") - testApp(t, "tx_begin; int 42; tx_field TypeEnum; tx_submit; int 1;", ep, "42 is not a valid TypeEnum") - testApp(t, "tx_begin; int 0; tx_field TypeEnum; tx_submit; int 1;", ep, "0 is not a valid TypeEnum") + testApp(t, "itxn_begin; int keyreg; itxn_field TypeEnum; itxn_submit; int 1;", ep, "keyreg is not a valid Type for itxn_field") + testApp(t, "itxn_begin; int appl; itxn_field TypeEnum; itxn_submit; int 1;", ep, "appl is not a valid Type for itxn_field") + testApp(t, "itxn_begin; int 42; itxn_field TypeEnum; itxn_submit; int 1;", ep, "42 is not a valid TypeEnum") + testApp(t, "itxn_begin; int 0; itxn_field TypeEnum; itxn_submit; int 1;", ep, "0 is not a valid TypeEnum") // "insufficient balance" because app account is charged fee // (defaults make these 0 pay|axfer to zero address, from app account) - testApp(t, "tx_begin; byte \"pay\"; tx_field Type; tx_submit; int 1;", ep, "insufficient balance") - testApp(t, "tx_begin; byte \"axfer\"; tx_field Type; tx_submit; int 1;", ep, "insufficient balance") - testApp(t, "tx_begin; int pay; tx_field TypeEnum; tx_submit; int 1;", ep, "insufficient balance") - testApp(t, "tx_begin; int axfer; tx_field TypeEnum; tx_submit; int 1;", ep, "insufficient balance") + testApp(t, "itxn_begin; byte \"pay\"; itxn_field Type; itxn_submit; int 1;", ep, "insufficient balance") + testApp(t, "itxn_begin; byte \"axfer\"; itxn_field Type; itxn_submit; int 1;", ep, "insufficient balance") + testApp(t, "itxn_begin; int pay; itxn_field TypeEnum; itxn_submit; int 1;", ep, "insufficient balance") + testApp(t, "itxn_begin; int axfer; itxn_field TypeEnum; itxn_submit; int 1;", ep, "insufficient balance") + + testApp(t, "itxn_begin; byte \"acfg\"; itxn_field Type; itxn_submit; int 1;", ep, "insufficient balance") + testApp(t, "itxn_begin; byte \"afrz\"; itxn_field Type; itxn_submit; int 1;", ep, "insufficient balance") + testApp(t, "itxn_begin; int acfg; itxn_field TypeEnum; itxn_submit; int 1;", ep, "insufficient balance") + testApp(t, "itxn_begin; int afrz; itxn_field TypeEnum; itxn_submit; int 1;", ep, "insufficient balance") // Establish 888 as the app id, and fund it. ledger.NewApp(ep.Txn.Txn.Receiver, 888, basics.AppParams{}) ledger.NewAccount(basics.AppIndex(888).Address(), 200000) - testApp(t, "tx_begin; byte \"pay\"; tx_field Type; tx_submit; int 1;", ep) - testApp(t, "tx_begin; int pay; tx_field TypeEnum; tx_submit; int 1;", ep) + testApp(t, "itxn_begin; byte \"pay\"; itxn_field Type; itxn_submit; int 1;", ep) + testApp(t, "itxn_begin; int pay; itxn_field TypeEnum; itxn_submit; int 1;", ep) + // Can't submit because we haven't finished setup, but type passes itxn_field + testApp(t, "itxn_begin; byte \"axfer\"; itxn_field Type; int 1;", ep) + testApp(t, "itxn_begin; int axfer; itxn_field TypeEnum; int 1;", ep) + testApp(t, "itxn_begin; byte \"acfg\"; itxn_field Type; int 1;", ep) + testApp(t, "itxn_begin; int acfg; itxn_field TypeEnum; int 1;", ep) + testApp(t, "itxn_begin; byte \"afrz\"; itxn_field Type; int 1;", ep) + testApp(t, "itxn_begin; int afrz; itxn_field TypeEnum; int 1;", ep) } func TestFieldTypes(t *testing.T) { ep, _ := makeSampleEnv() - testApp(t, "tx_begin; byte \"pay\"; tx_field Sender;", ep, "not an address") - testApp(t, obfuscate("tx_begin; int 7; tx_field Receiver;"), ep, "not an address") - testApp(t, "tx_begin; byte \"\"; tx_field CloseRemainderTo;", ep, "not an address") - testApp(t, "tx_begin; byte \"\"; tx_field AssetSender;", ep, "not an address") + testApp(t, "itxn_begin; byte \"pay\"; itxn_field Sender;", ep, "not an address") + testApp(t, obfuscate("itxn_begin; int 7; itxn_field Receiver;"), ep, "not an address") + testApp(t, "itxn_begin; byte \"\"; itxn_field CloseRemainderTo;", ep, "not an address") + testApp(t, "itxn_begin; byte \"\"; itxn_field AssetSender;", ep, "not an address") // can't really tell if it's an addres, so 32 bytes gets further - testApp(t, "tx_begin; byte \"01234567890123456789012345678901\"; tx_field AssetReceiver;", + testApp(t, "itxn_begin; byte \"01234567890123456789012345678901\"; itxn_field AssetReceiver;", ep, "invalid Account reference") // but a b32 string rep is not an account - testApp(t, "tx_begin; byte \"GAYTEMZUGU3DOOBZGAYTEMZUGU3DOOBZGAYTEMZUGU3DOOBZGAYZIZD42E\"; tx_field AssetCloseTo;", + testApp(t, "itxn_begin; byte \"GAYTEMZUGU3DOOBZGAYTEMZUGU3DOOBZGAYTEMZUGU3DOOBZGAYZIZD42E\"; itxn_field AssetCloseTo;", ep, "not an address") - testApp(t, obfuscate("tx_begin; byte \"pay\"; tx_field Fee;"), ep, "not a uint64") - testApp(t, obfuscate("tx_begin; byte 0x01; tx_field Amount;"), ep, "not a uint64") - testApp(t, obfuscate("tx_begin; byte 0x01; tx_field XferAsset;"), ep, "not a uint64") - testApp(t, obfuscate("tx_begin; byte 0x01; tx_field AssetAmount;"), ep, "not a uint64") + testApp(t, obfuscate("itxn_begin; byte \"pay\"; itxn_field Fee;"), ep, "not a uint64") + testApp(t, obfuscate("itxn_begin; byte 0x01; itxn_field Amount;"), ep, "not a uint64") + testApp(t, obfuscate("itxn_begin; byte 0x01; itxn_field XferAsset;"), ep, "not a uint64") + testApp(t, obfuscate("itxn_begin; byte 0x01; itxn_field AssetAmount;"), ep, "not a uint64") } func TestAppPay(t *testing.T) { pay := ` - tx_begin - tx_field Amount - tx_field Receiver - tx_field Sender + itxn_begin + itxn_field Amount + itxn_field Receiver + itxn_field Sender int pay - tx_field TypeEnum - tx_submit + itxn_field TypeEnum + itxn_submit int 1 ` @@ -116,10 +126,10 @@ func TestAppPay(t *testing.T) { testApp(t, "txn Receiver; balance; int 100; ==", ep) close := ` - tx_begin - int pay; tx_field TypeEnum - txn Receiver; tx_field CloseRemainderTo - tx_submit + itxn_begin + int pay; itxn_field TypeEnum + txn Receiver; itxn_field CloseRemainderTo + itxn_submit int 1 ` testApp(t, close, ep) @@ -135,24 +145,24 @@ func TestAppAssetOptIn(t *testing.T) { ledger.NewAccount(basics.AppIndex(888).Address(), 200000) axfer := ` -tx_begin -int axfer; tx_field TypeEnum; -int 25; tx_field XferAsset; -int 2; tx_field AssetAmount; -txn Sender; tx_field AssetReceiver; -tx_submit +itxn_begin +int axfer; itxn_field TypeEnum; +int 25; itxn_field XferAsset; +int 2; itxn_field AssetAmount; +txn Sender; itxn_field AssetReceiver; +itxn_submit int 1 ` testApp(t, axfer, ep, "invalid Asset reference") ep.Txn.Txn.ForeignAssets = append(ep.Txn.Txn.ForeignAssets, 25) testApp(t, axfer, ep, "not opted in") // app account not opted in optin := ` -tx_begin -int axfer; tx_field TypeEnum; -int 25; tx_field XferAsset; -int 0; tx_field AssetAmount; -global CurrentApplicationAddress; tx_field AssetReceiver; -tx_submit +itxn_begin +int axfer; itxn_field TypeEnum; +int 25; itxn_field XferAsset; +int 0; itxn_field AssetAmount; +global CurrentApplicationAddress; itxn_field AssetReceiver; +itxn_submit int 1 ` testApp(t, optin, ep, "does not exist") @@ -174,13 +184,13 @@ int 1 testApp(t, "global CurrentApplicationAddress; int 25; asset_holding_get AssetBalance; assert; int 1; ==", ep) close := ` -tx_begin -int axfer; tx_field TypeEnum; -int 25; tx_field XferAsset; -int 0; tx_field AssetAmount; -txn Sender; tx_field AssetReceiver; -txn Sender; tx_field AssetCloseTo; -tx_submit +itxn_begin +int axfer; itxn_field TypeEnum; +int 25; itxn_field XferAsset; +int 0; itxn_field AssetAmount; +txn Sender; itxn_field AssetReceiver; +txn Sender; itxn_field AssetCloseTo; +itxn_submit int 1 ` testApp(t, close, ep) @@ -189,13 +199,13 @@ int 1 func TestRekeyPay(t *testing.T) { pay := ` - tx_begin - tx_field Amount - tx_field Receiver - tx_field Sender + itxn_begin + itxn_field Amount + itxn_field Receiver + itxn_field Sender int pay - tx_field TypeEnum - tx_submit + itxn_field TypeEnum + itxn_submit ` ep, ledger := makeSampleEnv() @@ -212,12 +222,12 @@ func TestRekeyPay(t *testing.T) { func TestDefaultSender(t *testing.T) { pay := ` - tx_begin - tx_field Amount - tx_field Receiver + itxn_begin + itxn_field Amount + itxn_field Receiver int pay - tx_field TypeEnum - tx_submit + itxn_field TypeEnum + itxn_submit ` ep, ledger := makeSampleEnv() @@ -231,15 +241,15 @@ func TestDefaultSender(t *testing.T) { func TestAppAxfer(t *testing.T) { axfer := ` - tx_begin + itxn_begin int 77 - tx_field XferAsset - tx_field AssetAmount - tx_field AssetReceiver - tx_field Sender + itxn_field XferAsset + itxn_field AssetAmount + itxn_field AssetReceiver + itxn_field Sender int axfer - tx_field TypeEnum - tx_submit + itxn_field TypeEnum + itxn_submit ` ep, ledger := makeSampleEnv() @@ -272,13 +282,13 @@ func TestAppAxfer(t *testing.T) { ep.Txn.Txn.ForeignAssets = save noid := ` - tx_begin - tx_field AssetAmount - tx_field AssetReceiver - tx_field Sender + itxn_begin + itxn_field AssetAmount + itxn_field AssetReceiver + itxn_field Sender int axfer - tx_field TypeEnum - tx_submit + itxn_field TypeEnum + itxn_submit ` testApp(t, "global CurrentApplicationAddress; txn Accounts 1; int 100"+noid+"int 1", ep, fmt.Sprintf("Sender (%s) not opted in to 0", ledger.ApplicationID().Address())) @@ -292,14 +302,14 @@ func TestAppAxfer(t *testing.T) { func TestExtraFields(t *testing.T) { pay := ` - tx_begin - int 7; tx_field AssetAmount; - tx_field Amount - tx_field Receiver - tx_field Sender + itxn_begin + int 7; itxn_field AssetAmount; + itxn_field Amount + itxn_field Receiver + itxn_field Sender int pay - tx_field TypeEnum - tx_submit + itxn_field TypeEnum + itxn_submit ` ep, ledger := makeSampleEnv() @@ -312,34 +322,34 @@ func TestExtraFields(t *testing.T) { func TestBadField(t *testing.T) { pay := ` - tx_begin - int 7; tx_field AssetAmount; - tx_field Amount - tx_field Receiver - tx_field Sender + itxn_begin + int 7; itxn_field AssetAmount; + itxn_field Amount + itxn_field Receiver + itxn_field Sender int pay - tx_field TypeEnum + itxn_field TypeEnum txn Receiver - tx_field RekeyTo // NOT ALLOWED - tx_submit + itxn_field RekeyTo // NOT ALLOWED + itxn_submit ` ep, ledger := makeSampleEnv() ledger.NewApp(ep.Txn.Txn.Receiver, 888, basics.AppParams{}) testApp(t, "global CurrentApplicationAddress; txn Accounts 1; int 100"+pay, ep, - "invalid tx_field RekeyTo") + "invalid itxn_field RekeyTo") } func TestNumInner(t *testing.T) { pay := ` - tx_begin + itxn_begin int 1 - tx_field Amount + itxn_field Amount txn Accounts 1 - tx_field Receiver + itxn_field Receiver int pay - tx_field TypeEnum - tx_submit + itxn_field TypeEnum + itxn_submit ` ep, ledger := makeSampleEnv() @@ -350,5 +360,77 @@ func TestNumInner(t *testing.T) { testApp(t, pay+pay+pay+";int 1", ep) testApp(t, pay+pay+pay+pay+";int 1", ep) // In the sample proto, MaxInnerTransactions = 4 - testApp(t, pay+pay+pay+pay+pay+";int 1", ep, "tx_submit with MaxInnerTransactions") + testApp(t, pay+pay+pay+pay+pay+";int 1", ep, "itxn_submit with MaxInnerTransactions") +} + +func TestAssetCreate(t *testing.T) { + create := ` + itxn_begin + int acfg + itxn_field TypeEnum + int 1000000 + itxn_field ConfigAssetTotal + int 3 + itxn_field ConfigAssetDecimals + byte "oz" + itxn_field ConfigAssetUnitName + byte "Gold" + itxn_field ConfigAssetName + byte "https://gold.rush/" + itxn_field ConfigAssetURL + itxn_submit + int 1 +` + ep, ledger := makeSampleEnv() + ledger.NewApp(ep.Txn.Txn.Receiver, 888, basics.AppParams{}) + testApp(t, create, ep, "insufficient balance") + // Give it enough for fee. Recall that we don't check min balance at this level. + ledger.NewAccount(ledger.ApplicationID().Address(), defaultEvalProto().MinTxnFee) + testApp(t, create, ep) +} + +func TestAssetFreeze(t *testing.T) { + create := ` + itxn_begin + int acfg ; itxn_field TypeEnum + int 1000000 ; itxn_field ConfigAssetTotal + int 3 ; itxn_field ConfigAssetDecimals + byte "oz" ; itxn_field ConfigAssetUnitName + byte "Gold" ; itxn_field ConfigAssetName + byte "https://gold.rush/" ; itxn_field ConfigAssetURL + global CurrentApplicationAddress ; itxn_field ConfigAssetFreeze; + itxn_submit + itxn CreatedAssetID + int 889 + == +` + ep, ledger := makeSampleEnv() + ledger.NewApp(ep.Txn.Txn.Receiver, 888, basics.AppParams{}) + // Give it enough for fees. Recall that we don't check min balance at this level. + ledger.NewAccount(ledger.ApplicationID().Address(), 12*defaultEvalProto().MinTxnFee) + testApp(t, create, ep) + + freeze := ` + itxn_begin + int afrz ; itxn_field TypeEnum + int 889 ; itxn_field FreezeAsset + txn ApplicationArgs 0; btoi ; itxn_field FreezeAssetFrozen + txn Accounts 1 ; itxn_field FreezeAssetAccount + itxn_submit + int 1 +` + testApp(t, freeze, ep, "invalid Asset reference") + ep.Txn.Txn.ForeignAssets = []basics.AssetIndex{basics.AssetIndex(889)} + ep.Txn.Txn.ApplicationArgs = [][]byte{{0x01}} + testApp(t, freeze, ep, "does not hold Asset") + ledger.NewHolding(ep.Txn.Txn.Receiver, 889, 55, false) + testApp(t, freeze, ep) + holding, err := ledger.AssetHolding(ep.Txn.Txn.Receiver, 889) + require.NoError(t, err) + require.Equal(t, true, holding.Frozen) + ep.Txn.Txn.ApplicationArgs = [][]byte{{0x00}} + testApp(t, freeze, ep) + holding, err = ledger.AssetHolding(ep.Txn.Txn.Receiver, 889) + require.NoError(t, err) + require.Equal(t, false, holding.Frozen) } diff --git a/data/transactions/logic/evalStateful_test.go b/data/transactions/logic/evalStateful_test.go index 7a4c5bcba3..f270bd5414 100644 --- a/data/transactions/logic/evalStateful_test.go +++ b/data/transactions/logic/evalStateful_test.go @@ -2347,6 +2347,7 @@ func TestReturnTypes(t *testing.T) { require.NoError(t, err) algoValue := basics.TealValue{Type: basics.TealUintType, Uint: 0x77} ledger.NewLocal(txn.Txn.Receiver, 1, string(key), algoValue) + ledger.NewAccount(basics.AppIndex(1).Address(), 1000000) ep.Ledger = ledger @@ -2388,6 +2389,9 @@ func TestReturnTypes(t *testing.T) { "gtxnas": "gtxnas 0 ApplicationArgs", "gtxnsas": "pop; pop; int 0; int 0; gtxnsas ApplicationArgs", "args": "args", + "itxn": "itxn_begin; int pay; itxn_field TypeEnum; itxn_submit; itxn CreatedAssetID", + // This next one is a cop out. Can't use itxna Logs until we have inner appl + "itxna": "itxn_begin; int pay; itxn_field TypeEnum; itxn_submit; itxn NumLogs", } // these require special input data and tested separately diff --git a/data/transactions/logic/eval_test.go b/data/transactions/logic/eval_test.go index 3a81867dd9..64bf47964f 100644 --- a/data/transactions/logic/eval_test.go +++ b/data/transactions/logic/eval_test.go @@ -55,7 +55,7 @@ func defaultEvalProtoWithVersion(version uint64) config.ConsensusParams { // These must be identical to keep an old backward compat test working MinTxnFee: 1001, MinBalance: 1001, - // Our sample txn is 42-1066 (and that's used as default in tx_begin) + // Our sample txn is 42-1066 (and that's used as default in itxn_begin) MaxTxnLife: 1500, // Strange choices below so that we test against conflating them AppFlatParamsMinBalance: 1002, @@ -65,10 +65,14 @@ func defaultEvalProtoWithVersion(version uint64) config.ConsensusParams { MaxInnerTransactions: 4, - // With the addition of tx_perform, which relies on machinery - // outside logic package for validity checking, we need a more - // realistic set of consensus paramaters. - Asset: true, + // With the addition of itxn_field, itxn_submit, which rely on + // machinery outside logic package for validity checking, we + // need a more realistic set of consensus paramaters. + Asset: true, + MaxAssetNameBytes: 12, + MaxAssetUnitNameBytes: 6, + MaxAssetURLBytes: 32, + MaxAssetDecimals: 4, } } @@ -1520,8 +1524,9 @@ func TestTxn(t *testing.T) { partitiontest.PartitionTest(t) t.Parallel() - for _, txnField := range TxnFieldNames { - if !strings.Contains(testTxnProgramTextV5, txnField) { + for i, txnField := range TxnFieldNames { + fs := txnFieldSpecByField[TxnField(i)] + if !fs.effects && !strings.Contains(testTxnProgramTextV5, txnField) { if txnField != FirstValidTime.String() { t.Errorf("TestTxn missing field %v", txnField) } @@ -2263,6 +2268,9 @@ func TestExtractOp(t *testing.T) { testAccepts(t, "byte 0x123456789abcdef0; int 1; extract32bits; int 0x3456789a; ==", 5) testAccepts(t, "byte 0x123456789abcdef0; int 0; extract64bits; int 0x123456789abcdef0; ==", 5) testAccepts(t, "byte 0x123456789abcdef0; int 0; extract64bits; int 0x123456789abcdef; !=", 5) + + testAccepts(t, `byte "hello"; extract 5 0; byte ""; ==`, 5) + testAccepts(t, `byte "hello"; int 5; int 0; extract3; byte ""; ==`, 5) } func TestExtractFlop(t *testing.T) { @@ -2322,6 +2330,8 @@ func TestLoadStore(t *testing.T) { partitiontest.PartitionTest(t) t.Parallel() + testAccepts(t, "load 3; int 0; ==;", 1) + testAccepts(t, `int 37 int 37 store 1 @@ -2343,6 +2353,7 @@ func TestLoadStoreStack(t *testing.T) { partitiontest.PartitionTest(t) t.Parallel() + testAccepts(t, "int 3; loads; int 0; ==;", 5) testAccepts(t, `int 37 int 1 int 37 diff --git a/data/transactions/logic/fields.go b/data/transactions/logic/fields.go index 03a847ea4c..32d29fd85c 100644 --- a/data/transactions/logic/fields.go +++ b/data/transactions/logic/fields.go @@ -149,6 +149,18 @@ const ( // Nonparticipation Transaction.Nonparticipation Nonparticipation + // Logs Transaction.ApplyData.EvalDelta.Logs + Logs + + // NumLogs len(Logs) + NumLogs + + // CreatedAssetID Transaction.ApplyData.EvalDelta.ConfigAsset + CreatedAssetID + + // CreatedApplicationID Transaction.ApplyData.EvalDelta.ApplicationID + CreatedApplicationID + invalidTxnField // fence for some setup that loops from Sender..invalidTxnField ) @@ -175,73 +187,79 @@ type txnFieldSpec struct { field TxnField ftype StackType version uint64 // When this field become available to txn/gtxn. 0=always - itxVersion uint64 // When this field become available to tx_field. 0=never + itxVersion uint64 // When this field become available to itxn_field. 0=never + effects bool // Is this a field on the "effects"? That is, something in ApplyData } var txnFieldSpecs = []txnFieldSpec{ - {Sender, StackBytes, 0, 5}, - {Fee, StackUint64, 0, 5}, - {FirstValid, StackUint64, 0, 0}, - {FirstValidTime, StackUint64, 0, 0}, - {LastValid, StackUint64, 0, 0}, - {Note, StackBytes, 0, 0}, - {Lease, StackBytes, 0, 0}, - {Receiver, StackBytes, 0, 5}, - {Amount, StackUint64, 0, 5}, - {CloseRemainderTo, StackBytes, 0, 5}, - {VotePK, StackBytes, 0, 0}, - {SelectionPK, StackBytes, 0, 0}, - {VoteFirst, StackUint64, 0, 0}, - {VoteLast, StackUint64, 0, 0}, - {VoteKeyDilution, StackUint64, 0, 0}, - {Type, StackBytes, 0, 5}, - {TypeEnum, StackUint64, 0, 5}, - {XferAsset, StackUint64, 0, 5}, - {AssetAmount, StackUint64, 0, 5}, - {AssetSender, StackBytes, 0, 5}, - {AssetReceiver, StackBytes, 0, 5}, - {AssetCloseTo, StackBytes, 0, 5}, - {GroupIndex, StackUint64, 0, 0}, - {TxID, StackBytes, 0, 0}, - {ApplicationID, StackUint64, 2, 0}, - {OnCompletion, StackUint64, 2, 0}, - {ApplicationArgs, StackBytes, 2, 0}, - {NumAppArgs, StackUint64, 2, 0}, - {Accounts, StackBytes, 2, 0}, - {NumAccounts, StackUint64, 2, 0}, - {ApprovalProgram, StackBytes, 2, 0}, - {ClearStateProgram, StackBytes, 2, 0}, - {RekeyTo, StackBytes, 2, 0}, - {ConfigAsset, StackUint64, 2, 0}, - {ConfigAssetTotal, StackUint64, 2, 0}, - {ConfigAssetDecimals, StackUint64, 2, 0}, - {ConfigAssetDefaultFrozen, StackUint64, 2, 0}, - {ConfigAssetUnitName, StackBytes, 2, 0}, - {ConfigAssetName, StackBytes, 2, 0}, - {ConfigAssetURL, StackBytes, 2, 0}, - {ConfigAssetMetadataHash, StackBytes, 2, 0}, - {ConfigAssetManager, StackBytes, 2, 0}, - {ConfigAssetReserve, StackBytes, 2, 0}, - {ConfigAssetFreeze, StackBytes, 2, 0}, - {ConfigAssetClawback, StackBytes, 2, 0}, - {FreezeAsset, StackUint64, 2, 0}, - {FreezeAssetAccount, StackBytes, 2, 0}, - {FreezeAssetFrozen, StackUint64, 2, 0}, - {Assets, StackUint64, 3, 0}, - {NumAssets, StackUint64, 3, 0}, - {Applications, StackUint64, 3, 0}, - {NumApplications, StackUint64, 3, 0}, - {GlobalNumUint, StackUint64, 3, 0}, - {GlobalNumByteSlice, StackUint64, 3, 0}, - {LocalNumUint, StackUint64, 3, 0}, - {LocalNumByteSlice, StackUint64, 3, 0}, - {ExtraProgramPages, StackUint64, 4, 0}, - {Nonparticipation, StackUint64, 5, 0}, + {Sender, StackBytes, 0, 5, false}, + {Fee, StackUint64, 0, 5, false}, + {FirstValid, StackUint64, 0, 0, false}, + {FirstValidTime, StackUint64, 0, 0, false}, + {LastValid, StackUint64, 0, 0, false}, + {Note, StackBytes, 0, 0, false}, + {Lease, StackBytes, 0, 0, false}, + {Receiver, StackBytes, 0, 5, false}, + {Amount, StackUint64, 0, 5, false}, + {CloseRemainderTo, StackBytes, 0, 5, false}, + {VotePK, StackBytes, 0, 0, false}, + {SelectionPK, StackBytes, 0, 0, false}, + {VoteFirst, StackUint64, 0, 0, false}, + {VoteLast, StackUint64, 0, 0, false}, + {VoteKeyDilution, StackUint64, 0, 0, false}, + {Type, StackBytes, 0, 5, false}, + {TypeEnum, StackUint64, 0, 5, false}, + {XferAsset, StackUint64, 0, 5, false}, + {AssetAmount, StackUint64, 0, 5, false}, + {AssetSender, StackBytes, 0, 5, false}, + {AssetReceiver, StackBytes, 0, 5, false}, + {AssetCloseTo, StackBytes, 0, 5, false}, + {GroupIndex, StackUint64, 0, 0, false}, + {TxID, StackBytes, 0, 0, false}, + {ApplicationID, StackUint64, 2, 0, false}, + {OnCompletion, StackUint64, 2, 0, false}, + {ApplicationArgs, StackBytes, 2, 0, false}, + {NumAppArgs, StackUint64, 2, 0, false}, + {Accounts, StackBytes, 2, 0, false}, + {NumAccounts, StackUint64, 2, 0, false}, + {ApprovalProgram, StackBytes, 2, 0, false}, + {ClearStateProgram, StackBytes, 2, 0, false}, + {RekeyTo, StackBytes, 2, 0, false}, + {ConfigAsset, StackUint64, 2, 5, false}, + {ConfigAssetTotal, StackUint64, 2, 5, false}, + {ConfigAssetDecimals, StackUint64, 2, 5, false}, + {ConfigAssetDefaultFrozen, StackUint64, 2, 5, false}, + {ConfigAssetUnitName, StackBytes, 2, 5, false}, + {ConfigAssetName, StackBytes, 2, 5, false}, + {ConfigAssetURL, StackBytes, 2, 5, false}, + {ConfigAssetMetadataHash, StackBytes, 2, 5, false}, + {ConfigAssetManager, StackBytes, 2, 5, false}, + {ConfigAssetReserve, StackBytes, 2, 5, false}, + {ConfigAssetFreeze, StackBytes, 2, 5, false}, + {ConfigAssetClawback, StackBytes, 2, 5, false}, + {FreezeAsset, StackUint64, 2, 5, false}, + {FreezeAssetAccount, StackBytes, 2, 5, false}, + {FreezeAssetFrozen, StackUint64, 2, 5, false}, + {Assets, StackUint64, 3, 0, false}, + {NumAssets, StackUint64, 3, 0, false}, + {Applications, StackUint64, 3, 0, false}, + {NumApplications, StackUint64, 3, 0, false}, + {GlobalNumUint, StackUint64, 3, 0, false}, + {GlobalNumByteSlice, StackUint64, 3, 0, false}, + {LocalNumUint, StackUint64, 3, 0, false}, + {LocalNumByteSlice, StackUint64, 3, 0, false}, + {ExtraProgramPages, StackUint64, 4, 0, false}, + {Nonparticipation, StackUint64, 5, 0, false}, + + {Logs, StackBytes, 5, 5, true}, + {NumLogs, StackUint64, 5, 5, true}, + {CreatedAssetID, StackUint64, 5, 5, true}, + {CreatedApplicationID, StackUint64, 5, 5, true}, } // TxnaFieldNames are arguments to the 'txna' opcode // It is a subset of txn transaction fields so initialized here in-place -var TxnaFieldNames = []string{ApplicationArgs.String(), Accounts.String(), Assets.String(), Applications.String()} +var TxnaFieldNames = []string{ApplicationArgs.String(), Accounts.String(), Assets.String(), Applications.String(), Logs.String()} // TxnaFieldTypes is StackBytes or StackUint64 parallel to TxnaFieldNames var TxnaFieldTypes = []StackType{ @@ -249,18 +267,23 @@ var TxnaFieldTypes = []StackType{ txnaFieldSpecByField[Accounts].ftype, txnaFieldSpecByField[Assets].ftype, txnaFieldSpecByField[Applications].ftype, + txnaFieldSpecByField[Logs].ftype, } var txnaFieldSpecByField = map[TxnField]txnFieldSpec{ - ApplicationArgs: {ApplicationArgs, StackBytes, 2, 0}, - Accounts: {Accounts, StackBytes, 2, 0}, - Assets: {Assets, StackUint64, 3, 0}, - Applications: {Applications, StackUint64, 3, 0}, + ApplicationArgs: {ApplicationArgs, StackBytes, 2, 0, false}, + Accounts: {Accounts, StackBytes, 2, 0, false}, + Assets: {Assets, StackUint64, 3, 0, false}, + Applications: {Applications, StackUint64, 3, 0, false}, + + Logs: {Logs, StackBytes, 5, 5, true}, } var innerTxnTypes = map[string]protocol.TxType{ string(protocol.PaymentTx): protocol.PaymentTx, string(protocol.AssetTransferTx): protocol.AssetTransferTx, + string(protocol.AssetConfigTx): protocol.AssetConfigTx, + string(protocol.AssetFreezeTx): protocol.AssetFreezeTx, } // TxnTypeNames is the values of Txn.Type in enum order @@ -599,7 +622,7 @@ var appParamsFieldSpecByName appNameSpecMap type appNameSpecMap map[string]appParamsFieldSpec func (s appNameSpecMap) getExtraFor(name string) (extra string) { - // Uses 2 here because app fields were introduced in 5 + // Uses 5 here because app fields were introduced in 5 if s[name].version > 5 { extra = fmt.Sprintf("LogicSigVersion >= %d.", s[name].version) } diff --git a/data/transactions/logic/fields_string.go b/data/transactions/logic/fields_string.go index 653bb38d1b..82abacb941 100644 --- a/data/transactions/logic/fields_string.go +++ b/data/transactions/logic/fields_string.go @@ -66,12 +66,16 @@ func _() { _ = x[LocalNumByteSlice-55] _ = x[ExtraProgramPages-56] _ = x[Nonparticipation-57] - _ = x[invalidTxnField-58] + _ = x[Logs-58] + _ = x[NumLogs-59] + _ = x[CreatedAssetID-60] + _ = x[CreatedApplicationID-61] + _ = x[invalidTxnField-62] } -const _TxnField_name = "SenderFeeFirstValidFirstValidTimeLastValidNoteLeaseReceiverAmountCloseRemainderToVotePKSelectionPKVoteFirstVoteLastVoteKeyDilutionTypeTypeEnumXferAssetAssetAmountAssetSenderAssetReceiverAssetCloseToGroupIndexTxIDApplicationIDOnCompletionApplicationArgsNumAppArgsAccountsNumAccountsApprovalProgramClearStateProgramRekeyToConfigAssetConfigAssetTotalConfigAssetDecimalsConfigAssetDefaultFrozenConfigAssetUnitNameConfigAssetNameConfigAssetURLConfigAssetMetadataHashConfigAssetManagerConfigAssetReserveConfigAssetFreezeConfigAssetClawbackFreezeAssetFreezeAssetAccountFreezeAssetFrozenAssetsNumAssetsApplicationsNumApplicationsGlobalNumUintGlobalNumByteSliceLocalNumUintLocalNumByteSliceExtraProgramPagesNonparticipationinvalidTxnField" +const _TxnField_name = "SenderFeeFirstValidFirstValidTimeLastValidNoteLeaseReceiverAmountCloseRemainderToVotePKSelectionPKVoteFirstVoteLastVoteKeyDilutionTypeTypeEnumXferAssetAssetAmountAssetSenderAssetReceiverAssetCloseToGroupIndexTxIDApplicationIDOnCompletionApplicationArgsNumAppArgsAccountsNumAccountsApprovalProgramClearStateProgramRekeyToConfigAssetConfigAssetTotalConfigAssetDecimalsConfigAssetDefaultFrozenConfigAssetUnitNameConfigAssetNameConfigAssetURLConfigAssetMetadataHashConfigAssetManagerConfigAssetReserveConfigAssetFreezeConfigAssetClawbackFreezeAssetFreezeAssetAccountFreezeAssetFrozenAssetsNumAssetsApplicationsNumApplicationsGlobalNumUintGlobalNumByteSliceLocalNumUintLocalNumByteSliceExtraProgramPagesNonparticipationLogsNumLogsCreatedAssetIDCreatedApplicationIDinvalidTxnField" -var _TxnField_index = [...]uint16{0, 6, 9, 19, 33, 42, 46, 51, 59, 65, 81, 87, 98, 107, 115, 130, 134, 142, 151, 162, 173, 186, 198, 208, 212, 225, 237, 252, 262, 270, 281, 296, 313, 320, 331, 347, 366, 390, 409, 424, 438, 461, 479, 497, 514, 533, 544, 562, 579, 585, 594, 606, 621, 634, 652, 664, 681, 698, 714, 729} +var _TxnField_index = [...]uint16{0, 6, 9, 19, 33, 42, 46, 51, 59, 65, 81, 87, 98, 107, 115, 130, 134, 142, 151, 162, 173, 186, 198, 208, 212, 225, 237, 252, 262, 270, 281, 296, 313, 320, 331, 347, 366, 390, 409, 424, 438, 461, 479, 497, 514, 533, 544, 562, 579, 585, 594, 606, 621, 634, 652, 664, 681, 698, 714, 718, 725, 739, 759, 774} func (i TxnField) String() string { if i < 0 || i >= TxnField(len(_TxnField_index)-1) { diff --git a/data/transactions/logic/opcodes.go b/data/transactions/logic/opcodes.go index 8848e93b83..d5aa5c2e38 100644 --- a/data/transactions/logic/opcodes.go +++ b/data/transactions/logic/opcodes.go @@ -312,11 +312,13 @@ var OpSpecs = []OpSpec{ // AVM "effects" {0xb0, "log", opLog, asmDefault, disDefault, oneBytes, nil, 5, runModeApplication, opDefault}, - {0xb1, "tx_begin", opTxBegin, asmDefault, disDefault, nil, nil, 5, runModeApplication, opDefault}, - {0xb2, "tx_field", opTxField, asmTxField, disTxField, oneAny, nil, 5, runModeApplication, stacky(typeTxField, "f")}, - {0xb3, "tx_submit", opTxSubmit, asmDefault, disDefault, nil, nil, 5, runModeApplication, opDefault}, + {0xb1, "itxn_begin", opTxBegin, asmDefault, disDefault, nil, nil, 5, runModeApplication, opDefault}, + {0xb2, "itxn_field", opTxField, asmTxField, disTxField, oneAny, nil, 5, runModeApplication, stacky(typeTxField, "f")}, + {0xb3, "itxn_submit", opTxSubmit, asmDefault, disDefault, nil, nil, 5, runModeApplication, opDefault}, + {0xb4, "itxn", opItxn, asmItxn, disTxn, nil, oneAny, 5, runModeApplication, immediates("f")}, + {0xb5, "itxna", opItxna, asmItxna, disTxna, nil, oneAny, 5, runModeApplication, immediates("f", "i")}, - // Dynamically indexing into LogicSigs + // Dynamic indexing {0xc0, "txnas", opTxnas, assembleTxnas, disTxn, oneInt, oneAny, 5, modeAny, immediates("f")}, {0xc1, "gtxnas", opGtxnas, assembleGtxnas, disGtxn, oneInt, oneAny, 5, modeAny, immediates("t", "f")}, {0xc2, "gtxnsas", opGtxnsas, assembleGtxnsas, disTxn, twoInts, oneAny, 5, modeAny, immediates("f")}, diff --git a/data/transactions/logictest/ledger.go b/data/transactions/logictest/ledger.go index e7e2ec3d69..5d75b210fc 100644 --- a/data/transactions/logictest/ledger.go +++ b/data/transactions/logictest/ledger.go @@ -140,6 +140,20 @@ func (l *Ledger) NewAsset(creator basics.Address, assetID basics.AssetIndex, par l.balances[creator] = br } +// freshID gets a new creatable ID that isn't in use +func (l *Ledger) freshID() uint64 { + for try := l.appID + 1; true; try++ { + if _, ok := l.assets[basics.AssetIndex(try)]; ok { + continue + } + if _, ok := l.applications[basics.AppIndex(try)]; ok { + continue + } + return uint64(try) + } + panic("wow") +} + // NewHolding sets the ASA balance of a given account. func (l *Ledger) NewHolding(addr basics.Address, assetID uint64, amount uint64, frozen bool) { br, ok := l.balances[addr] @@ -635,6 +649,44 @@ func (l *Ledger) axfer(from basics.Address, xfer transactions.AssetTransferTxnFi return nil } +func (l *Ledger) acfg(from basics.Address, cfg transactions.AssetConfigTxnFields) (transactions.ApplyData, error) { + if cfg.ConfigAsset == 0 { + aid := basics.AssetIndex(l.freshID()) + l.NewAsset(from, aid, cfg.AssetParams) + return transactions.ApplyData{ConfigAsset: aid}, nil + } + // This is just a mock. We don't check all the rules about + // not setting fields that have been zeroed. Nor do we keep + // anything from before. + l.assets[cfg.ConfigAsset] = asaParams{ + Creator: from, + AssetParams: cfg.AssetParams, + } + return transactions.ApplyData{}, nil +} + +func (l *Ledger) afrz(from basics.Address, frz transactions.AssetFreezeTxnFields) error { + aid := frz.FreezeAsset + params, ok := l.assets[aid] + if !ok { + return fmt.Errorf("Asset (%d) does not exist", aid) + } + if params.Freeze != from { + return fmt.Errorf("Asset (%d) can not be frozen by %s", aid, from) + } + br, ok := l.balances[frz.FreezeAccount] + if !ok { + return fmt.Errorf("%s does not hold anything", from) + } + holding, ok := br.holdings[aid] + if !ok { + return fmt.Errorf("%s does not hold Asset (%d)", from, aid) + } + holding.Frozen = frz.AssetFrozen + br.holdings[aid] = holding + return nil +} + /* It's gross to reimplement this here, rather than have a way to use a ledger that's backed by our mock, but uses the "real" code (cowRoundState which implements Balances), as a better test. To @@ -659,6 +711,10 @@ func (l *Ledger) Perform(txn *transactions.Transaction, spec transactions.Specia err = l.pay(txn.Sender, txn.PaymentTxnFields) case protocol.AssetTransferTx: err = l.axfer(txn.Sender, txn.AssetTransferTxnFields) + case protocol.AssetConfigTx: + ad, err = l.acfg(txn.Sender, txn.AssetConfigTxnFields) + case protocol.AssetFreezeTx: + err = l.afrz(txn.Sender, txn.AssetFreezeTxnFields) default: err = fmt.Errorf("%s txn in AVM", txn.Type) } diff --git a/data/transactions/msgp_gen.go b/data/transactions/msgp_gen.go index b46a5694da..009de07b5b 100644 --- a/data/transactions/msgp_gen.go +++ b/data/transactions/msgp_gen.go @@ -773,32 +773,40 @@ func (z *ApplicationCallTxnFields) MsgIsZero() bool { func (z *ApplyData) MarshalMsg(b []byte) (o []byte) { o = msgp.Require(b, z.Msgsize()) // omitempty: check for empty values - zb0001Len := uint32(6) - var zb0001Mask uint8 /* 7 bits */ + zb0001Len := uint32(8) + var zb0001Mask uint16 /* 9 bits */ if (*z).AssetClosingAmount == 0 { zb0001Len-- zb0001Mask |= 0x2 } - if (*z).ClosingAmount.MsgIsZero() { + if (*z).ApplicationID.MsgIsZero() { zb0001Len-- zb0001Mask |= 0x4 } - if (*z).EvalDelta.MsgIsZero() { + if (*z).ClosingAmount.MsgIsZero() { zb0001Len-- zb0001Mask |= 0x8 } - if (*z).CloseRewards.MsgIsZero() { + if (*z).ConfigAsset.MsgIsZero() { zb0001Len-- zb0001Mask |= 0x10 } - if (*z).ReceiverRewards.MsgIsZero() { + if (*z).EvalDelta.MsgIsZero() { zb0001Len-- zb0001Mask |= 0x20 } - if (*z).SenderRewards.MsgIsZero() { + if (*z).CloseRewards.MsgIsZero() { zb0001Len-- zb0001Mask |= 0x40 } + if (*z).ReceiverRewards.MsgIsZero() { + zb0001Len-- + zb0001Mask |= 0x80 + } + if (*z).SenderRewards.MsgIsZero() { + zb0001Len-- + zb0001Mask |= 0x100 + } // variable map header, size zb0001Len o = append(o, 0x80|uint8(zb0001Len)) if zb0001Len != 0 { @@ -808,26 +816,36 @@ func (z *ApplyData) MarshalMsg(b []byte) (o []byte) { o = msgp.AppendUint64(o, (*z).AssetClosingAmount) } if (zb0001Mask & 0x4) == 0 { // if not empty + // string "apid" + o = append(o, 0xa4, 0x61, 0x70, 0x69, 0x64) + o = (*z).ApplicationID.MarshalMsg(o) + } + if (zb0001Mask & 0x8) == 0 { // if not empty // string "ca" o = append(o, 0xa2, 0x63, 0x61) o = (*z).ClosingAmount.MarshalMsg(o) } - if (zb0001Mask & 0x8) == 0 { // if not empty + if (zb0001Mask & 0x10) == 0 { // if not empty + // string "caid" + o = append(o, 0xa4, 0x63, 0x61, 0x69, 0x64) + o = (*z).ConfigAsset.MarshalMsg(o) + } + if (zb0001Mask & 0x20) == 0 { // if not empty // string "dt" o = append(o, 0xa2, 0x64, 0x74) o = (*z).EvalDelta.MarshalMsg(o) } - if (zb0001Mask & 0x10) == 0 { // if not empty + if (zb0001Mask & 0x40) == 0 { // if not empty // string "rc" o = append(o, 0xa2, 0x72, 0x63) o = (*z).CloseRewards.MarshalMsg(o) } - if (zb0001Mask & 0x20) == 0 { // if not empty + if (zb0001Mask & 0x80) == 0 { // if not empty // string "rr" o = append(o, 0xa2, 0x72, 0x72) o = (*z).ReceiverRewards.MarshalMsg(o) } - if (zb0001Mask & 0x40) == 0 { // if not empty + if (zb0001Mask & 0x100) == 0 { // if not empty // string "rs" o = append(o, 0xa2, 0x72, 0x73) o = (*z).SenderRewards.MarshalMsg(o) @@ -902,6 +920,22 @@ func (z *ApplyData) UnmarshalMsg(bts []byte) (o []byte, err error) { return } } + if zb0001 > 0 { + zb0001-- + bts, err = (*z).ConfigAsset.UnmarshalMsg(bts) + if err != nil { + err = msgp.WrapError(err, "struct-from-array", "ConfigAsset") + return + } + } + if zb0001 > 0 { + zb0001-- + bts, err = (*z).ApplicationID.UnmarshalMsg(bts) + if err != nil { + err = msgp.WrapError(err, "struct-from-array", "ApplicationID") + return + } + } if zb0001 > 0 { err = msgp.ErrTooManyArrayFields(zb0001) if err != nil { @@ -961,6 +995,18 @@ func (z *ApplyData) UnmarshalMsg(bts []byte) (o []byte, err error) { err = msgp.WrapError(err, "EvalDelta") return } + case "caid": + bts, err = (*z).ConfigAsset.UnmarshalMsg(bts) + if err != nil { + err = msgp.WrapError(err, "ConfigAsset") + return + } + case "apid": + bts, err = (*z).ApplicationID.UnmarshalMsg(bts) + if err != nil { + err = msgp.WrapError(err, "ApplicationID") + return + } default: err = msgp.ErrNoField(string(field)) if err != nil { @@ -981,13 +1027,13 @@ func (_ *ApplyData) CanUnmarshalMsg(z interface{}) bool { // Msgsize returns an upper bound estimate of the number of bytes occupied by the serialized message func (z *ApplyData) Msgsize() (s int) { - s = 1 + 3 + (*z).ClosingAmount.Msgsize() + 4 + msgp.Uint64Size + 3 + (*z).SenderRewards.Msgsize() + 3 + (*z).ReceiverRewards.Msgsize() + 3 + (*z).CloseRewards.Msgsize() + 3 + (*z).EvalDelta.Msgsize() + s = 1 + 3 + (*z).ClosingAmount.Msgsize() + 4 + msgp.Uint64Size + 3 + (*z).SenderRewards.Msgsize() + 3 + (*z).ReceiverRewards.Msgsize() + 3 + (*z).CloseRewards.Msgsize() + 3 + (*z).EvalDelta.Msgsize() + 5 + (*z).ConfigAsset.Msgsize() + 5 + (*z).ApplicationID.Msgsize() return } // MsgIsZero returns whether this is a zero value func (z *ApplyData) MsgIsZero() bool { - return ((*z).ClosingAmount.MsgIsZero()) && ((*z).AssetClosingAmount == 0) && ((*z).SenderRewards.MsgIsZero()) && ((*z).ReceiverRewards.MsgIsZero()) && ((*z).CloseRewards.MsgIsZero()) && ((*z).EvalDelta.MsgIsZero()) + return ((*z).ClosingAmount.MsgIsZero()) && ((*z).AssetClosingAmount == 0) && ((*z).SenderRewards.MsgIsZero()) && ((*z).ReceiverRewards.MsgIsZero()) && ((*z).CloseRewards.MsgIsZero()) && ((*z).EvalDelta.MsgIsZero()) && ((*z).ConfigAsset.MsgIsZero()) && ((*z).ApplicationID.MsgIsZero()) } // MarshalMsg implements msgp.Marshaler @@ -3320,60 +3366,68 @@ func (z *SignedTxn) MsgIsZero() bool { func (z *SignedTxnInBlock) MarshalMsg(b []byte) (o []byte) { o = msgp.Require(b, z.Msgsize()) // omitempty: check for empty values - zb0001Len := uint32(13) - var zb0001Mask uint32 /* 17 bits */ + zb0001Len := uint32(15) + var zb0001Mask uint32 /* 19 bits */ if (*z).SignedTxnWithAD.ApplyData.AssetClosingAmount == 0 { zb0001Len-- zb0001Mask |= 0x10 } - if (*z).SignedTxnWithAD.ApplyData.ClosingAmount.MsgIsZero() { + if (*z).SignedTxnWithAD.ApplyData.ApplicationID.MsgIsZero() { zb0001Len-- zb0001Mask |= 0x20 } - if (*z).SignedTxnWithAD.ApplyData.EvalDelta.MsgIsZero() { + if (*z).SignedTxnWithAD.ApplyData.ClosingAmount.MsgIsZero() { zb0001Len-- zb0001Mask |= 0x40 } - if (*z).HasGenesisHash == false { + if (*z).SignedTxnWithAD.ApplyData.ConfigAsset.MsgIsZero() { zb0001Len-- zb0001Mask |= 0x80 } - if (*z).HasGenesisID == false { + if (*z).SignedTxnWithAD.ApplyData.EvalDelta.MsgIsZero() { zb0001Len-- zb0001Mask |= 0x100 } - if (*z).SignedTxnWithAD.SignedTxn.Lsig.MsgIsZero() { + if (*z).HasGenesisHash == false { zb0001Len-- zb0001Mask |= 0x200 } - if (*z).SignedTxnWithAD.SignedTxn.Msig.MsgIsZero() { + if (*z).HasGenesisID == false { zb0001Len-- zb0001Mask |= 0x400 } - if (*z).SignedTxnWithAD.ApplyData.CloseRewards.MsgIsZero() { + if (*z).SignedTxnWithAD.SignedTxn.Lsig.MsgIsZero() { zb0001Len-- zb0001Mask |= 0x800 } - if (*z).SignedTxnWithAD.ApplyData.ReceiverRewards.MsgIsZero() { + if (*z).SignedTxnWithAD.SignedTxn.Msig.MsgIsZero() { zb0001Len-- zb0001Mask |= 0x1000 } - if (*z).SignedTxnWithAD.ApplyData.SenderRewards.MsgIsZero() { + if (*z).SignedTxnWithAD.ApplyData.CloseRewards.MsgIsZero() { zb0001Len-- zb0001Mask |= 0x2000 } - if (*z).SignedTxnWithAD.SignedTxn.AuthAddr.MsgIsZero() { + if (*z).SignedTxnWithAD.ApplyData.ReceiverRewards.MsgIsZero() { zb0001Len-- zb0001Mask |= 0x4000 } - if (*z).SignedTxnWithAD.SignedTxn.Sig.MsgIsZero() { + if (*z).SignedTxnWithAD.ApplyData.SenderRewards.MsgIsZero() { zb0001Len-- zb0001Mask |= 0x8000 } - if (*z).SignedTxnWithAD.SignedTxn.Txn.MsgIsZero() { + if (*z).SignedTxnWithAD.SignedTxn.AuthAddr.MsgIsZero() { zb0001Len-- zb0001Mask |= 0x10000 } + if (*z).SignedTxnWithAD.SignedTxn.Sig.MsgIsZero() { + zb0001Len-- + zb0001Mask |= 0x20000 + } + if (*z).SignedTxnWithAD.SignedTxn.Txn.MsgIsZero() { + zb0001Len-- + zb0001Mask |= 0x40000 + } // variable map header, size zb0001Len o = append(o, 0x80|uint8(zb0001Len)) if zb0001Len != 0 { @@ -3383,61 +3437,71 @@ func (z *SignedTxnInBlock) MarshalMsg(b []byte) (o []byte) { o = msgp.AppendUint64(o, (*z).SignedTxnWithAD.ApplyData.AssetClosingAmount) } if (zb0001Mask & 0x20) == 0 { // if not empty + // string "apid" + o = append(o, 0xa4, 0x61, 0x70, 0x69, 0x64) + o = (*z).SignedTxnWithAD.ApplyData.ApplicationID.MarshalMsg(o) + } + if (zb0001Mask & 0x40) == 0 { // if not empty // string "ca" o = append(o, 0xa2, 0x63, 0x61) o = (*z).SignedTxnWithAD.ApplyData.ClosingAmount.MarshalMsg(o) } - if (zb0001Mask & 0x40) == 0 { // if not empty + if (zb0001Mask & 0x80) == 0 { // if not empty + // string "caid" + o = append(o, 0xa4, 0x63, 0x61, 0x69, 0x64) + o = (*z).SignedTxnWithAD.ApplyData.ConfigAsset.MarshalMsg(o) + } + if (zb0001Mask & 0x100) == 0 { // if not empty // string "dt" o = append(o, 0xa2, 0x64, 0x74) o = (*z).SignedTxnWithAD.ApplyData.EvalDelta.MarshalMsg(o) } - if (zb0001Mask & 0x80) == 0 { // if not empty + if (zb0001Mask & 0x200) == 0 { // if not empty // string "hgh" o = append(o, 0xa3, 0x68, 0x67, 0x68) o = msgp.AppendBool(o, (*z).HasGenesisHash) } - if (zb0001Mask & 0x100) == 0 { // if not empty + if (zb0001Mask & 0x400) == 0 { // if not empty // string "hgi" o = append(o, 0xa3, 0x68, 0x67, 0x69) o = msgp.AppendBool(o, (*z).HasGenesisID) } - if (zb0001Mask & 0x200) == 0 { // if not empty + if (zb0001Mask & 0x800) == 0 { // if not empty // string "lsig" o = append(o, 0xa4, 0x6c, 0x73, 0x69, 0x67) o = (*z).SignedTxnWithAD.SignedTxn.Lsig.MarshalMsg(o) } - if (zb0001Mask & 0x400) == 0 { // if not empty + if (zb0001Mask & 0x1000) == 0 { // if not empty // string "msig" o = append(o, 0xa4, 0x6d, 0x73, 0x69, 0x67) o = (*z).SignedTxnWithAD.SignedTxn.Msig.MarshalMsg(o) } - if (zb0001Mask & 0x800) == 0 { // if not empty + if (zb0001Mask & 0x2000) == 0 { // if not empty // string "rc" o = append(o, 0xa2, 0x72, 0x63) o = (*z).SignedTxnWithAD.ApplyData.CloseRewards.MarshalMsg(o) } - if (zb0001Mask & 0x1000) == 0 { // if not empty + if (zb0001Mask & 0x4000) == 0 { // if not empty // string "rr" o = append(o, 0xa2, 0x72, 0x72) o = (*z).SignedTxnWithAD.ApplyData.ReceiverRewards.MarshalMsg(o) } - if (zb0001Mask & 0x2000) == 0 { // if not empty + if (zb0001Mask & 0x8000) == 0 { // if not empty // string "rs" o = append(o, 0xa2, 0x72, 0x73) o = (*z).SignedTxnWithAD.ApplyData.SenderRewards.MarshalMsg(o) } - if (zb0001Mask & 0x4000) == 0 { // if not empty + if (zb0001Mask & 0x10000) == 0 { // if not empty // string "sgnr" o = append(o, 0xa4, 0x73, 0x67, 0x6e, 0x72) o = (*z).SignedTxnWithAD.SignedTxn.AuthAddr.MarshalMsg(o) } - if (zb0001Mask & 0x8000) == 0 { // if not empty + if (zb0001Mask & 0x20000) == 0 { // if not empty // string "sig" o = append(o, 0xa3, 0x73, 0x69, 0x67) o = (*z).SignedTxnWithAD.SignedTxn.Sig.MarshalMsg(o) } - if (zb0001Mask & 0x10000) == 0 { // if not empty + if (zb0001Mask & 0x40000) == 0 { // if not empty // string "txn" o = append(o, 0xa3, 0x74, 0x78, 0x6e) o = (*z).SignedTxnWithAD.SignedTxn.Txn.MarshalMsg(o) @@ -3552,6 +3616,22 @@ func (z *SignedTxnInBlock) UnmarshalMsg(bts []byte) (o []byte, err error) { return } } + if zb0001 > 0 { + zb0001-- + bts, err = (*z).SignedTxnWithAD.ApplyData.ConfigAsset.UnmarshalMsg(bts) + if err != nil { + err = msgp.WrapError(err, "struct-from-array", "ConfigAsset") + return + } + } + if zb0001 > 0 { + zb0001-- + bts, err = (*z).SignedTxnWithAD.ApplyData.ApplicationID.UnmarshalMsg(bts) + if err != nil { + err = msgp.WrapError(err, "struct-from-array", "ApplicationID") + return + } + } if zb0001 > 0 { zb0001-- (*z).HasGenesisID, bts, err = msgp.ReadBoolBytes(bts) @@ -3657,6 +3737,18 @@ func (z *SignedTxnInBlock) UnmarshalMsg(bts []byte) (o []byte, err error) { err = msgp.WrapError(err, "EvalDelta") return } + case "caid": + bts, err = (*z).SignedTxnWithAD.ApplyData.ConfigAsset.UnmarshalMsg(bts) + if err != nil { + err = msgp.WrapError(err, "ConfigAsset") + return + } + case "apid": + bts, err = (*z).SignedTxnWithAD.ApplyData.ApplicationID.UnmarshalMsg(bts) + if err != nil { + err = msgp.WrapError(err, "ApplicationID") + return + } case "hgi": (*z).HasGenesisID, bts, err = msgp.ReadBoolBytes(bts) if err != nil { @@ -3689,65 +3781,73 @@ func (_ *SignedTxnInBlock) CanUnmarshalMsg(z interface{}) bool { // Msgsize returns an upper bound estimate of the number of bytes occupied by the serialized message func (z *SignedTxnInBlock) Msgsize() (s int) { - s = 1 + 4 + (*z).SignedTxnWithAD.SignedTxn.Sig.Msgsize() + 5 + (*z).SignedTxnWithAD.SignedTxn.Msig.Msgsize() + 5 + (*z).SignedTxnWithAD.SignedTxn.Lsig.Msgsize() + 4 + (*z).SignedTxnWithAD.SignedTxn.Txn.Msgsize() + 5 + (*z).SignedTxnWithAD.SignedTxn.AuthAddr.Msgsize() + 3 + (*z).SignedTxnWithAD.ApplyData.ClosingAmount.Msgsize() + 4 + msgp.Uint64Size + 3 + (*z).SignedTxnWithAD.ApplyData.SenderRewards.Msgsize() + 3 + (*z).SignedTxnWithAD.ApplyData.ReceiverRewards.Msgsize() + 3 + (*z).SignedTxnWithAD.ApplyData.CloseRewards.Msgsize() + 3 + (*z).SignedTxnWithAD.ApplyData.EvalDelta.Msgsize() + 4 + msgp.BoolSize + 4 + msgp.BoolSize + s = 1 + 4 + (*z).SignedTxnWithAD.SignedTxn.Sig.Msgsize() + 5 + (*z).SignedTxnWithAD.SignedTxn.Msig.Msgsize() + 5 + (*z).SignedTxnWithAD.SignedTxn.Lsig.Msgsize() + 4 + (*z).SignedTxnWithAD.SignedTxn.Txn.Msgsize() + 5 + (*z).SignedTxnWithAD.SignedTxn.AuthAddr.Msgsize() + 3 + (*z).SignedTxnWithAD.ApplyData.ClosingAmount.Msgsize() + 4 + msgp.Uint64Size + 3 + (*z).SignedTxnWithAD.ApplyData.SenderRewards.Msgsize() + 3 + (*z).SignedTxnWithAD.ApplyData.ReceiverRewards.Msgsize() + 3 + (*z).SignedTxnWithAD.ApplyData.CloseRewards.Msgsize() + 3 + (*z).SignedTxnWithAD.ApplyData.EvalDelta.Msgsize() + 5 + (*z).SignedTxnWithAD.ApplyData.ConfigAsset.Msgsize() + 5 + (*z).SignedTxnWithAD.ApplyData.ApplicationID.Msgsize() + 4 + msgp.BoolSize + 4 + msgp.BoolSize return } // MsgIsZero returns whether this is a zero value func (z *SignedTxnInBlock) MsgIsZero() bool { - return ((*z).SignedTxnWithAD.SignedTxn.Sig.MsgIsZero()) && ((*z).SignedTxnWithAD.SignedTxn.Msig.MsgIsZero()) && ((*z).SignedTxnWithAD.SignedTxn.Lsig.MsgIsZero()) && ((*z).SignedTxnWithAD.SignedTxn.Txn.MsgIsZero()) && ((*z).SignedTxnWithAD.SignedTxn.AuthAddr.MsgIsZero()) && ((*z).SignedTxnWithAD.ApplyData.ClosingAmount.MsgIsZero()) && ((*z).SignedTxnWithAD.ApplyData.AssetClosingAmount == 0) && ((*z).SignedTxnWithAD.ApplyData.SenderRewards.MsgIsZero()) && ((*z).SignedTxnWithAD.ApplyData.ReceiverRewards.MsgIsZero()) && ((*z).SignedTxnWithAD.ApplyData.CloseRewards.MsgIsZero()) && ((*z).SignedTxnWithAD.ApplyData.EvalDelta.MsgIsZero()) && ((*z).HasGenesisID == false) && ((*z).HasGenesisHash == false) + return ((*z).SignedTxnWithAD.SignedTxn.Sig.MsgIsZero()) && ((*z).SignedTxnWithAD.SignedTxn.Msig.MsgIsZero()) && ((*z).SignedTxnWithAD.SignedTxn.Lsig.MsgIsZero()) && ((*z).SignedTxnWithAD.SignedTxn.Txn.MsgIsZero()) && ((*z).SignedTxnWithAD.SignedTxn.AuthAddr.MsgIsZero()) && ((*z).SignedTxnWithAD.ApplyData.ClosingAmount.MsgIsZero()) && ((*z).SignedTxnWithAD.ApplyData.AssetClosingAmount == 0) && ((*z).SignedTxnWithAD.ApplyData.SenderRewards.MsgIsZero()) && ((*z).SignedTxnWithAD.ApplyData.ReceiverRewards.MsgIsZero()) && ((*z).SignedTxnWithAD.ApplyData.CloseRewards.MsgIsZero()) && ((*z).SignedTxnWithAD.ApplyData.EvalDelta.MsgIsZero()) && ((*z).SignedTxnWithAD.ApplyData.ConfigAsset.MsgIsZero()) && ((*z).SignedTxnWithAD.ApplyData.ApplicationID.MsgIsZero()) && ((*z).HasGenesisID == false) && ((*z).HasGenesisHash == false) } // MarshalMsg implements msgp.Marshaler func (z *SignedTxnWithAD) MarshalMsg(b []byte) (o []byte) { o = msgp.Require(b, z.Msgsize()) // omitempty: check for empty values - zb0001Len := uint32(11) - var zb0001Mask uint16 /* 14 bits */ + zb0001Len := uint32(13) + var zb0001Mask uint16 /* 16 bits */ if (*z).ApplyData.AssetClosingAmount == 0 { zb0001Len-- zb0001Mask |= 0x8 } - if (*z).ApplyData.ClosingAmount.MsgIsZero() { + if (*z).ApplyData.ApplicationID.MsgIsZero() { zb0001Len-- zb0001Mask |= 0x10 } - if (*z).ApplyData.EvalDelta.MsgIsZero() { + if (*z).ApplyData.ClosingAmount.MsgIsZero() { zb0001Len-- zb0001Mask |= 0x20 } - if (*z).SignedTxn.Lsig.MsgIsZero() { + if (*z).ApplyData.ConfigAsset.MsgIsZero() { zb0001Len-- zb0001Mask |= 0x40 } - if (*z).SignedTxn.Msig.MsgIsZero() { + if (*z).ApplyData.EvalDelta.MsgIsZero() { zb0001Len-- zb0001Mask |= 0x80 } - if (*z).ApplyData.CloseRewards.MsgIsZero() { + if (*z).SignedTxn.Lsig.MsgIsZero() { zb0001Len-- zb0001Mask |= 0x100 } - if (*z).ApplyData.ReceiverRewards.MsgIsZero() { + if (*z).SignedTxn.Msig.MsgIsZero() { zb0001Len-- zb0001Mask |= 0x200 } - if (*z).ApplyData.SenderRewards.MsgIsZero() { + if (*z).ApplyData.CloseRewards.MsgIsZero() { zb0001Len-- zb0001Mask |= 0x400 } - if (*z).SignedTxn.AuthAddr.MsgIsZero() { + if (*z).ApplyData.ReceiverRewards.MsgIsZero() { zb0001Len-- zb0001Mask |= 0x800 } - if (*z).SignedTxn.Sig.MsgIsZero() { + if (*z).ApplyData.SenderRewards.MsgIsZero() { zb0001Len-- zb0001Mask |= 0x1000 } - if (*z).SignedTxn.Txn.MsgIsZero() { + if (*z).SignedTxn.AuthAddr.MsgIsZero() { zb0001Len-- zb0001Mask |= 0x2000 } + if (*z).SignedTxn.Sig.MsgIsZero() { + zb0001Len-- + zb0001Mask |= 0x4000 + } + if (*z).SignedTxn.Txn.MsgIsZero() { + zb0001Len-- + zb0001Mask |= 0x8000 + } // variable map header, size zb0001Len o = append(o, 0x80|uint8(zb0001Len)) if zb0001Len != 0 { @@ -3757,51 +3857,61 @@ func (z *SignedTxnWithAD) MarshalMsg(b []byte) (o []byte) { o = msgp.AppendUint64(o, (*z).ApplyData.AssetClosingAmount) } if (zb0001Mask & 0x10) == 0 { // if not empty + // string "apid" + o = append(o, 0xa4, 0x61, 0x70, 0x69, 0x64) + o = (*z).ApplyData.ApplicationID.MarshalMsg(o) + } + if (zb0001Mask & 0x20) == 0 { // if not empty // string "ca" o = append(o, 0xa2, 0x63, 0x61) o = (*z).ApplyData.ClosingAmount.MarshalMsg(o) } - if (zb0001Mask & 0x20) == 0 { // if not empty + if (zb0001Mask & 0x40) == 0 { // if not empty + // string "caid" + o = append(o, 0xa4, 0x63, 0x61, 0x69, 0x64) + o = (*z).ApplyData.ConfigAsset.MarshalMsg(o) + } + if (zb0001Mask & 0x80) == 0 { // if not empty // string "dt" o = append(o, 0xa2, 0x64, 0x74) o = (*z).ApplyData.EvalDelta.MarshalMsg(o) } - if (zb0001Mask & 0x40) == 0 { // if not empty + if (zb0001Mask & 0x100) == 0 { // if not empty // string "lsig" o = append(o, 0xa4, 0x6c, 0x73, 0x69, 0x67) o = (*z).SignedTxn.Lsig.MarshalMsg(o) } - if (zb0001Mask & 0x80) == 0 { // if not empty + if (zb0001Mask & 0x200) == 0 { // if not empty // string "msig" o = append(o, 0xa4, 0x6d, 0x73, 0x69, 0x67) o = (*z).SignedTxn.Msig.MarshalMsg(o) } - if (zb0001Mask & 0x100) == 0 { // if not empty + if (zb0001Mask & 0x400) == 0 { // if not empty // string "rc" o = append(o, 0xa2, 0x72, 0x63) o = (*z).ApplyData.CloseRewards.MarshalMsg(o) } - if (zb0001Mask & 0x200) == 0 { // if not empty + if (zb0001Mask & 0x800) == 0 { // if not empty // string "rr" o = append(o, 0xa2, 0x72, 0x72) o = (*z).ApplyData.ReceiverRewards.MarshalMsg(o) } - if (zb0001Mask & 0x400) == 0 { // if not empty + if (zb0001Mask & 0x1000) == 0 { // if not empty // string "rs" o = append(o, 0xa2, 0x72, 0x73) o = (*z).ApplyData.SenderRewards.MarshalMsg(o) } - if (zb0001Mask & 0x800) == 0 { // if not empty + if (zb0001Mask & 0x2000) == 0 { // if not empty // string "sgnr" o = append(o, 0xa4, 0x73, 0x67, 0x6e, 0x72) o = (*z).SignedTxn.AuthAddr.MarshalMsg(o) } - if (zb0001Mask & 0x1000) == 0 { // if not empty + if (zb0001Mask & 0x4000) == 0 { // if not empty // string "sig" o = append(o, 0xa3, 0x73, 0x69, 0x67) o = (*z).SignedTxn.Sig.MarshalMsg(o) } - if (zb0001Mask & 0x2000) == 0 { // if not empty + if (zb0001Mask & 0x8000) == 0 { // if not empty // string "txn" o = append(o, 0xa3, 0x74, 0x78, 0x6e) o = (*z).SignedTxn.Txn.MarshalMsg(o) @@ -3916,6 +4026,22 @@ func (z *SignedTxnWithAD) UnmarshalMsg(bts []byte) (o []byte, err error) { return } } + if zb0001 > 0 { + zb0001-- + bts, err = (*z).ApplyData.ConfigAsset.UnmarshalMsg(bts) + if err != nil { + err = msgp.WrapError(err, "struct-from-array", "ConfigAsset") + return + } + } + if zb0001 > 0 { + zb0001-- + bts, err = (*z).ApplyData.ApplicationID.UnmarshalMsg(bts) + if err != nil { + err = msgp.WrapError(err, "struct-from-array", "ApplicationID") + return + } + } if zb0001 > 0 { err = msgp.ErrTooManyArrayFields(zb0001) if err != nil { @@ -4005,6 +4131,18 @@ func (z *SignedTxnWithAD) UnmarshalMsg(bts []byte) (o []byte, err error) { err = msgp.WrapError(err, "EvalDelta") return } + case "caid": + bts, err = (*z).ApplyData.ConfigAsset.UnmarshalMsg(bts) + if err != nil { + err = msgp.WrapError(err, "ConfigAsset") + return + } + case "apid": + bts, err = (*z).ApplyData.ApplicationID.UnmarshalMsg(bts) + if err != nil { + err = msgp.WrapError(err, "ApplicationID") + return + } default: err = msgp.ErrNoField(string(field)) if err != nil { @@ -4025,13 +4163,13 @@ func (_ *SignedTxnWithAD) CanUnmarshalMsg(z interface{}) bool { // Msgsize returns an upper bound estimate of the number of bytes occupied by the serialized message func (z *SignedTxnWithAD) Msgsize() (s int) { - s = 1 + 4 + (*z).SignedTxn.Sig.Msgsize() + 5 + (*z).SignedTxn.Msig.Msgsize() + 5 + (*z).SignedTxn.Lsig.Msgsize() + 4 + (*z).SignedTxn.Txn.Msgsize() + 5 + (*z).SignedTxn.AuthAddr.Msgsize() + 3 + (*z).ApplyData.ClosingAmount.Msgsize() + 4 + msgp.Uint64Size + 3 + (*z).ApplyData.SenderRewards.Msgsize() + 3 + (*z).ApplyData.ReceiverRewards.Msgsize() + 3 + (*z).ApplyData.CloseRewards.Msgsize() + 3 + (*z).ApplyData.EvalDelta.Msgsize() + s = 1 + 4 + (*z).SignedTxn.Sig.Msgsize() + 5 + (*z).SignedTxn.Msig.Msgsize() + 5 + (*z).SignedTxn.Lsig.Msgsize() + 4 + (*z).SignedTxn.Txn.Msgsize() + 5 + (*z).SignedTxn.AuthAddr.Msgsize() + 3 + (*z).ApplyData.ClosingAmount.Msgsize() + 4 + msgp.Uint64Size + 3 + (*z).ApplyData.SenderRewards.Msgsize() + 3 + (*z).ApplyData.ReceiverRewards.Msgsize() + 3 + (*z).ApplyData.CloseRewards.Msgsize() + 3 + (*z).ApplyData.EvalDelta.Msgsize() + 5 + (*z).ApplyData.ConfigAsset.Msgsize() + 5 + (*z).ApplyData.ApplicationID.Msgsize() return } // MsgIsZero returns whether this is a zero value func (z *SignedTxnWithAD) MsgIsZero() bool { - return ((*z).SignedTxn.Sig.MsgIsZero()) && ((*z).SignedTxn.Msig.MsgIsZero()) && ((*z).SignedTxn.Lsig.MsgIsZero()) && ((*z).SignedTxn.Txn.MsgIsZero()) && ((*z).SignedTxn.AuthAddr.MsgIsZero()) && ((*z).ApplyData.ClosingAmount.MsgIsZero()) && ((*z).ApplyData.AssetClosingAmount == 0) && ((*z).ApplyData.SenderRewards.MsgIsZero()) && ((*z).ApplyData.ReceiverRewards.MsgIsZero()) && ((*z).ApplyData.CloseRewards.MsgIsZero()) && ((*z).ApplyData.EvalDelta.MsgIsZero()) + return ((*z).SignedTxn.Sig.MsgIsZero()) && ((*z).SignedTxn.Msig.MsgIsZero()) && ((*z).SignedTxn.Lsig.MsgIsZero()) && ((*z).SignedTxn.Txn.MsgIsZero()) && ((*z).SignedTxn.AuthAddr.MsgIsZero()) && ((*z).ApplyData.ClosingAmount.MsgIsZero()) && ((*z).ApplyData.AssetClosingAmount == 0) && ((*z).ApplyData.SenderRewards.MsgIsZero()) && ((*z).ApplyData.ReceiverRewards.MsgIsZero()) && ((*z).ApplyData.CloseRewards.MsgIsZero()) && ((*z).ApplyData.EvalDelta.MsgIsZero()) && ((*z).ApplyData.ConfigAsset.MsgIsZero()) && ((*z).ApplyData.ApplicationID.MsgIsZero()) } // MarshalMsg implements msgp.Marshaler diff --git a/data/transactions/transaction.go b/data/transactions/transaction.go index 923e794785..fb356bb04d 100644 --- a/data/transactions/transaction.go +++ b/data/transactions/transaction.go @@ -113,6 +113,12 @@ type ApplyData struct { ReceiverRewards basics.MicroAlgos `codec:"rr"` CloseRewards basics.MicroAlgos `codec:"rc"` EvalDelta EvalDelta `codec:"dt"` + + // If asa or app is being created, the id used. Else 0. + // Names chosen to match naming the corresponding txn. + // These are populated on when MaxInnerTransactions > 0 (TEAL 5) + ConfigAsset basics.AssetIndex `codec:"caid"` + ApplicationID basics.AppIndex `codec:"apid"` } // Equal returns true if two ApplyDatas are equal, ignoring nilness equality on @@ -133,6 +139,12 @@ func (ad ApplyData) Equal(o ApplyData) bool { if ad.CloseRewards != o.CloseRewards { return false } + if ad.ConfigAsset != o.ConfigAsset { + return false + } + if ad.ApplicationID != o.ApplicationID { + return false + } if !ad.EvalDelta.Equal(o.EvalDelta) { return false } diff --git a/data/transactions/verify/txn.go b/data/transactions/verify/txn.go index 671b9a347c..13a07b328a 100644 --- a/data/transactions/verify/txn.go +++ b/data/transactions/verify/txn.go @@ -41,14 +41,14 @@ var logicErrTotal = metrics.MakeCounter(metrics.MetricName{Name: "algod_ledger_l // When doing so, it attempts to break these into smaller "worksets" where each workset takes about 2ms of execution time in order // to avoid context switching overhead while providing good validation cancelation responsiveness. Each one of these worksets is // "populated" with roughly txnPerWorksetThreshold transactions. ( note that the real evaluation time is unknown, but benchmarks -// showen that these are realistic numbers ) +// show that these are realistic numbers ) const txnPerWorksetThreshold = 32 // When the PaysetGroups is generating worksets, it enqueues up to concurrentWorksets entries to the execution pool. This serves several // purposes : // - if the verification task need to be aborted, there are only concurrentWorksets entries that are currently redundant on the execution pool queue. // - that number of concurrent tasks would not get beyond the capacity of the execution pool back buffer. -// - if we were to "redundently" execute all these during context cancelation, we would spent at most 2ms * 16 = 32ms time. +// - if we were to "redundantly" execute all these during context cancelation, we would spent at most 2ms * 16 = 32ms time. // - it allows us to linearly scan the input, and process elements only once we're going to queue them into the pool. const concurrentWorksets = 16 diff --git a/ledger/applications.go b/ledger/applications.go index e8ce84ad31..9b3cb27b47 100644 --- a/ledger/applications.go +++ b/ledger/applications.go @@ -45,6 +45,8 @@ type cowForLogicLedger interface { round() basics.Round prevTimestamp() int64 allocated(addr basics.Address, aidx basics.AppIndex, global bool) (bool, error) + txnCounter() uint64 + incTxnCount() } func newLogicLedger(cow cowForLogicLedger, aidx basics.AppIndex) (*logicLedger, error) { @@ -271,11 +273,26 @@ func (al *logicLedger) Perform(tx *transactions.Transaction, spec transactions.S return ad, err } + // compared to eval.transaction() it may seem strange that we + // increment the transaction count *before* transaction + // processing, rather than after. But we need to account for the + // fact that our outer transaction has not yet incremented their + // count (in addTx()), so we need to increment ahead of use, so we + // don't use the same index. If eval.transaction() incremented + // ahead of processing, we'd have to do ours *after* so that we'd + // use the next id. So either way, this would seem backwards at + // first glance. + al.cow.incTxnCount() + switch tx.Type { case protocol.PaymentTx: err = apply.Payment(tx.PaymentTxnFields, tx.Header, balances, spec, &ad) case protocol.AssetTransferTx: err = apply.AssetTransfer(tx.AssetTransferTxnFields, tx.Header, balances, spec, &ad) + case protocol.AssetConfigTx: + err = apply.AssetConfig(tx.AssetConfigTxnFields, tx.Header, balances, spec, &ad, al.cow.txnCounter()) + case protocol.AssetFreezeTx: + err = apply.AssetFreeze(tx.AssetFreezeTxnFields, tx.Header, balances, spec, &ad) default: err = fmt.Errorf("%s tx in AVM", tx.Type) } diff --git a/ledger/applications_test.go b/ledger/applications_test.go index 43bdca4317..83b7471ecb 100644 --- a/ledger/applications_test.go +++ b/ledger/applications_test.go @@ -61,6 +61,7 @@ type mockCowForLogicLedger struct { brs map[basics.Address]basics.AccountData stores map[storeLocator]basics.TealKeyValue tcs map[int]basics.CreatableIndex + txc uint64 } func (c *mockCowForLogicLedger) Get(addr basics.Address, withPendingRewards bool) (basics.AccountData, error) { @@ -126,6 +127,14 @@ func (c *mockCowForLogicLedger) allocated(addr basics.Address, aidx basics.AppIn return found, nil } +func (c *mockCowForLogicLedger) incTxnCount() { + c.txc++ +} + +func (c *mockCowForLogicLedger) txnCounter() uint64 { + return c.txc +} + func newCowMock(creatables []modsData) *mockCowForLogicLedger { var m mockCowForLogicLedger m.cr = make(map[creatableLocator]basics.Address, len(creatables)) diff --git a/ledger/apply/application.go b/ledger/apply/application.go index fab18a925c..2ff5733030 100644 --- a/ledger/apply/application.go +++ b/ledger/apply/application.go @@ -342,6 +342,11 @@ func ApplicationCall(ac transactions.ApplicationCallTxnFields, header transactio if err != nil { return } + // No separate config for activating storage in AD because + // inner transactions can't be turned on without this change. + if balances.ConsensusParams().MaxInnerTransactions > 0 { + ad.ApplicationID = appIdx + } } // Fetch the application parameters, if they exist diff --git a/ledger/apply/asset.go b/ledger/apply/asset.go index 1fe3c6faca..0796cb8f7f 100644 --- a/ledger/apply/asset.go +++ b/ledger/apply/asset.go @@ -100,6 +100,13 @@ func AssetConfig(cc transactions.AssetConfigTxnFields, header transactions.Heade return err } + // Record the index used. No separate config for activating + // storage in AD because inner transactions can't be turned on + // without this change. + if balances.ConsensusParams().MaxInnerTransactions > 0 { + ad.ConfigAsset = newidx + } + // Tell the cow what asset we created err = balances.AllocateAsset(header.Sender, newidx, true) if err != nil { diff --git a/ledger/apptxn_test.go b/ledger/apptxn_test.go index b93604ca46..845bb54c48 100644 --- a/ledger/apptxn_test.go +++ b/ledger/apptxn_test.go @@ -49,38 +49,42 @@ func TestPayAction(t *testing.T) { Type: "appl", Sender: addrs[0], ApprovalProgram: main(` - tx_begin + itxn_begin int pay - tx_field TypeEnum + itxn_field TypeEnum int 5000 - tx_field Amount + itxn_field Amount txn Accounts 1 - tx_field Receiver - tx_submit + itxn_field Receiver + itxn_submit `), } + ai := basics.AppIndex(1) fund := txntest.Txn{ Type: "pay", Sender: addrs[0], - Receiver: basics.AppIndex(1).Address(), + Receiver: ai.Address(), Amount: 200000, // account min balance, plus fees } payout1 := txntest.Txn{ Type: "appl", Sender: addrs[1], - ApplicationID: basics.AppIndex(1), + ApplicationID: ai, Accounts: []basics.Address{addrs[1]}, // pay self } eval := l.nextBlock(t) eval.txns(t, &create, &fund, &payout1) - l.endBlock(t, eval) + vb := l.endBlock(t, eval) + + // AD contains expected appIndex + require.Equal(t, ai, vb.blk.Payset[0].ApplyData.ApplicationID) ad0 := l.micros(t, addrs[0]) ad1 := l.micros(t, addrs[1]) - app := l.micros(t, basics.AppIndex(1).Address()) + app := l.micros(t, ai.Address()) // create(1000) and fund(1000 + 200000) require.Equal(t, uint64(202000), genBalances.Balances[addrs[0]].MicroAlgos.Raw-ad0) @@ -99,7 +103,7 @@ func TestPayAction(t *testing.T) { payout2 := txntest.Txn{ Type: "appl", Sender: addrs[1], - ApplicationID: basics.AppIndex(1), + ApplicationID: ai, Accounts: []basics.Address{addrs[2]}, // pay other } eval.txn(t, &payout2) @@ -128,7 +132,7 @@ func TestPayAction(t *testing.T) { ad1 = l.micros(t, addrs[1]) ad2 := l.micros(t, addrs[2]) - app = l.micros(t, basics.AppIndex(1).Address()) + app = l.micros(t, ai.Address()) // paid 5000, in first payout (only), but paid 1000 fee in each payout txn require.Equal(t, rewards+3000, ad1-genBalances.Balances[addrs[1]].MicroAlgos.Raw) @@ -143,13 +147,13 @@ func TestPayAction(t *testing.T) { tenkalgos := txntest.Txn{ Type: "pay", Sender: addrs[0], - Receiver: basics.AppIndex(1).Address(), + Receiver: ai.Address(), Amount: 10 * 1000 * 1000000, // account min balance, plus fees } eval = l.nextBlock(t) eval.txn(t, &tenkalgos) l.endBlock(t, eval) - beforepay := l.micros(t, basics.AppIndex(1).Address()) + beforepay := l.micros(t, ai.Address()) // Build up Residue in RewardsState so it's ready to pay again for i := 1; i < 10; i++ { @@ -160,7 +164,7 @@ func TestPayAction(t *testing.T) { eval.txn(t, payout2.Noted("2")) l.endBlock(t, eval) - afterpay := l.micros(t, basics.AppIndex(1).Address()) + afterpay := l.micros(t, ai.Address()) payInBlock = eval.block.Payset[0] inners = payInBlock.ApplyData.EvalDelta.InnerTxns @@ -196,11 +200,11 @@ func TestAxferAction(t *testing.T) { Type: "appl", Sender: addrs[0], ApprovalProgram: main(` - tx_begin + itxn_begin int axfer - tx_field TypeEnum + itxn_field TypeEnum txn Assets 0 - tx_field XferAsset + itxn_field XferAsset txn ApplicationArgs 0 byte "optin" @@ -208,7 +212,7 @@ func TestAxferAction(t *testing.T) { bz withdraw // let AssetAmount default to 0 global CurrentApplicationAddress - tx_field AssetReceiver + itxn_field AssetReceiver b submit withdraw: txn ApplicationArgs 0 @@ -216,24 +220,25 @@ withdraw: == bz noclose txn Accounts 1 - tx_field AssetCloseTo + itxn_field AssetCloseTo b skipamount noclose: int 10000 - tx_field AssetAmount + itxn_field AssetAmount skipamount: txn Accounts 1 - tx_field AssetReceiver -submit: tx_submit + itxn_field AssetReceiver +submit: itxn_submit `), } eval := l.nextBlock(t) eval.txns(t, &asa, &app) - l.endBlock(t, eval) + vb := l.endBlock(t, eval) - // Would be better to pull these out of block, or at least check them. asaIndex := basics.AssetIndex(1) + require.Equal(t, asaIndex, vb.blk.Payset[0].ApplyData.ConfigAsset) appIndex := basics.AppIndex(2) + require.Equal(t, appIndex, vb.blk.Payset[1].ApplyData.ApplicationID) fund := txntest.Txn{ Type: "pay", @@ -372,7 +377,6 @@ func TestClawbackAction(t *testing.T) { l := newTestLedger(t, genBalances) defer l.Close() - // Would be better to pull these out of block, or at least check them. asaIndex := basics.AssetIndex(1) appIndex := basics.AppIndex(2) @@ -393,24 +397,24 @@ func TestClawbackAction(t *testing.T) { Type: "appl", Sender: addrs[0], ApprovalProgram: main(` - tx_begin + itxn_begin int axfer - tx_field TypeEnum + itxn_field TypeEnum txn Assets 0 - tx_field XferAsset + itxn_field XferAsset txn Accounts 1 - tx_field AssetSender + itxn_field AssetSender txn Accounts 2 - tx_field AssetReceiver + itxn_field AssetReceiver int 1000 - tx_field AssetAmount + itxn_field AssetAmount - tx_submit + itxn_submit `), } @@ -422,7 +426,10 @@ func TestClawbackAction(t *testing.T) { } eval := l.nextBlock(t) eval.txns(t, &asa, &app, &optin) - l.endBlock(t, eval) + vb := l.endBlock(t, eval) + + require.Equal(t, asaIndex, vb.blk.Payset[0].ApplyData.ConfigAsset) + require.Equal(t, appIndex, vb.blk.Payset[1].ApplyData.ApplicationID) bystander := addrs[2] // Has no authority of its own overpay := txntest.Txn{ @@ -459,23 +466,23 @@ func TestRekeyAction(t *testing.T) { Type: "appl", Sender: addrs[5], ApprovalProgram: main(` - tx_begin + itxn_begin int pay - tx_field TypeEnum + itxn_field TypeEnum int 5000 - tx_field Amount + itxn_field Amount txn Accounts 1 - tx_field Sender + itxn_field Sender txn Accounts 2 - tx_field Receiver + itxn_field Receiver txn NumAccounts int 3 == bz skipclose txn Accounts 3 - tx_field CloseRemainderTo + itxn_field CloseRemainderTo skipclose: - tx_submit + itxn_submit `), } @@ -564,35 +571,35 @@ func TestRekeyActionCloseAccount(t *testing.T) { Sender: addrs[5], ApprovalProgram: main(` // close account 1 - tx_begin + itxn_begin int pay - tx_field TypeEnum + itxn_field TypeEnum txn Accounts 1 - tx_field Sender + itxn_field Sender txn Accounts 2 - tx_field CloseRemainderTo - tx_submit + itxn_field CloseRemainderTo + itxn_submit // reopen account 1 - tx_begin + itxn_begin int pay - tx_field TypeEnum + itxn_field TypeEnum int 5000 - tx_field Amount + itxn_field Amount txn Accounts 1 - tx_field Receiver - tx_submit + itxn_field Receiver + itxn_submit // send from account 1 again (should fail because closing an account erases rekeying) - tx_begin + itxn_begin int pay - tx_field TypeEnum + itxn_field TypeEnum int 1 - tx_field Amount + itxn_field Amount txn Accounts 1 - tx_field Sender + itxn_field Sender txn Accounts 2 - tx_field Receiver - tx_submit + itxn_field Receiver + itxn_submit `), } @@ -624,3 +631,284 @@ func TestRekeyActionCloseAccount(t *testing.T) { eval.txn(t, &useacct, "unauthorized") l.endBlock(t, eval) } + +// TestDuplicatePayAction shows two pays with same parameters can be done as inner tarnsactions +func TestDuplicatePayAction(t *testing.T) { + partitiontest.PartitionTest(t) + + genBalances, addrs, _ := newTestGenesis() + l := newTestLedger(t, genBalances) + defer l.Close() + + appIndex := basics.AppIndex(1) + create := txntest.Txn{ + Type: "appl", + Sender: addrs[0], + ApprovalProgram: main(` + itxn_begin + int pay + itxn_field TypeEnum + int 5000 + itxn_field Amount + txn Accounts 1 + itxn_field Receiver + itxn_submit + itxn_begin + int pay + itxn_field TypeEnum + int 5000 + itxn_field Amount + txn Accounts 1 + itxn_field Receiver + itxn_submit +`), + } + + fund := txntest.Txn{ + Type: "pay", + Sender: addrs[0], + Receiver: appIndex.Address(), + Amount: 200000, // account min balance, plus fees + } + + paytwice := txntest.Txn{ + Type: "appl", + Sender: addrs[1], + ApplicationID: appIndex, + Accounts: []basics.Address{addrs[1]}, // pay self + } + + eval := l.nextBlock(t) + eval.txns(t, &create, &fund, &paytwice, create.Noted("in same block")) + vb := l.endBlock(t, eval) + + require.Equal(t, appIndex, vb.blk.Payset[0].ApplyData.ApplicationID) + require.Equal(t, 4, len(vb.blk.Payset)) + // create=1, fund=2, payTwice=3,4,5 + require.Equal(t, basics.AppIndex(6), vb.blk.Payset[3].ApplyData.ApplicationID) + + ad0 := l.micros(t, addrs[0]) + ad1 := l.micros(t, addrs[1]) + app := l.micros(t, appIndex.Address()) + + // create(1000) and fund(1000 + 200000), extra create (1000) + require.Equal(t, 203000, int(genBalances.Balances[addrs[0]].MicroAlgos.Raw-ad0)) + // paid 10000, but 1000 fee on tx + require.Equal(t, 9000, int(ad1-genBalances.Balances[addrs[1]].MicroAlgos.Raw)) + // app still has 188000 (paid out 10000, and paid 2 x fee to do it) + require.Equal(t, 188000, int(app)) + + // Now create another app, and see if it gets the index we expect. + eval = l.nextBlock(t) + eval.txns(t, create.Noted("again")) + vb = l.endBlock(t, eval) + + // create=1, fund=2, payTwice=3,4,5, insameblock=6 + require.Equal(t, basics.AppIndex(7), vb.blk.Payset[0].ApplyData.ApplicationID) +} + +// TestInnerTxCount ensures that inner transactions increment the TxnCounter +func TestInnerTxnCount(t *testing.T) { + partitiontest.PartitionTest(t) + + genBalances, addrs, _ := newTestGenesis() + l := newTestLedger(t, genBalances) + defer l.Close() + + create := txntest.Txn{ + Type: "appl", + Sender: addrs[0], + ApprovalProgram: main(` + itxn_begin + int pay + itxn_field TypeEnum + int 5000 + itxn_field Amount + txn Accounts 1 + itxn_field Receiver + itxn_submit +`), + } + + fund := txntest.Txn{ + Type: "pay", + Sender: addrs[0], + Receiver: basics.AppIndex(1).Address(), + Amount: 200000, // account min balance, plus fees + } + + payout1 := txntest.Txn{ + Type: "appl", + Sender: addrs[1], + ApplicationID: basics.AppIndex(1), + Accounts: []basics.Address{addrs[1]}, // pay self + } + + eval := l.nextBlock(t) + eval.txns(t, &create, &fund) + vb := l.endBlock(t, eval) + require.Equal(t, 2, int(vb.blk.TxnCounter)) + + eval = l.nextBlock(t) + eval.txns(t, &payout1) + vb = l.endBlock(t, eval) + require.Equal(t, 4, int(vb.blk.TxnCounter)) +} + +// TestAcfgAction ensures assets can be created and configured in teal +func TestAcfgAction(t *testing.T) { + partitiontest.PartitionTest(t) + + genBalances, addrs, _ := newTestGenesis() + l := newTestLedger(t, genBalances) + defer l.Close() + + appIndex := basics.AppIndex(1) + app := txntest.Txn{ + Type: "appl", + Sender: addrs[0], + ApprovalProgram: main(` + itxn_begin + int acfg + itxn_field TypeEnum + + txn ApplicationArgs 0 + byte "create" + == + bz manager + int 1000000 + itxn_field ConfigAssetTotal + int 3 + itxn_field ConfigAssetDecimals + byte "oz" + itxn_field ConfigAssetUnitName + byte "Gold" + itxn_field ConfigAssetName + byte "https://gold.rush/" + itxn_field ConfigAssetURL + global CurrentApplicationAddress + dup + dup2 + itxn_field ConfigAssetManager + itxn_field ConfigAssetReserve + itxn_field ConfigAssetFreeze + itxn_field ConfigAssetClawback + b submit +manager: + txn ApplicationArgs 0 + byte "manager" + == + bz reserve +reserve: + txn ApplicationArgs 0 + byte "reserve" + == + bz freeze +freeze: + txn ApplicationArgs 0 + byte "freeze" + == + bz clawback +clawback: + txn ApplicationArgs 0 + byte "manager" + == +submit: itxn_submit +`), + } + + fund := txntest.Txn{ + Type: "pay", + Sender: addrs[0], + Receiver: appIndex.Address(), + Amount: 200_000, // exactly account min balance + one asset + } + + eval := l.nextBlock(t) + eval.txns(t, &app, &fund) + l.endBlock(t, eval) + + createAsa := txntest.Txn{ + Type: "appl", + Sender: addrs[1], + ApplicationID: appIndex, + ApplicationArgs: [][]byte{[]byte("create")}, + } + + eval = l.nextBlock(t) + // Can't create an asset if you have exactly 200,000 and need to pay fee + eval.txn(t, &createAsa, "balance 199000 below min 200000") + // fund it some more and try again + eval.txns(t, fund.Noted("more!"), &createAsa) + vb := l.endBlock(t, eval) + + asaIndex := vb.blk.Payset[1].EvalDelta.InnerTxns[0].ConfigAsset + require.Equal(t, basics.AssetIndex(5), asaIndex) + + asaParams, err := l.asaParams(t, basics.AssetIndex(5)) + require.NoError(t, err) + + require.Equal(t, 1_000_000, int(asaParams.Total)) + require.Equal(t, 3, int(asaParams.Decimals)) + require.Equal(t, "oz", asaParams.UnitName) + require.Equal(t, "Gold", asaParams.AssetName) + require.Equal(t, "https://gold.rush/", asaParams.URL) + +} + +// TestAsaDuringInit ensures an ASA can be made while initilizing an +// app. In practice, this is impossible, because you would not be +// able to prefund the account - you don't know the app id. But here +// we can know, so it helps exercise txncounter changes. +func TestAsaDuringInit(t *testing.T) { + partitiontest.PartitionTest(t) + + genBalances, addrs, _ := newTestGenesis() + l := newTestLedger(t, genBalances) + defer l.Close() + + appIndex := basics.AppIndex(2) + prefund := txntest.Txn{ + Type: "pay", + Sender: addrs[0], + Receiver: appIndex.Address(), + Amount: 300000, // plenty for min balances, fees + } + + app := txntest.Txn{ + Type: "appl", + Sender: addrs[0], + ApprovalProgram: ` + itxn_begin + int acfg + itxn_field TypeEnum + int 1000000 + itxn_field ConfigAssetTotal + byte "oz" + itxn_field ConfigAssetUnitName + byte "Gold" + itxn_field ConfigAssetName + itxn_submit + itxn CreatedAssetID + int 3 + == + itxn CreatedApplicationID + int 0 + == + && + itxn NumLogs + int 0 + == + && +`, + } + + eval := l.nextBlock(t) + eval.txns(t, &prefund, &app) + vb := l.endBlock(t, eval) + + require.Equal(t, appIndex, vb.blk.Payset[1].ApplicationID) + + asaIndex := vb.blk.Payset[1].EvalDelta.InnerTxns[0].ConfigAsset + require.Equal(t, basics.AssetIndex(3), asaIndex) +} diff --git a/ledger/cow.go b/ledger/cow.go index e618a59196..1234c191b4 100644 --- a/ledger/cow.go +++ b/ledger/cow.go @@ -57,6 +57,10 @@ type roundCowState struct { proto config.ConsensusParams mods ledgercore.StateDelta + // count of transactions. Formerly, we used len(cb.mods), but that + // does not count inner transactions. + txnCount uint64 + // storage deltas populated as side effects of AppCall transaction // 1. Opt-in/Close actions (see Allocate/Deallocate) // 2. Stateful TEAL evaluation (see SetKey/DelKey) @@ -180,7 +184,7 @@ func (cb *roundCowState) checkDup(firstValid, lastValid basics.Round, txid trans } func (cb *roundCowState) txnCounter() uint64 { - return cb.lookupParent.txnCounter() + uint64(len(cb.mods.Txids)) + return cb.lookupParent.txnCounter() + cb.txnCount } func (cb *roundCowState) compactCertNext() basics.Round { @@ -198,8 +202,13 @@ func (cb *roundCowState) trackCreatable(creatableIndex basics.CreatableIndex) { cb.trackedCreatables[cb.groupIdx] = creatableIndex } +func (cb *roundCowState) incTxnCount() { + cb.txnCount++ +} + func (cb *roundCowState) addTx(txn transactions.Transaction, txid transactions.Txid) { cb.mods.Txids[txid] = txn.LastValid + cb.incTxnCount() if txn.Lease != [32]byte{} { cb.mods.Txleases[ledgercore.Txlease{Sender: txn.Sender, Lease: txn.Lease}] = txn.LastValid } @@ -242,6 +251,8 @@ func (cb *roundCowState) commitToParent() { for txid, lv := range cb.mods.Txids { cb.commitParent.mods.Txids[txid] = lv } + cb.commitParent.txnCount += cb.txnCount + for txl, expires := range cb.mods.Txleases { cb.commitParent.mods.Txleases[txl] = expires } diff --git a/ledger/eval.go b/ledger/eval.go index 533525e8e4..5730a4f223 100644 --- a/ledger/eval.go +++ b/ledger/eval.go @@ -559,8 +559,8 @@ func (eval *BlockEvaluator) workaroundOverspentRewards(rewardPoolBalance basics. return } -// TxnCounter returns the number of transactions that have been added to the block evaluator so far. -func (eval *BlockEvaluator) TxnCounter() int { +// PaySetSize returns the number of top-level transactions that have been added to the block evaluator so far. +func (eval *BlockEvaluator) PaySetSize() int { return len(eval.block.Payset) } @@ -904,6 +904,13 @@ func (eval *BlockEvaluator) transaction(txn transactions.SignedTxn, evalParams * } } + // We are not allowing InnerTxns to have InnerTxns yet. Error if that happens. + for _, itx := range applyData.EvalDelta.InnerTxns { + if len(itx.ApplyData.EvalDelta.InnerTxns) > 0 { + return fmt.Errorf("inner transaction has inner transactions %v", itx) + } + } + // Remember this txn cow.addTx(txn.Txn, txid) @@ -1283,7 +1290,7 @@ transactionGroupLoop: return eval.state.deltas(), nil } -// loadedTransactionGroup is a helper struct to allow asyncronious loading of the account data needed by the transaction groups +// loadedTransactionGroup is a helper struct to allow asynchronous loading of the account data needed by the transaction groups type loadedTransactionGroup struct { // group is the transaction group group []transactions.SignedTxnWithAD diff --git a/ledger/eval_test.go b/ledger/eval_test.go index cdaf600bdb..865ea209e9 100644 --- a/ledger/eval_test.go +++ b/ledger/eval_test.go @@ -1441,6 +1441,21 @@ func (ledger *Ledger) asa(t testing.TB, addr basics.Address, asset basics.AssetI return 0, false } +// asaParams gets the asset params for a given asa index +func (ledger *Ledger) asaParams(t testing.TB, asset basics.AssetIndex) (basics.AssetParams, error) { + creator, ok, err := ledger.GetCreator(basics.CreatableIndex(asset), basics.AssetCreatable) + if err != nil { + return basics.AssetParams{}, err + } + if !ok { + return basics.AssetParams{}, fmt.Errorf("no asset (%d)", asset) + } + if params, ok := ledger.lookup(t, creator).AssetParams[asset]; ok { + return params, nil + } + return basics.AssetParams{}, fmt.Errorf("bad lookup (%d)", asset) +} + func (eval *BlockEvaluator) fillDefaults(txn *txntest.Txn) { if txn.GenesisHash.IsZero() { txn.GenesisHash = eval.genesisHash diff --git a/test/e2e-go/restAPI/restClient_test.go b/test/e2e-go/restAPI/restClient_test.go index 329b50c183..49d05ae4a3 100644 --- a/test/e2e-go/restAPI/restClient_test.go +++ b/test/e2e-go/restAPI/restClient_test.go @@ -18,6 +18,7 @@ package restapi import ( "context" + "encoding/hex" "errors" "flag" "math" @@ -1058,3 +1059,121 @@ return } } + +func TestPendingTransactionInfoInnerTxnAssetCreate(t *testing.T) { + partitiontest.PartitionTest(t) + + a := require.New(fixtures.SynchronizedTest(t)) + var localFixture fixtures.RestClientFixture + localFixture.Setup(t, filepath.Join("nettemplates", "TwoNodes50EachFuture.json")) + defer localFixture.Shutdown() + + testClient := localFixture.LibGoalClient + + testClient.WaitForRound(1) + + testClient.SetAPIVersionAffinity(algodclient.APIVersionV2, kmdclient.APIVersionV1) + + wh, err := testClient.GetUnencryptedWalletHandle() + a.NoError(err) + addresses, err := testClient.ListAddresses(wh) + a.NoError(err) + _, someAddress := getMaxBalAddr(t, testClient, addresses) + if someAddress == "" { + t.Error("no addr with funds") + } + a.NoError(err) + + prog := `#pragma version 5 +txn ApplicationID +bz end +itxn_begin +int acfg +itxn_field TypeEnum +int 1000000 +itxn_field ConfigAssetTotal +int 3 +itxn_field ConfigAssetDecimals +byte "oz" +itxn_field ConfigAssetUnitName +byte "Gold" +itxn_field ConfigAssetName +byte "https://gold.rush/" +itxn_field ConfigAssetURL +byte 0x67f0cd61653bd34316160bc3f5cd3763c85b114d50d38e1f4e72c3b994411e7b +itxn_field ConfigAssetMetadataHash +itxn_submit +end: +int 1 +return +` + ops, err := logic.AssembleString(prog) + approv := ops.Program + ops, err = logic.AssembleString("#pragma version 5 \nint 1") + clst := ops.Program + + gl := basics.StateSchema{} + lc := basics.StateSchema{} + + // create app + appCreateTxn, err := testClient.MakeUnsignedApplicationCallTx(0, nil, nil, nil, nil, transactions.NoOpOC, approv, clst, gl, lc, 0) + a.NoError(err) + appCreateTxn, err = testClient.FillUnsignedTxTemplate(someAddress, 0, 0, 0, appCreateTxn) + a.NoError(err) + appCreateTxID, err := testClient.SignAndBroadcastTransaction(wh, nil, appCreateTxn) + a.NoError(err) + _, err = waitForTransaction(t, testClient, someAddress, appCreateTxID, 30*time.Second) + a.NoError(err) + + // get app ID + submittedAppCreateTxn, err := testClient.PendingTransactionInformationV2(appCreateTxID) + a.NoError(err) + a.NotNil(submittedAppCreateTxn.ApplicationIndex) + createdAppID := basics.AppIndex(*submittedAppCreateTxn.ApplicationIndex) + a.Greater(uint64(createdAppID), uint64(0)) + + // fund app account + appFundTxn, err := testClient.SendPaymentFromWallet(wh, nil, someAddress, createdAppID.Address().String(), 0, 1_000_000, nil, "", 0, 0) + a.NoError(err) + appFundTxID := appFundTxn.ID() + _, err = waitForTransaction(t, testClient, someAddress, appFundTxID.String(), 30*time.Second) + a.NoError(err) + + // call app, which will issue an ASA create inner txn + appCallTxn, err := testClient.MakeUnsignedAppNoOpTx(uint64(createdAppID), nil, nil, nil, nil) + a.NoError(err) + appCallTxn, err = testClient.FillUnsignedTxTemplate(someAddress, 0, 0, 0, appCallTxn) + a.NoError(err) + appCallTxnTxID, err := testClient.SignAndBroadcastTransaction(wh, nil, appCallTxn) + a.NoError(err) + _, err = waitForTransaction(t, testClient, someAddress, appCallTxnTxID, 30*time.Second) + a.NoError(err) + + // verify pending txn info of outer txn + submittedAppCallTxn, err := testClient.PendingTransactionInformationV2(appCallTxnTxID) + a.NoError(err) + a.Nil(submittedAppCallTxn.ApplicationIndex) + a.Nil(submittedAppCallTxn.AssetIndex) + a.NotNil(submittedAppCallTxn.InnerTxns) + a.Len(*submittedAppCallTxn.InnerTxns, 1) + + // verify pending txn info of inner txn + innerTxn := (*submittedAppCallTxn.InnerTxns)[0] + a.Nil(innerTxn.ApplicationIndex) + a.NotNil(innerTxn.AssetIndex) + createdAssetID := *innerTxn.AssetIndex + a.Greater(createdAssetID, uint64(0)) + + createdAssetInfo, err := testClient.AssetInformationV2(createdAssetID) + a.NoError(err) + a.Equal(createdAssetID, createdAssetInfo.Index) + a.Equal(createdAppID.Address().String(), createdAssetInfo.Params.Creator) + a.Equal(uint64(1000000), createdAssetInfo.Params.Total) + a.Equal(uint64(3), createdAssetInfo.Params.Decimals) + a.Equal("oz", *createdAssetInfo.Params.UnitName) + a.Equal("Gold", *createdAssetInfo.Params.Name) + a.Equal("https://gold.rush/", *createdAssetInfo.Params.Url) + expectedMetadata, err := hex.DecodeString("67f0cd61653bd34316160bc3f5cd3763c85b114d50d38e1f4e72c3b994411e7b") + a.NoError(err) + a.Equal(expectedMetadata, *createdAssetInfo.Params.MetadataHash) +} diff --git a/test/scripts/e2e_subs/tealprogs/app-escrow.teal b/test/scripts/e2e_subs/tealprogs/app-escrow.teal index 315f397db6..e742db429b 100644 --- a/test/scripts/e2e_subs/tealprogs/app-escrow.teal +++ b/test/scripts/e2e_subs/tealprogs/app-escrow.teal @@ -126,17 +126,17 @@ not_deposit: - app_local_put - tx_begin + itxn_begin int pay - tx_field TypeEnum + itxn_field TypeEnum txn ApplicationArgs 1 btoi - tx_field Amount + itxn_field Amount txn Sender - tx_field Receiver - tx_submit + itxn_field Receiver + itxn_submit int 1 return