Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve static validation of contract/transaction moves #3341

Merged
merged 5 commits into from
May 15, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions runtime/resource_duplicate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import (
"github.com/onflow/cadence/encoding/json"
. "github.com/onflow/cadence/runtime"
"github.com/onflow/cadence/runtime/common"
"github.com/onflow/cadence/runtime/interpreter"
"github.com/onflow/cadence/runtime/sema"
. "github.com/onflow/cadence/runtime/tests/runtime_utils"
. "github.com/onflow/cadence/runtime/tests/utils"
)
Expand Down Expand Up @@ -204,6 +204,6 @@ func TestRuntimeResourceDuplicationWithContractTransfer(t *testing.T) {
)
RequireError(t, err)

var nonTransferableValueError interpreter.NonTransferableValueError
require.ErrorAs(t, err, &nonTransferableValueError)
var invalidMoveError *sema.InvalidMoveError
require.ErrorAs(t, err, &invalidMoveError)
}
117 changes: 0 additions & 117 deletions runtime/runtime_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10634,123 +10634,6 @@ func TestRuntimeNonPublicAccessModifierInInterface(t *testing.T) {
require.Len(t, conformanceErr.MemberMismatches, 2)
}

func TestRuntimeMoveSelfVariable(t *testing.T) {
SupunS marked this conversation as resolved.
Show resolved Hide resolved

t.Parallel()

t.Run("contract", func(t *testing.T) {
t.Parallel()

contract := []byte(`
access(all) contract Foo {

access(all) fun moveSelf() {
var x = self!
}
}
`)

runtime := NewTestInterpreterRuntimeWithConfig(Config{
AtreeValidationEnabled: false,
})

address := common.MustBytesToAddress([]byte{0x1})

var contractCode []byte

runtimeInterface := &TestRuntimeInterface{
Storage: NewTestLedger(nil, nil),
OnGetSigningAccounts: func() ([]Address, error) {
return []Address{address}, nil
},
OnGetAccountContractCode: func(location common.AddressLocation) ([]byte, error) {
return contractCode, nil
},
OnResolveLocation: NewSingleIdentifierLocationResolver(t),
OnUpdateAccountContractCode: func(_ common.AddressLocation, code []byte) error {
contractCode = code
return nil
},
OnEmitEvent: func(event cadence.Event) error {
return nil
},
}

nextTransactionLocation := NewTransactionLocationGenerator()

// Deploy

deploymentTx := DeploymentTransaction("Foo", contract)
err := runtime.ExecuteTransaction(
Script{
Source: deploymentTx,
},
Context{
Interface: runtimeInterface,
Location: nextTransactionLocation(),
},
)
require.NoError(t, err)

// Execute script

nextScriptLocation := NewScriptLocationGenerator()

script := []byte(fmt.Sprintf(`
import Foo from %[1]s

access(all) fun main(): Void {
Foo.moveSelf()
}`,
address.HexWithPrefix(),
))

_, err = runtime.ExecuteScript(
Script{
Source: script,
},
Context{
Interface: runtimeInterface,
Location: nextScriptLocation(),
},
)

RequireError(t, err)
require.ErrorAs(t, err, &interpreter.NonTransferableValueError{})
})

t.Run("transaction", func(t *testing.T) {
t.Parallel()

script := []byte(`
transaction {
prepare() {
var x = true ? self : self
}
execute {}
}
`)

runtime := NewTestInterpreterRuntime()
runtimeInterface := &TestRuntimeInterface{}

nextTransactionLocation := NewTransactionLocationGenerator()

err := runtime.ExecuteTransaction(
Script{
Source: script,
},
Context{
Interface: runtimeInterface,
Location: nextTransactionLocation(),
},
)

RequireError(t, err)
require.ErrorAs(t, err, &interpreter.NonTransferableValueError{})
})
}

func TestRuntimeContractWithInvalidCapability(t *testing.T) {

t.Parallel()
Expand Down
1 change: 0 additions & 1 deletion runtime/sema/check_array_expression.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,6 @@ func (checker *Checker) VisitArrayExpression(arrayExpression *ast.ArrayExpressio

argumentTypes[i] = valueType

checker.checkVariableMove(element)
checker.checkResourceMoveOperation(element, valueType)
}
}
Expand Down
1 change: 0 additions & 1 deletion runtime/sema/check_assignment.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,6 @@ func (checker *Checker) checkAssignment(
}

checker.enforceViewAssignment(assignment, target)
checker.checkVariableMove(value)

checker.recordResourceInvalidation(
value,
Expand Down
1 change: 0 additions & 1 deletion runtime/sema/check_attach_expression.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@ func (checker *Checker) VisitAttachExpression(expression *ast.AttachExpression)
return InvalidType
}

checker.checkVariableMove(baseExpression)
checker.checkResourceMoveOperation(baseExpression, attachmentType)

// check that the attachment type is a valid attachment,
Expand Down
2 changes: 0 additions & 2 deletions runtime/sema/check_dictionary_expression.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,9 @@ func (checker *Checker) VisitDictionaryExpression(expression *ast.DictionaryExpr
// not combined after both type checks!

entryKeyType := checker.VisitExpression(entry.Key, expression, keyType)
checker.checkVariableMove(entry.Key)
checker.checkResourceMoveOperation(entry.Key, entryKeyType)

entryValueType := checker.VisitExpression(entry.Value, expression, valueType)
checker.checkVariableMove(entry.Value)
checker.checkResourceMoveOperation(entry.Value, entryValueType)

entryTypes[i] = DictionaryEntryType{
Expand Down
41 changes: 41 additions & 0 deletions runtime/sema/check_expression.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,50 @@ func (checker *Checker) VisitIdentifierExpression(expression *ast.IdentifierExpr
checker.Elaboration.SetIdentifierInInvocationType(expression, valueType)
}

checker.checkVariableMove(expression, variable)

return valueType
}

func (checker *Checker) checkVariableMove(identifierExpression *ast.IdentifierExpression, variable *Variable) {

reportMaybeInvalidMove := func(declarationKind common.DeclarationKind) {
// If the parent is member-access or index-access, then it's OK.
// e.g: `v.foo`, `v.bar()`, `v[T]` are OK.
switch parent := checker.parent.(type) {
case *ast.MemberExpression:
// TODO: No need for below check? i.e: should always be true
if parent.Expression == identifierExpression {
return
}
case *ast.IndexExpression:
// Only `v[foo]` is OK, `foo[v]` is not.
if parent.TargetExpression == identifierExpression {
return
}
}

checker.report(
&InvalidMoveError{
Name: variable.Identifier,
DeclarationKind: declarationKind,
Pos: identifierExpression.StartPosition(),
},
)
}

switch ty := variable.Type.(type) {
case *TransactionType:
reportMaybeInvalidMove(common.DeclarationKindTransaction)

case CompositeKindedType:
kind := ty.GetCompositeKind()
if kind == common.CompositeKindContract {
reportMaybeInvalidMove(common.DeclarationKindContract)
}
}
}

func (checker *Checker) checkReferenceValidity(variable *Variable, hasPosition ast.HasPosition) {
typ := UnwrapOptionalType(variable.Type)
if _, ok := typ.(*ReferenceType); !ok {
Expand Down
3 changes: 0 additions & 3 deletions runtime/sema/check_invocation_expression.go
Original file line number Diff line number Diff line change
Expand Up @@ -807,9 +807,6 @@ func (checker *Checker) checkInvocationArgumentParameterTypeCompatibility(
}

func (checker *Checker) checkInvocationArgumentMove(argument ast.Expression, argumentType Type) Type {

checker.checkVariableMove(argument)
checker.checkResourceMoveOperation(argument, argumentType)

return argumentType
}
1 change: 0 additions & 1 deletion runtime/sema/check_return_statement.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,6 @@ func (checker *Checker) VisitReturnStatement(statement *ast.ReturnStatement) (_
return
}

checker.checkVariableMove(statement.Expression)
checker.checkResourceMoveOperation(statement.Expression, valueType)

return
Expand Down
2 changes: 0 additions & 2 deletions runtime/sema/check_variable_declaration.go
Original file line number Diff line number Diff line change
Expand Up @@ -113,8 +113,6 @@ func (checker *Checker) visitVariableDeclarationValues(declaration *ast.Variable
panic(errors.NewUnreachableError())
}

checker.checkVariableMove(declaration.Value)

// If only one value expression is provided, it is invalidated (if it has a resource type)

checker.recordResourceInvalidation(
Expand Down
34 changes: 0 additions & 34 deletions runtime/sema/checker.go
Original file line number Diff line number Diff line change
Expand Up @@ -2300,40 +2300,6 @@ func (checker *Checker) predeclaredMembers(containerType Type) []*Member {
return predeclaredMembers
}

func (checker *Checker) checkVariableMove(expression ast.Expression) {

identifierExpression, ok := expression.(*ast.IdentifierExpression)
if !ok {
return
}

variable := checker.valueActivations.Find(identifierExpression.Identifier.Identifier)
if variable == nil {
return
}

reportInvalidMove := func(declarationKind common.DeclarationKind) {
checker.report(
&InvalidMoveError{
Name: variable.Identifier,
DeclarationKind: declarationKind,
Pos: identifierExpression.StartPosition(),
},
)
}

switch ty := variable.Type.(type) {
case *TransactionType:
reportInvalidMove(common.DeclarationKindTransaction)

case CompositeKindedType:
kind := ty.GetCompositeKind()
if kind == common.CompositeKindContract {
reportInvalidMove(common.DeclarationKindContract)
}
}
}

func (checker *Checker) checkTypeAnnotation(typeAnnotation TypeAnnotation, pos ast.HasPosition) {

switch typeAnnotation.TypeAnnotationState() {
Expand Down
21 changes: 15 additions & 6 deletions runtime/tests/checker/attachments_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1540,9 +1540,12 @@ func TestCheckAttachmentIllegalInit(t *testing.T) {
let t = optContractRef?.Test()
`)

errs := RequireCheckerErrors(t, err, 1)
errs := RequireCheckerErrors(t, err, 2)

assert.IsType(t, &sema.InvalidAttachmentUsageError{}, errs[0])
var invalidMoveError *sema.InvalidMoveError
require.ErrorAs(t, errs[0], &invalidMoveError)

assert.IsType(t, &sema.InvalidAttachmentUsageError{}, errs[1])
})
}

Expand Down Expand Up @@ -1655,9 +1658,12 @@ func TestCheckAttachmentAttachNonAttachment(t *testing.T) {
`,
)

errs := RequireCheckerErrors(t, err, 1)
errs := RequireCheckerErrors(t, err, 2)

var invalidMoveError *sema.InvalidMoveError
require.ErrorAs(t, errs[0], &invalidMoveError)

assert.IsType(t, &sema.NotCallableError{}, errs[0])
assert.IsType(t, &sema.NotCallableError{}, errs[1])
})
}

Expand Down Expand Up @@ -1773,9 +1779,12 @@ func TestCheckAttachmentAttachToNonComposite(t *testing.T) {
`,
)

errs := RequireCheckerErrors(t, err, 1)
errs := RequireCheckerErrors(t, err, 2)

var invalidMoveError *sema.InvalidMoveError
require.ErrorAs(t, errs[0], &invalidMoveError)

assert.IsType(t, &sema.NotCallableError{}, errs[0])
assert.IsType(t, &sema.NotCallableError{}, errs[1])
})

t.Run("attachment", func(t *testing.T) {
Expand Down
Loading
Loading